---
id: BasketDeletedCompleteIntegrationEvent
name: Basket deletion completed
version: 1.0.0
summary: |
Indicates that Basket successfully deleted the submitted basket during
checkout cleanup.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
---
`BasketDeletedCompleteIntegrationEvent` (v1.0.0) signals that [[service|basket-api]] removed a submitted customer basket during post-checkout cleanup. [[service|order-orchestration]] consumes this event to advance the order orchestration saga; it confirms basket deletion only and does not imply order completion.
## Overview
| Property | Value |
| :----------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Shopping |
| **Producer** | [[service\|basket-api]] |
| **Consumer(s)** | [[service\|order-orchestration]] |
| **Protocol / Format** | Kafka + CloudEvents JSON (camelCase payload) |
| **Channel / Topic** | [[channel\|bookworm.{env}.basket.delete-complete]] |
| **Dead-Letter Channel** | None on consumer ([[service\|order-orchestration]] uses Azure Functions Kafka trigger retries and Durable Task Hub diagnostics; [[channel\|bookworm.{env}.basket.dead-letter-queue]] is for [[service\|basket-api]] inbound failures) |
| **Partition Key** | `OrderId` |
| **Delivery / Idempotency Guarantee** | At-least-once delivery; producer deduplicates incoming [[command\|PlaceOrderCommand]] via Redis-backed 24-hour idempotency keyed by `OrderId` |
## Payload Fields & Envelope
### Event Payload
| Name | Type | Required | Constraints | Description |
| :------------- | :--------------------- | :------- | :------------------------------ | :------------------------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | UUIDv7 | Unique identifier for this integration event instance |
| `creationDate` | `string` (`date-time`) | Yes | ISO 8601 UTC timestamp | UTC timestamp when the event was created |
| `orderId` | `string` (`uuid`) | Yes | Valid UUID; Kafka partition key | Identifier of the order whose submitted basket was deleted |
| `basketId` | `string` (`uuid`) | Yes | Valid UUID | Identifier of the Redis basket removed during checkout cleanup |
| `totalMoney` | `number` | Yes | Non-negative monetary amount | Total purchase amount associated with the order |
### CloudEvents Envelope Headers
| Header | Value / Source | Purpose |
| :------------ | :--------------------------------------------------------- | :---------------------------------------------------------- |
| `messagetype` | `BookWorm.Contracts.BasketDeletedCompleteIntegrationEvent` | Explicit message identity for cross-service deserialization |
| `source` | `urn:bookworm:bookworm-basket` | Identifies the producing service |
| `requestid` | Propagated from incoming [[command\|PlaceOrderCommand]] | End-to-end correlation across HTTP and Kafka hops |
## Delivery Guarantees & Error Handling
| Condition | System Behavior | Recovery / Compensation |
| :------------------------------------------------------- | :--------------------------------------------------------------------------------------------------- | :----------------------------------------------------------- |
| Duplicate [[command\|PlaceOrderCommand]] within 24 hours | Producer detects the Redis idempotency key for `OrderId` and re-emits this event without re-deleting | Orchestration handles duplicate external events idempotently |
| Transient broker or consumer error | Retried with cooldown (`50ms`, `250ms`, `1s`) and full jitter | Exhausted messages route to the consumer dead-letter queue |
| Deserialization failure | Routed immediately to the dead-letter queue without retries | Inspect dead-letter payload against contract schema |
## Related Documentation
- [[service|basket-api]] — Producer service contract and Redis storage details.
- [[service|order-orchestration]] — Consumer orchestration service.
- [[channel|bookworm.{env}.basket.delete-complete]] — Kafka channel specification.
- [[event|BasketDeletedFailedIntegrationEvent]] — Companion failure event when Redis deletion returns `false`.
- [[entity|basket]] — Redis basket data model.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "BasketDeletedCompleteIntegrationEvent",
"type": "object",
"additionalProperties": false,
"required": ["id", "creationDate", "orderId", "basketId", "totalMoney"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "Unique identifier assigned by the integration-event building block."
},
"creationDate": {
"type": "string",
"format": "date-time",
"description": "UTC timestamp when the integration event was created."
},
"orderId": {
"type": "string",
"format": "uuid",
"description": "Identifier of the order whose submitted basket was deleted."
},
"basketId": {
"type": "string",
"format": "uuid",
"description": "Identifier of the basket deleted during checkout cleanup."
},
"totalMoney": {
"type": "number",
"format": "double",
"description": "Total purchase amount associated with the order."
}
}
}
---
id: BasketDeletedFailedIntegrationEvent
name: Basket deletion failed
version: 1.0.0
summary: |
Indicates that Basket could not delete the submitted basket during checkout
cleanup.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
---
`BasketDeletedFailedIntegrationEvent` (v1.0.0) signals that [[service|basket-api]] could not delete a submitted customer basket during post-checkout cleanup. [[service|order-orchestration]] consumes this event to trigger compensating failure handling instead of stalling the checkout orchestration.
## Overview
| Property | Value |
| :----------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Shopping |
| **Producer** | [[service\|basket-api]] |
| **Consumer(s)** | [[service\|order-orchestration]] |
| **Protocol / Format** | Kafka + CloudEvents JSON (camelCase payload) |
| **Channel / Topic** | [[channel\|bookworm.{env}.basket.delete-failed]] |
| **Dead-Letter Channel** | None on consumer ([[service\|order-orchestration]] uses Azure Functions Kafka trigger retries and Durable Task Hub diagnostics; [[channel\|bookworm.{env}.basket.dead-letter-queue]] is for [[service\|basket-api]] inbound failures) |
| **Partition Key** | `OrderId` |
| **Delivery / Idempotency Guarantee** | At-least-once delivery; emitted when Redis deletion returns `false` while handling [[command\|PlaceOrderCommand]] |
## Payload Fields & Envelope
### Event Payload
| Name | Type | Required | Constraints | Description |
| :------------- | :--------------------- | :------- | :----------------------------------- | :-------------------------------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | UUIDv7 | Unique identifier for this integration event instance |
| `creationDate` | `string` (`date-time`) | Yes | ISO 8601 UTC timestamp | UTC timestamp when the event was created |
| `orderId` | `string` (`uuid`) | Yes | Valid UUID; Kafka partition key | Identifier of the order whose submitted basket could not be deleted |
| `basketId` | `string` (`uuid`) | Yes | Valid UUID | Identifier of the basket that could not be removed |
| `email` | `string \| null` | No | Email format when non-null; nullable | Customer email used by downstream recovery notifications when present |
| `totalMoney` | `number` | Yes | Non-negative monetary amount | Total purchase amount associated with the order |
:::note
Consumers must handle `email` when it is `null` or omitted and must never interpret `BasketDeletedFailedIntegrationEvent` as a successful cleanup milestone.
:::
### CloudEvents Envelope Headers
| Header | Value / Source | Purpose |
| :------------ | :------------------------------------------------------- | :---------------------------------------------------------- |
| `messagetype` | `BookWorm.Contracts.BasketDeletedFailedIntegrationEvent` | Explicit message identity for cross-service deserialization |
| `source` | `urn:bookworm:bookworm-basket` | Identifies the producing service |
| `requestid` | Propagated from incoming [[command\|PlaceOrderCommand]] | Correlates checkout and recovery logs across services |
## Delivery Guarantees & Error Handling
| Condition | System Behavior | Recovery / Compensation |
| :---------------------------------------------------------- | :--------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------- |
| Redis deletion returns `false` (key missing or not deleted) | Emits `BasketDeletedFailedIntegrationEvent` | [[service\|order-orchestration]] dispatches [[command\|DeleteBasketFailedCommand]] to [[service\|order-api]] |
| Unhandled exception during Redis deletion | Releases the `OrderId` idempotency lock and retries (`50ms`, `250ms`, `1s`, full jitter) | Exhausted messages route to [[channel\|bookworm.{env}.basket.dead-letter-queue]] |
| Deserialization failure | Routed immediately to the dead-letter queue without retries | Inspect dead-letter payload against contract schema |
## Related Documentation
- [[service|basket-api]] — Producer service contract and Redis storage details.
- [[service|order-orchestration]] — Consumer orchestration service.
- [[channel|bookworm.{env}.basket.delete-failed]] — Kafka channel specification.
- [[channel|bookworm.{env}.basket.dead-letter-queue]] — Dead-letter channel for failed Basket consumers.
- [[event|BasketDeletedCompleteIntegrationEvent]] — Companion success event for checkout basket cleanup.
- [[entity|basket]] — Redis basket data model.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "BasketDeletedFailedIntegrationEvent",
"type": "object",
"additionalProperties": false,
"required": ["id", "creationDate", "orderId", "basketId", "totalMoney"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "Unique identifier assigned by the integration-event building block."
},
"creationDate": {
"type": "string",
"format": "date-time",
"description": "UTC timestamp when the integration event was created."
},
"orderId": {
"type": "string",
"format": "uuid",
"description": "Identifier of the order whose submitted basket could not be deleted."
},
"basketId": {
"type": "string",
"format": "uuid",
"description": "Identifier of the basket that could not be deleted."
},
"email": {
"type": ["string", "null"],
"format": "email",
"description": "Customer email used by downstream recovery or notification workflows."
},
"totalMoney": {
"type": "number",
"format": "double",
"description": "Total purchase amount associated with the order."
}
}
}
---
id: BookUpdatedRatingFailedIntegrationEvent
name: Book rating update failed
version: 1.0.0
summary: |
Indicates that Catalog could not apply a feedback-created event because the
referenced book was not found.
owners:
- catalog-experience-team
schemaPath: schema.json
badges:
- content: Reviews
backgroundColor: purple
textColor: purple
---
`BookUpdatedRatingFailedIntegrationEvent` (v1.0.0) is a compensating event published by [[service|catalog-api]] when it receives [[event|FeedbackCreatedIntegrationEvent]] for a book that does not exist in the catalog. [[service|rating-api]] consumes this event to revert and delete the orphaned feedback record.
## Overview
| Property | Value |
| :----------------------------------- | :----------------------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog (compensating for Reviews) |
| **Producer** | [[service\|catalog-api]] |
| **Consumer(s)** | [[service\|rating-api]] |
| **Protocol / Format** | Kafka + CloudEvents JSON (camelCase payload) |
| **Channel / Topic** | [[channel\|bookworm.{env}.catalog.book-update-rating-failed]] |
| **Dead-Letter Channel** | [[channel\|bookworm.{env}.rating.dead-letter-queue]] |
| **Partition Key** | `FeedbackId` |
| **Delivery / Idempotency Guarantee** | Published via transactional outbox; consumed with Redis-backed 24-hour idempotency keyed by `id` |
## Payload Fields & Envelope
### Event Payload
| Name | Type | Required | Constraints | Description |
| :------------- | :--------------------- | :------- | :------------------------------ | :----------------------------------------------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | UUIDv7 | Unique event identifier used by [[service\|rating-api]] as the Redis idempotency key |
| `creationDate` | `string` (`date-time`) | Yes | ISO 8601 UTC timestamp | UTC timestamp when the event was created |
| `feedbackId` | `string` (`uuid`) | Yes | Valid UUID; Kafka partition key | Identifier of the orphaned [[entity\|feedback]] record to revert and delete |
### CloudEvents Envelope Headers
| Header | Value / Source | Purpose |
| :------------ | :------------------------------------------------------------------ | :------------------------------------------------------------ |
| `messagetype` | `BookWorm.Contracts.BookUpdatedRatingFailedIntegrationEvent` | Explicit message identity for cross-service deserialization |
| `source` | `urn:bookworm:bookworm-catalog` | Identifies the producing service |
| `requestid` | Propagated from incoming [[event\|FeedbackCreatedIntegrationEvent]] | Traces compensation back to the originating review submission |
## Delivery Guarantees & Error Handling
| Condition | System Behavior | Recovery / Compensation |
| :--------------------------------- | :-------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------- |
| Duplicate delivery within 24 hours | Consumer skips reprocessing via Redis-backed 24-hour idempotency keyed by `id` | Safe at-least-once delivery |
| Feedback record already deleted | Consumer returns without error | No action required; compensation is naturally idempotent |
| Transient store or network failure | Retried with cooldown (`50ms`, `250ms`, `1s`) and full jitter | Exhausted messages route to [[channel\|bookworm.{env}.rating.dead-letter-queue]] |
| Deserialization failure | Routed directly to [[channel\|bookworm.{env}.rating.dead-letter-queue]] | Inspect dead-letter payload against contract schema |
## Related Documentation
- [[channel|bookworm.{env}.catalog.book-update-rating-failed]] — Kafka channel specification.
- [[channel|bookworm.{env}.rating.dead-letter-queue]] — Dead-letter channel for failed Rating consumers.
- [[event|FeedbackCreatedIntegrationEvent]] — Upstream event that triggers this compensation when a book is missing.
- [[service|catalog-api]] — Producer service.
- [[service|rating-api]] — Consumer service owning feedback records.
- [[entity|feedback]] — Feedback document schema.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "BookUpdatedRatingFailedIntegrationEvent",
"type": "object",
"additionalProperties": false,
"required": ["id", "creationDate", "feedbackId"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "Unique event identifier (UUIDv7) inherited from IntegrationEvent."
},
"creationDate": {
"type": "string",
"format": "date-time",
"description": "ISO 8601 UTC timestamp when the event was created."
},
"feedbackId": {
"type": "string",
"format": "uuid",
"description": "Identifier of the feedback that could not be applied."
}
}
}
---
id: FeedbackCreatedIntegrationEvent
name: Feedback created
version: 1.0.0
summary: |
Indicates that a customer feedback rating was created for a book. Rating API
publishes this event so Catalog can update its denormalized rating summary.
owners:
- catalog-experience-team
schemaPath: schema.json
badges:
- content: Reviews
backgroundColor: purple
textColor: purple
---
`FeedbackCreatedIntegrationEvent` (v1.0.0) signals that [[service|rating-api]] persisted a new customer [[entity|feedback]] document in Azure Cosmos DB. [[service|catalog-api]] consumes this event to increment the target book's denormalized rating summary in PostgreSQL.
## Overview
| Property | Value |
| :----------------------------------- | :----------------------------------------------------------------------------------------------- |
| **Bounded Context** | Reviews |
| **Producer** | [[service\|rating-api]] |
| **Consumer(s)** | [[service\|catalog-api]] |
| **Protocol / Format** | Kafka + CloudEvents JSON (camelCase payload) |
| **Channel / Topic** | [[channel\|bookworm.{env}.rating.feedback-create]] |
| **Dead-Letter Channel** | [[channel\|bookworm.{env}.catalog.dead-letter-queue]] |
| **Partition Key** | `BookId` |
| **Delivery / Idempotency Guarantee** | Published via transactional outbox; consumed with Redis-backed 24-hour idempotency keyed by `id` |
## Payload Fields & Envelope
### Event Payload
| Name | Type | Required | Constraints | Description |
| :------------- | :--------------------- | :------- | :------------------------------ | :-------------------------------------------------------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | UUIDv7 | Unique event identifier used by [[service\|catalog-api]] as the Redis idempotency key |
| `creationDate` | `string` (`date-time`) | Yes | ISO 8601 UTC timestamp | UTC timestamp when the event was created |
| `bookId` | `string` (`uuid`) | Yes | Valid UUID; Kafka partition key | Identifier of the book whose rating summary must be updated |
| `rating` | `integer` | Yes | `0`-`5` | Rating score to add to the book's denormalized rating summary |
| `feedbackId` | `string` (`uuid`) | Yes | Valid UUID | Identifier of the newly created feedback record, used for compensation if the book is missing |
### CloudEvents Envelope Headers
| Header | Value / Source | Purpose |
| :------------ | :--------------------------------------------------- | :---------------------------------------------------------- |
| `messagetype` | `BookWorm.Contracts.FeedbackCreatedIntegrationEvent` | Explicit message identity for cross-service deserialization |
| `source` | `urn:bookworm:bookworm-rating` | Identifies the producing service |
| `requestid` | Propagated from `POST /rating/api/v1/feedbacks` | Correlates review creation with catalog projection updates |
## Delivery Guarantees & Error Handling
| Condition | System Behavior | Recovery / Compensation |
| :------------------------------------------------ | :---------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------ |
| Duplicate delivery within 24 hours | Consumer skips reprocessing via Redis-backed 24-hour idempotency keyed by `id` | Prevents double-counting a rating on retries |
| Target book not found in [[service\|catalog-api]] | Consumer emits [[event\|BookUpdatedRatingFailedIntegrationEvent]] with `feedbackId` | [[service\|rating-api]] reverts and deletes the orphaned feedback record |
| Transient database or concurrency error | Retried with cooldown (`50ms`, `250ms`, `1s`) and full jitter | Exhausted messages route to [[channel\|bookworm.{env}.catalog.dead-letter-queue]] |
| Deserialization failure | Routed directly to [[channel\|bookworm.{env}.catalog.dead-letter-queue]] | Inspect dead-letter payload against contract schema |
## Related Documentation
- [[service|rating-api]] — Producer service owning feedback records.
- [[service|catalog-api]] — Consumer service maintaining denormalized book ratings.
- [[channel|bookworm.{env}.rating.feedback-create]] — Kafka channel specification.
- [[channel|bookworm.{env}.catalog.dead-letter-queue]] — Dead-letter channel for failed Catalog consumers.
- [[event|BookUpdatedRatingFailedIntegrationEvent]] — Compensating event emitted when the referenced book does not exist.
- [[event|FeedbackDeletedIntegrationEvent]] — Companion event for removing a deleted rating.
- [[entity|feedback]] — Feedback document schema.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "FeedbackCreatedIntegrationEvent",
"type": "object",
"additionalProperties": false,
"required": ["id", "creationDate", "bookId", "rating", "feedbackId"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "Unique event identifier (UUIDv7) inherited from IntegrationEvent."
},
"creationDate": {
"type": "string",
"format": "date-time",
"description": "ISO 8601 UTC timestamp when the event was created."
},
"bookId": {
"type": "string",
"format": "uuid",
"description": "Identifier of the book whose rating summary changes."
},
"rating": {
"type": "integer",
"minimum": 0,
"maximum": 5,
"description": "Rating value added to the book."
},
"feedbackId": {
"type": "string",
"format": "uuid",
"description": "Identifier of the feedback record."
}
}
}
---
id: FeedbackDeletedIntegrationEvent
name: Feedback deleted
version: 1.0.0
summary: |
Indicates that a customer feedback rating was deleted for a book. Rating API
publishes this event so Catalog can remove it from its denormalized summary.
owners:
- catalog-experience-team
schemaPath: schema.json
badges:
- content: Reviews
backgroundColor: purple
textColor: purple
---
`FeedbackDeletedIntegrationEvent` (v1.0.0) signals that [[service|rating-api]] deleted an existing customer [[entity|feedback]] document from Azure Cosmos DB. [[service|catalog-api]] consumes this event to subtract the removed score from the target book's denormalized rating summary in PostgreSQL.
## Overview
| Property | Value |
| :----------------------------------- | :----------------------------------------------------------------------------------------------- |
| **Bounded Context** | Reviews |
| **Producer** | [[service\|rating-api]] |
| **Consumer(s)** | [[service\|catalog-api]] |
| **Protocol / Format** | Kafka + CloudEvents JSON (camelCase payload) |
| **Channel / Topic** | [[channel\|bookworm.{env}.rating.feedback-delete]] |
| **Dead-Letter Channel** | [[channel\|bookworm.{env}.catalog.dead-letter-queue]] |
| **Partition Key** | `BookId` |
| **Delivery / Idempotency Guarantee** | Published via transactional outbox; consumed with Redis-backed 24-hour idempotency keyed by `id` |
## Payload Fields & Envelope
### Event Payload
| Name | Type | Required | Constraints | Description |
| :------------- | :--------------------- | :------- | :------------------------------ | :------------------------------------------------------------------------------------ |
| `id` | `string` (`uuid`) | Yes | UUIDv7 | Unique event identifier used by [[service\|catalog-api]] as the Redis idempotency key |
| `creationDate` | `string` (`date-time`) | Yes | ISO 8601 UTC timestamp | UTC timestamp when the event was created |
| `bookId` | `string` (`uuid`) | Yes | Valid UUID; Kafka partition key | Identifier of the book whose rating summary must be decremented |
| `rating` | `integer` | Yes | `0`-`5` | Rating score removed from the book's denormalized rating summary |
| `feedbackId` | `string` (`uuid`) | Yes | Valid UUID | Identifier of the deleted feedback record |
### CloudEvents Envelope Headers
| Header | Value / Source | Purpose |
| :------------ | :----------------------------------------------------- | :----------------------------------------------------------- |
| `messagetype` | `BookWorm.Contracts.FeedbackDeletedIntegrationEvent` | Explicit message identity for cross-service deserialization |
| `source` | `urn:bookworm:bookworm-rating` | Identifies the producing service |
| `requestid` | Propagated from `DELETE /rating/api/v1/feedbacks/{id}` | Correlates feedback deletion with catalog projection updates |
## Delivery Guarantees & Error Handling
| Condition | System Behavior | Recovery / Compensation |
| :------------------------------------------------ | :--------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------ |
| Duplicate delivery within 24 hours | Consumer skips reprocessing via Redis-backed 24-hour idempotency keyed by `id` | Prevents double-subtracting a rating on retries |
| Target book not found in [[service\|catalog-api]] | Consumer returns without modifying state or emitting a compensating event | No action required; no local rating summary exists to adjust |
| Transient database or concurrency error | Retried with cooldown (`50ms`, `250ms`, `1s`) and full jitter | Exhausted messages route to [[channel\|bookworm.{env}.catalog.dead-letter-queue]] |
| Deserialization failure | Routed directly to [[channel\|bookworm.{env}.catalog.dead-letter-queue]] | Inspect dead-letter payload against contract schema |
## Related Documentation
- [[service|rating-api]] — Producer service owning feedback records.
- [[service|catalog-api]] — Consumer service maintaining denormalized book ratings.
- [[channel|bookworm.{env}.rating.feedback-delete]] — Kafka channel specification.
- [[channel|bookworm.{env}.catalog.dead-letter-queue]] — Dead-letter channel for failed Catalog consumers.
- [[event|FeedbackCreatedIntegrationEvent]] — Companion event for adding a new rating.
- [[entity|book]] — Catalog entity storing the denormalized rating summary.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "FeedbackDeletedIntegrationEvent",
"type": "object",
"additionalProperties": false,
"required": ["id", "creationDate", "bookId", "rating", "feedbackId"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "Unique event identifier (UUIDv7) inherited from IntegrationEvent."
},
"creationDate": {
"type": "string",
"format": "date-time",
"description": "ISO 8601 UTC timestamp when the event was created."
},
"bookId": {
"type": "string",
"format": "uuid",
"description": "Identifier of the book whose rating summary changes."
},
"rating": {
"type": "integer",
"minimum": 0,
"maximum": 5,
"description": "Rating value removed from the book."
},
"feedbackId": {
"type": "string",
"format": "uuid",
"description": "Identifier of the deleted feedback record."
}
}
}
---
id: OrderStatusChangedToCancelIntegrationEvent
name: Order cancelled
version: 1.0.0
summary: |
Reports that an Order transitioned from New to Cancelled.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
---
`OrderStatusChangedToCancelIntegrationEvent` (v1.0.0) reports that [[service|order-api]] transitioned an [[entity|order]] from `New` to `Cancelled`. [[service|order-orchestration]] consumes this authoritative status change to terminate its orchestration instance and dispatch [[command|CancelOrderCommand]] for customer notification; this event is a confirmed transition, not a cancellation request or soft deletion.
## Overview
| Property | Value |
| :----------------------------------- | :-------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Ordering |
| **Producer** | [[service\|order-api]] |
| **Consumer(s)** | [[service\|order-orchestration]] |
| **Protocol / Format** | Kafka + CloudEvents JSON (camelCase payload) |
| **Channel / Topic** | [[channel\|bookworm.{env}.ordering.order-status-change-to-cancel]] |
| **Dead-Letter Channel** | [[channel\|bookworm.{env}.ordering.dead-letter-queue]] |
| **Partition Key** | `OrderId` |
| **Delivery / Idempotency Guarantee** | Published via transactional outbox (at-least-once); orchestration routes idempotently per `OrderId` |
## Payload Fields & Envelope
### Event Payload
| Name | Type | Required | Constraints | Description |
| :------------- | :--------------------- | :------- | :------------------------------ | :------------------------------------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | UUIDv7 | Unique identifier for this integration event instance |
| `creationDate` | `string` (`date-time`) | Yes | ISO 8601 UTC timestamp | UTC timestamp when the event was created |
| `orderId` | `string` (`uuid`) | Yes | Valid UUID; Kafka partition key | Identifier of the cancelled order |
| `basketId` | `string` (`uuid`) | Yes | Valid UUID | Buyer-linked basket reference supplied by the producer |
| `fullName` | `string \| null` | Yes | Nullable string | Customer full name when available on the buyer record |
| `email` | `string \| null` | Yes | Nullable email format | Customer email address when available; email dispatch is skipped if absent |
| `totalMoney` | `number` | Yes | Non-negative monetary amount | Total purchase amount associated with the cancelled order |
:::note
The current producer populates `basketId` with the order's `BuyerId`. Downstream consumers must not assume `basketId` was independently resolved from [[service|basket-api]].
:::
### CloudEvents Envelope Headers
| Header | Value / Source | Purpose |
| :------------ | :-------------------------------------------------------------- | :----------------------------------------------------------------------- |
| `messagetype` | `BookWorm.Contracts.OrderStatusChangedToCancelIntegrationEvent` | Explicit message identity for cross-service deserialization |
| `source` | `urn:bookworm:bookworm-ordering` | Identifies the producing service |
| `requestid` | Propagated from the triggering HTTP request | Correlates order cancellation across Ordering, Finance, and Notification |
## Delivery Guarantees & Error Handling
| Condition | System Behavior | Recovery / Compensation |
| :-------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------- |
| `email` or `fullName` is `null` | Payload remains valid; [[service\|order-orchestration]] checks notification eligibility before dispatching [[command\|CancelOrderCommand]] | Consumers must tolerate `null` contact fields without failing deserialization |
| Transient broker or orchestration error | Transactional outbox guarantees at-least-once publication; Kafka trigger retries delivery | Inspect orchestration instance state and [[channel\|bookworm.{env}.ordering.dead-letter-queue]] |
## Related Documentation
- [[service|order-api]] — Producer service.
- [[service|order-orchestration]] — Consumer orchestration service.
- [[channel|bookworm.{env}.ordering.order-status-change-to-cancel]] — Kafka channel specification.
- [[channel|bookworm.{env}.ordering.dead-letter-queue]] — Dead-letter queue for failed Ordering consumers.
- [[event|OrderStatusChangedToCompleteIntegrationEvent]] — Companion event for `New` to `Completed` transitions.
- [[event|UserCheckedOutIntegrationEvent]] — Initial order placement event.
- [[entity|order]] — Ordering aggregate schema and status lifecycle.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "OrderStatusChangedToCancelIntegrationEvent",
"type": "object",
"additionalProperties": false,
"required": ["id", "creationDate", "orderId", "basketId", "fullName", "email", "totalMoney"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "Unique identifier assigned to the integration event."
},
"creationDate": {
"type": "string",
"format": "date-time",
"description": "UTC timestamp when the integration event was created."
},
"orderId": {
"type": "string",
"format": "uuid",
"description": "Identifier of the Order."
},
"basketId": {
"type": "string",
"format": "uuid",
"description": "UUID serialized as basketId. The current EventMapper supplies the\nOrder's BuyerId for this field.\n"
},
"fullName": {
"type": ["string", "null"],
"description": "Customer name, when available."
},
"email": {
"type": ["string", "null"],
"format": "email",
"description": "Customer email, when available."
},
"totalMoney": {
"type": "number",
"format": "double",
"description": "Total purchase amount associated with the Order."
}
}
}
---
id: OrderStatusChangedToCompleteIntegrationEvent
name: Order completed
version: 1.0.0
summary: |
Reports that an Order transitioned from New to Completed.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
---
`OrderStatusChangedToCompleteIntegrationEvent` (v1.0.0) reports that [[service|order-api]] transitioned an [[entity|order]] from `New` to `Completed`. [[service|order-orchestration]] consumes this event to complete its orchestration instance and dispatch [[command|CompleteOrderCommand]] to [[service|notification-api]]; it confirms an authoritative order status change and is neither a completion request nor an email delivery receipt.
## Overview
| Property | Value |
| :----------------------------------- | :-------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Ordering |
| **Producer** | [[service\|order-api]] |
| **Consumer(s)** | [[service\|order-orchestration]] |
| **Protocol / Format** | Kafka + CloudEvents JSON (camelCase payload) |
| **Channel / Topic** | [[channel\|bookworm.{env}.ordering.order-status-change-to-complete]] |
| **Dead-Letter Channel** | [[channel\|bookworm.{env}.ordering.dead-letter-queue]] |
| **Partition Key** | `OrderId` |
| **Delivery / Idempotency Guarantee** | Published via transactional outbox (at-least-once); orchestration routes idempotently per `OrderId` |
## Payload Fields & Envelope
### Event Payload
| Name | Type | Required | Constraints | Description |
| :------------- | :--------------------- | :------- | :------------------------------ | :------------------------------------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | UUIDv7 | Unique identifier for this integration event instance |
| `creationDate` | `string` (`date-time`) | Yes | ISO 8601 UTC timestamp | UTC timestamp when the event was created |
| `orderId` | `string` (`uuid`) | Yes | Valid UUID; Kafka partition key | Identifier of the completed order |
| `basketId` | `string` (`uuid`) | Yes | Valid UUID | Buyer-linked basket reference supplied by the producer |
| `fullName` | `string \| null` | Yes | Nullable string | Customer full name when available on the buyer record |
| `email` | `string \| null` | Yes | Nullable email format | Customer email address when available; email dispatch is skipped if absent |
| `totalMoney` | `number` | Yes | Non-negative monetary amount | Total purchase amount associated with the completed order |
:::note
The current producer populates `basketId` with the order's `BuyerId`. Downstream consumers must not assume `basketId` was independently resolved from [[service|basket-api]].
:::
### CloudEvents Envelope Headers
| Header | Value / Source | Purpose |
| :------------ | :---------------------------------------------------------------- | :--------------------------------------------------------------------- |
| `messagetype` | `BookWorm.Contracts.OrderStatusChangedToCompleteIntegrationEvent` | Explicit message identity for cross-service deserialization |
| `source` | `urn:bookworm:bookworm-ordering` | Identifies the producing service |
| `requestid` | Propagated from the triggering HTTP request | Correlates order completion across Ordering, Finance, and Notification |
## Delivery Guarantees & Error Handling
| Condition | System Behavior | Recovery / Compensation |
| :-------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------- |
| `email` or `fullName` is `null` | Payload remains valid; [[service\|order-orchestration]] checks notification eligibility before dispatching [[command\|CompleteOrderCommand]] | Consumers must tolerate `null` contact fields without failing deserialization |
| Transient broker or orchestration error | Transactional outbox guarantees at-least-once publication; Kafka trigger retries delivery | Inspect orchestration instance state and [[channel\|bookworm.{env}.ordering.dead-letter-queue]] |
## Related Documentation
- [[service|order-api]] — Producer service.
- [[service|order-orchestration]] — Consumer orchestration service.
- [[channel|bookworm.{env}.ordering.order-status-change-to-complete]] — Kafka channel specification.
- [[channel|bookworm.{env}.ordering.dead-letter-queue]] — Dead-letter queue for failed Ordering consumers.
- [[event|OrderStatusChangedToCancelIntegrationEvent]] — Companion event for `New` to `Cancelled` transitions.
- [[event|UserCheckedOutIntegrationEvent]] — Initial order placement event.
- [[entity|order]] — Ordering aggregate schema and status lifecycle.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "OrderStatusChangedToCompleteIntegrationEvent",
"type": "object",
"additionalProperties": false,
"required": ["id", "creationDate", "orderId", "basketId", "fullName", "email", "totalMoney"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "Unique identifier assigned to the integration event."
},
"creationDate": {
"type": "string",
"format": "date-time",
"description": "UTC timestamp when the integration event was created."
},
"orderId": {
"type": "string",
"format": "uuid",
"description": "Identifier of the Order."
},
"basketId": {
"type": "string",
"format": "uuid",
"description": "UUID serialized as basketId. The current EventMapper supplies the\nOrder's BuyerId for this field.\n"
},
"fullName": {
"type": ["string", "null"],
"description": "Customer name, when available."
},
"email": {
"type": ["string", "null"],
"format": "email",
"description": "Customer email, when available."
},
"totalMoney": {
"type": "number",
"format": "double",
"description": "Total purchase amount associated with the Order."
}
}
}
---
id: ProcessVectorBatchIntegrationEvent
name: Process vector batch
version: 1.0.0
summary: |
Integration event published by Scheduler every five minutes to trigger
Catalog Ingestion vector batch processing over Kafka.
owners:
- platform-engineering-team
badges:
- content: Integration Event
backgroundColor: orange
textColor: orange
icon: BoltIcon
schemaPath: schema.json
---
`ProcessVectorBatchIntegrationEvent` (v1.0.0) is a lightweight scheduled trigger published every five minutes by [[service|scheduler-service]] over Kafka. [[service|catalog-ingestion]] consumes this event to fetch changed catalog records from PostgreSQL, generate embeddings, and update the Qdrant vector index.
## Overview
| Property | Value |
| :----------------------------------- | :------------------------------------------------------------------------------ |
| **Bounded Context** | Platform / Scheduler |
| **Producer** | [[service\|scheduler-service]] |
| **Consumer(s)** | [[service\|catalog-ingestion]] (consumer group `catalog-ingestion`) |
| **Protocol / Format** | Kafka + CloudEvents JSON (camelCase payload) |
| **Channel / Topic** | [[channel\|scheduler.process-vector-batch]] (unprefixed across environments) |
| **Dead-Letter Channel** | None (pending records remain queued in PostgreSQL for the next scheduled batch) |
| **Partition Key** | None (single trigger event per 5-minute cron `0 0/5 * * * ?` UTC) |
| **Delivery / Idempotency Guarantee** | Published via transactional outbox; misfire policy `FireOnceNow` |
:::note
Unlike every other BookWorm integration topic, `scheduler.process-vector-batch` is **unprefixed** (omits `bookworm.{env}.`) so the static Azure Functions Kafka trigger binding matches across environments.
:::
## Payload Fields & Envelope
### Event Payload
The event carries only the two base envelope fields; batch sizing, selection order, and vector upsert logic remain owned by [[service|catalog-ingestion]].
| Name | Type | Required | Constraints | Description |
| :------------- | :--------------------- | :------- | :--------------------- | :----------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | UUIDv7 | Unique identifier of the trigger event |
| `creationDate` | `string` (`date-time`) | Yes | ISO 8601 UTC timestamp | UTC timestamp when the trigger event was created |
### CloudEvents Envelope Headers
| Header | Value / Source | Purpose |
| :------------ | :------------------------------------------------------ | :---------------------------------------------------------- |
| `messagetype` | `BookWorm.Contracts.ProcessVectorBatchIntegrationEvent` | Explicit message identity for cross-service deserialization |
| `source` | `urn:bookworm:bookworm-scheduler` | Identifies the producing service |
## Delivery Guarantees & Error Handling
| Condition | System Behavior | Recovery / Compensation |
| :----------------------------------- | :----------------------------------------------- | :---------------------------------------------------------- |
| Misfire during Scheduler downtime | Scheduler applies `FireOnceNow` misfire handling | A single catch-up event is published when Scheduler resumes |
| Catalog Ingestion processing failure | Azure Functions Kafka trigger invocation fails | Pending records remain eligible on the next five-minute run |
## Related Documentation
- [[channel|scheduler.process-vector-batch]] — Unprefixed Kafka channel specification.
- [[service|scheduler-service]] — Quartz scheduler service.
- [[service|catalog-ingestion]] — Azure Functions consumer service.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "BookWorm.Contracts.ProcessVectorBatchIntegrationEvent",
"title": "ProcessVectorBatchIntegrationEvent",
"type": "object",
"additionalProperties": false,
"required": ["id", "creationDate"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "Unique identifier of the integration event."
},
"creationDate": {
"type": "string",
"format": "date-time",
"description": "UTC timestamp when the event was created."
}
}
}
---
id: UserCheckedOutIntegrationEvent
name: User checked out
version: 1.0.0
summary: |
Reports that an Order was placed and its checkout details are ready for
Finance coordination.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
---
`UserCheckedOutIntegrationEvent` (v1.0.0) reports that [[service|order-api]] accepted and persisted a new [[entity|order]] during customer checkout. [[service|order-orchestration]] consumes this event to start a Durable Task saga instance, which dispatches [[command|PlaceOrderCommand]] to [[service|basket-api]] (for basket cleanup) and [[service|notification-api]] (for order confirmation email). Receiving this event confirms order placement only, not basket cleanup or order completion.
## Overview
| Property | Value |
| :----------------------------------- | :-------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Ordering |
| **Producer** | [[service\|order-api]] |
| **Consumer(s)** | [[service\|order-orchestration]] |
| **Protocol / Format** | Kafka + CloudEvents JSON (camelCase payload) |
| **Channel / Topic** | [[channel\|bookworm.{env}.ordering.user-checked-out]] |
| **Dead-Letter Channel** | [[channel\|bookworm.{env}.ordering.dead-letter-queue]] |
| **Partition Key** | `OrderId` |
| **Delivery / Idempotency Guarantee** | Published via transactional outbox (at-least-once); orchestration starts idempotently per `OrderId` |
## Payload Fields & Envelope
### Event Payload
| Name | Type | Required | Constraints | Description |
| :------------- | :--------------------- | :------- | :------------------------------ | :---------------------------------------------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | UUIDv7 | Unique identifier for this integration event instance |
| `creationDate` | `string` (`date-time`) | Yes | ISO 8601 UTC timestamp | UTC timestamp when the event was created |
| `orderId` | `string` (`uuid`) | Yes | Valid UUID; Kafka partition key | Identifier of the accepted order |
| `basketId` | `string` (`uuid`) | Yes | Valid UUID | Buyer-linked basket reference supplied by the producer |
| `fullName` | `string \| null` | Yes | Nullable string | Customer full name when available on the buyer record |
| `email` | `string \| null` | Yes | Nullable email format | Customer email address when available; used to decide whether to send notifications |
| `totalMoney` | `number` | Yes | Non-negative monetary amount | Total purchase amount associated with the accepted order |
:::note
The current producer populates `basketId` with the order's `BuyerId`. Downstream consumers must not treat `basketId` as an independently resolved [[service|basket-api]] record.
:::
### CloudEvents Envelope Headers
| Header | Value / Source | Purpose |
| :------------ | :-------------------------------------------------- | :--------------------------------------------------------------------- |
| `messagetype` | `BookWorm.Contracts.UserCheckedOutIntegrationEvent` | Explicit message identity for cross-service deserialization |
| `source` | `urn:bookworm:bookworm-ordering` | Identifies the producing service |
| `requestid` | Propagated from `POST /ordering/api/v1/orders` | Correlates checkout across Ordering, Finance, Basket, and Notification |
## Delivery Guarantees & Error Handling
| Condition | System Behavior | Recovery / Compensation |
| :-------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------ | :-------------------------------------------------------------------------------------------------- |
| `email` or `fullName` is `null` | Payload remains valid; [[service\|order-orchestration]] still coordinates basket cleanup and evaluates notification eligibility | Consumers must tolerate `null` contact fields without failing deserialization |
| Transient broker or orchestration error | Transactional outbox guarantees at-least-once publication; orchestration starts idempotently per `OrderId` | Inspect orchestration task hub and [[channel\|bookworm.{env}.ordering.dead-letter-queue]] |
## Related Documentation
- [[service|order-api]] — Producer service.
- [[service|order-orchestration]] — Consumer orchestration service.
- [[channel|bookworm.{env}.ordering.user-checked-out]] — Kafka channel specification.
- [[channel|bookworm.{env}.ordering.dead-letter-queue]] — Dead-letter queue for failed Ordering consumers.
- [[event|OrderStatusChangedToCompleteIntegrationEvent]] — Subsequent completion event.
- [[event|OrderStatusChangedToCancelIntegrationEvent]] — Subsequent cancellation event.
- [[entity|order]] — Ordering aggregate schema and lifecycle.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "UserCheckedOutIntegrationEvent",
"type": "object",
"additionalProperties": false,
"required": ["id", "creationDate", "orderId", "basketId", "fullName", "email", "totalMoney"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "Unique identifier assigned to the integration event."
},
"creationDate": {
"type": "string",
"format": "date-time",
"description": "UTC timestamp when the integration event was created."
},
"orderId": {
"type": "string",
"format": "uuid",
"description": "Identifier of the Order."
},
"basketId": {
"type": "string",
"format": "uuid",
"description": "UUID serialized as basketId. The current EventMapper supplies the\nOrder's BuyerId for this field.\n"
},
"fullName": {
"type": ["string", "null"],
"description": "Customer name, when available."
},
"email": {
"type": ["string", "null"],
"format": "email",
"description": "Customer email, when available."
},
"totalMoney": {
"type": "number",
"format": "double",
"description": "Total purchase amount associated with the Order."
}
}
}
---
id: AnalyzeText
name: Analyze text
version: 1.0.0
badges:
- content: Privacy
backgroundColor: red
textColor: red
summary: Detects PII entities in one text string or a batch, returning entity types, text offsets, confidence scores, and optional analysis explanations.
owners:
- platform-engineering-team
schemaPath: schema.json
operation:
method: POST
path: /analyze
statusCodes: ["200"]
sidebar:
badge: "POST"
---
`AnalyzeText` requests PII detection from the internal [[service|presidio-api]] Analyzer sidecar (`POST /analyze`). In BookWorm, [[service|chat-api]] and [[service|rating-api]] call this endpoint before anonymizing user-supplied text.
## Overview
| Property | Value |
| :--------------------------------- | :------------------------------------------------------------- |
| **Bounded Context** | Data Privacy (External Integration) |
| **Owner Service** | [[service\|presidio-api]] (`presidio-analyzer`) |
| **Protocol / Format** | HTTP `POST /analyze`, `application/json` request and response |
| **Gateway Endpoint** | Internal sidecar `POST /analyze` (not exposed via API Gateway) |
| **Authentication & Authorization** | None (internal service-to-service network boundary) |
| **Idempotency / Concurrency** | Stateless and naturally idempotent |
| **Rate Limit / Caching** | None (sidecar) |
| **Contract Version** | `1.0.0` |
:::note
The Presidio Analyzer (`presidio-analyzer`) and Anonymizer (`presidio-anonymizer`) run as separate sidecar containers with independent endpoints; never assume a shared base URL.
:::
## Request & Response Contract
### Request Body (`application/json`)
| Name | Type | Required | Constraints | Description |
| :------------------------ | :------------------- | :------- | :--------------------------------------------------------- | :----------------------------------------------------------------------- |
| `text` | `string \| string[]` | Yes | Non-empty string or array of strings | Input text to scan for PII entities (BookWorm sends a single `string`) |
| `language` | `string` | Yes | Two-character ISO 639-1 code (BookWorm defaults to `"en"`) | Language model used for PII recognition |
| `correlation_id` | `string` | No | — | Caller-supplied correlation identifier echoed for request tracing |
| `score_threshold` | `number` | No | Default `0.0`; floating-point confidence floor | Minimum confidence score required to include a detection |
| `entities` | `string[]` | No | Valid Presidio entity names | Optional allowlist of PII entity types (e.g., `PERSON`, `EMAIL_ADDRESS`) |
| `return_decision_process` | `boolean` | No | Default `false` | When `true`, includes recognizer decision-process metadata per detection |
| `ad_hoc_recognizers` | `object[]` | No | Presidio recognizer objects | Request-scoped custom pattern or deny-list recognizers |
| `context` | `string[]` | No | — | Surrounding context words that can boost recognizer confidence |
### Success Response (`200 OK`)
For a single-string request, returns a JSON array of detection objects. For a batch (`string[]`) request, returns an array of detection arrays (one per input string).
| Name | Type | Required | Constraints | Description |
| :--------------------- | :-------- | :------- | :----------------------------------------------- | :------------------------------------------------------ |
| `entity_type` | `string` | Yes | Presidio entity label | Detected PII category (e.g., `PERSON`, `EMAIL_ADDRESS`) |
| `start` | `integer` | Yes | `>= 0` | Zero-based inclusive start character index in `text` |
| `end` | `integer` | Yes | `> start` | Zero-based exclusive end character index in `text` |
| `score` | `number` | Yes | `0.0`-`1.0` | Confidence score assigned by the recognizer |
| `analysis_explanation` | `object` | No | Present when `return_decision_process` is `true` | Optional recognizer decision metadata |
## Behavior & Side Effects
- **Stateless analysis:** Performs in-memory NLP and pattern-based PII detection with no persistent state.
- **Client guard:** BookWorm callers skip calls when `text` is null or whitespace and return the original text unchanged when no detections are returned.
- **PII logging restriction:** Raw `text` payloads and unredacted detection excerpts must never be logged.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :------------------------------------------------------------------------------------------------------- | :------------------------------------------------------ |
| `400 Bad Request` | Malformed request payload or invalid ad-hoc recognizer definition | Fix the request body; do not retry unchanged |
| `500 Internal Server Error` | Unsupported `language` (`"No matching recognizers were found to serve the request."`) or sidecar failure | Supply a supported ISO 639-1 language code (e.g., `en`) |
## Related Documentation
- [[service|presidio-api]] — Overview of the Presidio Analyzer and Anonymizer sidecars.
- [[command|AnonymizeText]] — Transform text using detections returned by `AnalyzeText`.
- [[query|GetRecognizers]] — List active Presidio Analyzer recognizers.
- [[query|GetSupportedEntities]] — List detectable PII entity types.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "AnalyzeText",
"description": "Request to detect PII in one or more text strings.",
"type": "object",
"required": ["text", "language"],
"properties": {
"text": {
"description": "Text to analyze, as a single string or a batch of strings.",
"oneOf": [{ "type": "string" }, { "type": "array", "items": { "type": "string" } }]
},
"language": {
"type": "string",
"description": "Two-character ISO 639-1 language code.",
"examples": ["en"]
},
"correlation_id": { "type": "string" },
"score_threshold": {
"type": "number",
"description": "Minimum detection confidence score."
},
"entities": {
"type": "array",
"items": { "type": "string" },
"description": "PII entity types to analyze."
},
"return_decision_process": {
"type": "boolean",
"description": "Whether to include analysis explanations in the response."
},
"ad_hoc_recognizers": {
"type": "array",
"items": { "type": "object" },
"description": "Request-specific recognizers."
},
"context": {
"type": "array",
"items": { "type": "string" },
"description": "Context words that can improve recognition confidence."
}
}
}
---
id: AnonymizeText
name: Anonymize text
version: 1.0.0
badges:
- content: Privacy
backgroundColor: red
textColor: red
summary: Replaces or transforms detected PII in text using the supplied analysis results and configured anonymization operators.
owners:
- platform-engineering-team
schemaPath: schema.json
operation:
method: POST
path: /anonymize
statusCodes: ["200", "400", "422"]
sidebar:
badge: "POST"
---
`AnonymizeText` requests PII transformation from the internal [[service|presidio-api]] Anonymizer sidecar (`POST /anonymize`) using entity spans produced by [[command|AnalyzeText]]. In BookWorm, [[service|chat-api]] and [[service|rating-api]] call this endpoint to replace detected PII spans with ``.
## Overview
| Property | Value |
| :--------------------------------- | :--------------------------------------------------------------- |
| **Bounded Context** | Data Privacy (External Integration) |
| **Owner Service** | [[service\|presidio-api]] (`presidio-anonymizer`) |
| **Protocol / Format** | HTTP `POST /anonymize`, `application/json` request and response |
| **Gateway Endpoint** | Internal sidecar `POST /anonymize` (not exposed via API Gateway) |
| **Authentication & Authorization** | None (internal service-to-service network boundary) |
| **Idempotency / Concurrency** | Stateless and naturally idempotent |
| **Rate Limit / Caching** | None (sidecar) |
| **Contract Version** | `1.0.0` |
:::warning
Pass `analyzer_results` computed against the exact same `text` string. Stale character offsets cause Presidio Anonymizer to corrupt unrelated substrings or reject the request.
:::
## Request & Response Contract
### Request Body (`application/json`)
| Name | Type | Required | Constraints | Description |
| :----------------- | :--------- | :------- | :------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------- |
| `text` | `string` | Yes | Exact string analyzed by [[command\|AnalyzeText]] | Original text containing PII spans to transform |
| `analyzer_results` | `object[]` | Yes | Each item requires `start` (`>= 0`), `end` (`> start`), `score` (`0.0`-`1.0`), `entity_type` | PII detections returned by `POST /analyze` |
| `anonymizers` | `object` | No | Map of `DEFAULT` or entity type to operator (`replace`, `redact`, `mask`, `hash`, `encrypt`) | Per-entity or fallback operator configuration (BookWorm defaults to `replace` with `""`) |
### Success Response (`200 OK`)
| Name | Type | Required | Constraints | Description |
| :------ | :--------- | :------- | :--------------------------------------------------------------------------------- | :--------------------------------------------------- |
| `text` | `string` | Yes | — | Transformed text after applying configured operators |
| `items` | `object[]` | No | Each item includes `start`, `end`, `entity_type`, and optional `operator` / `text` | Applied operator metadata |
## Behavior & Side Effects
- **Stateless transformation:** Transforms the supplied string in memory and stores no data.
- **Default replacement:** BookWorm configures the `DEFAULT` operator as `{"type": "replace", "new_value": ""}` for all detected entities.
- **PII logging restriction:** Raw `text` request bodies must never be logged.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :------------------------- | :----------------------------------------------------------------- | :------------------------------------------- |
| `400 Bad Request` | Invalid request JSON payload | Fix the request body; do not retry unchanged |
| `422 Unprocessable Entity` | Invalid input (e.g., empty text or invalid operator configuration) | Correct the input fields and retry |
## Related Documentation
- [[service|presidio-api]] — Overview of the Presidio Analyzer and Anonymizer sidecars.
- [[command|AnalyzeText]] — Generate `analyzer_results` spans before calling `AnonymizeText`.
- [[query|GetAnonymizers]] — List supported anonymization operators.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "AnonymizeText",
"description": "Request to transform text using previously detected PII entities.",
"type": "object",
"required": ["text", "analyzer_results"],
"properties": {
"text": {
"type": "string",
"description": "Text to anonymize."
},
"anonymizers": {
"type": "object",
"description": "Optional operators keyed by DEFAULT or a PII entity type.",
"additionalProperties": {
"oneOf": [
{
"type": "object",
"required": ["type", "new_value"],
"properties": {
"type": { "const": "replace" },
"new_value": { "type": "string" }
}
},
{
"type": "object",
"required": ["type"],
"properties": { "type": { "const": "redact" } }
},
{
"type": "object",
"required": ["type", "masking_char", "chars_to_mask"],
"properties": {
"type": { "const": "mask" },
"masking_char": { "type": "string" },
"chars_to_mask": { "type": "integer" },
"from_end": { "type": "boolean" }
}
},
{
"type": "object",
"required": ["type"],
"properties": {
"type": { "const": "hash" },
"hash_type": { "type": "string", "enum": ["sha256", "sha512"] }
}
},
{
"type": "object",
"required": ["type", "key"],
"properties": {
"type": { "const": "encrypt" },
"key": { "type": "string" }
}
}
]
}
},
"analyzer_results": {
"type": "array",
"description": "PII detections returned by the Analyzer.",
"items": {
"type": "object",
"required": ["start", "end", "score", "entity_type"],
"properties": {
"start": { "type": "integer" },
"end": { "type": "integer" },
"score": { "type": "number" },
"entity_type": { "type": "string" }
}
}
}
}
}
---
id: CancelOrder
name: Cancel order
version: 1.0.0
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
summary: Marks an existing Order as Cancelled when its current status is New.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
operation:
method: PATCH
path: /api/v1/orders/{orderId}/cancel
statusCodes: ["200", "404"]
sidebar:
badge: "PATCH"
---
`CancelOrder` transitions an existing order from `New` to `Cancelled` in [[service|order-api]] (`PATCH /ordering/api/v1/orders/{orderId}/cancel`) and triggers downstream cancellation orchestration through Kafka.
## Overview
| Property | Value |
| :--------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Ordering |
| **Owner Service** | [[service\|order-api]] |
| **Protocol / Format** | HTTP `PATCH`, `application/json` response |
| **Gateway Endpoint** | `PATCH /ordering/api/v1/orders/{orderId}/cancel` (service path `/api/v1/orders/{orderId}/cancel`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `customer` or `admin` role plus scopes `ordering_read`, `ordering_write` |
| **Idempotency / Concurrency** | Required `x-request-id` header (Redis-backed 3600s TTL; returns `409 Conflict` on duplicate); optimistic concurrency (`412 Precondition Failed` on conflict) |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` burst, `20` per `10s`, queue `5`) |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Path Parameters & Headers
Accepts no request body.
| Name | Type | Required | Constraints | Description |
| :------------- | :---------------- | :------- | :------------------------------------- | :----------------------------------------------------------------- |
| `orderId` | `string` (`uuid`) | Yes | Path parameter; valid UUID | Unique identifier of the order to cancel |
| `x-request-id` | `string` | Yes | HTTP header; non-empty, non-whitespace | Client-generated idempotency key tracked in Redis for 3600 seconds |
### Success Response (`200 OK`)
| Name | Type | Required | Constraints | Description |
| :----------------- | :--------------------- | :------- | :---------------------------------- | :------------------------------------------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | Valid UUID | Unique identifier of the cancelled order |
| `date` | `string` (`date-time`) | Yes | ISO 8601 UTC timestamp | Creation timestamp |
| `total` | `number` | Yes | Rounded to 2 decimal places | Sum of `quantity * price` across all order items |
| `status` | `string` | Yes | `"Cancelled"` on success | Current lifecycle status |
| `items` | `object[]` | Yes | Array of line items | Purchased items belonging to the order |
| `items[].id` | `string` (`uuid`) | Yes | Valid UUID | Line item identifier |
| `items[].quantity` | `integer` | Yes | `> 0` | Purchased quantity for the item |
| `items[].price` | `number` | Yes | `>= 0`, rounded to 2 decimal places | Unit price captured at order creation |
| `items[].name` | `string \| null` | No | Nullable | Book title (`null` in this response because catalog enrichment is not performed) |
## Behavior & Side Effects
- **Access scoping:** Administrators can target any `New` order; customers can only target orders matching their authenticated buyer ID.
- **State transition:** Transitions `New` to `Cancelled`. Orders already in `Cancelled` or `Completed` status cannot transition again (admins receive `404 Not Found`; customers targeting their own non-`New` order receive `500 Internal Server Error`).
- **Event publishing:** Appends the cancellation event to the event store and publishes [[event|OrderStatusChangedToCancelIntegrationEvent]] via transactional outbox to [[channel|bookworm.{env}.ordering.order-status-change-to-cancel]] (partitioned by `OrderId`).
- **Idempotency key lifecycle:** Claims the `x-request-id` key in Redis for 3600 seconds (`409 Conflict` on replay) and deletes the key if the operation fails with `5xx` so retries can proceed.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :-------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------- |
| `400 Bad Request` | Missing or whitespace `x-request-id` header, or invalid user identifier claim | Provide a non-empty `x-request-id` header and valid token claims; do not retry unchanged |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID bearer token | Acquire a fresh Entra ID access token and retry |
| `403 Forbidden` | Caller lacks `customer`/`admin` role or `ordering_read`/`ordering_write` scopes | Request the required Entra ID role and scopes before retrying |
| `404 Not Found` | Order does not exist, is soft-deleted, belongs to another buyer, or (for `admin`) is not in `New` status | Verify the `orderId` and current order status; do not retry unchanged |
| `409 Conflict` | Duplicate `x-request-id` for this path within the 3600-second TTL | Treat as a duplicate submission and query order status before taking further action |
| `412 Precondition Failed` | Concurrent update conflict on the order or event stream | Refresh order state and retry with a new `x-request-id` if still `New` |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Customer attempted to cancel an owned order already in `Cancelled` or `Completed` status, or unhandled server failure | Inspect the order's current status; do not retry non-`New` transitions |
## Related Documentation
- [[service|order-api]] — Service architecture, persistence, and endpoints.
- [[entity|order]] — Order aggregate invariants and lifecycle statuses.
- [[event|OrderStatusChangedToCancelIntegrationEvent]] — Kafka event emitted on cancellation.
- [[channel|bookworm.{env}.ordering.order-status-change-to-cancel]] — Kafka topic specification.
- [[command|CompleteOrder]] — Transition a `New` order to `Completed`.
- [[command|DeleteOrder]] — Administrative soft-delete without status transition.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "CancelOrderRequest",
"description": "Path and header parameters for cancelling an Order. The operation has no request body.",
"type": "object",
"required": ["orderId", "x-request-id"],
"properties": {
"orderId": {
"type": "string",
"description": "Unique identifier of the Order to cancel."
},
"x-request-id": {
"type": "string",
"description": "Idempotency key for the cancellation request."
}
}
}
---
id: CancelOrderCommand
name: Send order cancelled notification
version: 1.0.0
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
summary: |
Shared Finance cancellation command consumed by Notification to render
and submit a canceled-order email.
schemaPath: schema.json
owners:
- platform-engineering-team
---
`CancelOrderCommand` is an asynchronous Kafka integration command published by [[service|order-orchestration]] and consumed by [[service|notification-api]] to render and submit a cancelled-order customer email. It never mutates order state in [[service|order-api]].
## Overview
| Property | Value |
| :----------------------------------- | :----------------------------------------------------------------------------------- |
| **Bounded Context** | Platform / Notifications |
| **Producer** | [[service\|order-orchestration]] |
| **Consumer(s)** | [[service\|notification-api]] |
| **Protocol / Format** | Kafka + CloudEvents JSON (camelCase payload) |
| **Channel / Topic** | [[channel\|bookworm.{env}.finance.cancel-order]] |
| **Dead-Letter Channel** | [[channel\|bookworm.{env}.notification.dead-letter-queue]] |
| **Partition Key** | `OrderId` |
| **Delivery / Idempotency Guarantee** | At-least-once delivery; consumed with Redis-backed 24-hour idempotency keyed by `id` |
:::note
`CancelOrderCommand` requests a customer email only. To change an order's authoritative status to `Cancelled`, call [[command|CancelOrder]].
:::
## Payload Fields & Envelope
### Command Payload
| Name | Type | Required | Constraints | Description |
| :------------- | :--------------------- | :------- | :-------------------------------------------- | :------------------------------------------------------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | UUIDv7 | Unique message identifier used for 24-hour Redis deduplication |
| `creationDate` | `string` (`date-time`) | Yes | ISO 8601 UTC timestamp | UTC timestamp when the command was created |
| `orderId` | `string` (`uuid`) | Yes | Valid UUID; Kafka partition key | Identifier of the cancelled order |
| `fullName` | `string \| null` | No | Nullable (defaults to `"Customer"` when null) | Customer display name |
| `email` | `string \| null` | No | Nullable | Recipient email address; null, empty, or whitespace values skip email rendering and delivery |
| `totalMoney` | `number` | Yes | Non-negative monetary amount | Order total displayed in the cancellation email template |
## Delivery Guarantees & Error Handling
| Condition | System Behavior | Recovery / Compensation |
| :--------------------------------- | :---------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------- |
| Duplicate delivery within 24 hours | Consumer skips reprocessing via Redis-backed 24-hour idempotency keyed by `id` | Safe at-least-once delivery; newly published commands with a different `id` execute again |
| Blank or `null` `email` | Consumer returns without error and skips template rendering and SMTP submission | No action required |
| Transient SMTP or network failure | Retried by the notification resilience pipeline (circuit breaker, exponential backoff with jitter, `30s` timeout) | Exhausted retries route to [[channel\|bookworm.{env}.notification.dead-letter-queue]] |
| Permanent SMTP failure | Retried with cooldown (`50ms`, `250ms`, `1s` with full jitter) | Routed to [[channel\|bookworm.{env}.notification.dead-letter-queue]] |
## Related Documentation
- [[service|notification-api]] — Stateless email worker architecture and SMTP configuration.
- [[service|order-orchestration]] — Producing orchestration service.
- [[channel|bookworm.{env}.finance.cancel-order]] — Kafka channel specification.
- [[channel|bookworm.{env}.notification.dead-letter-queue]] — Dead-letter queue for failed Notification consumers.
- [[event|OrderStatusChangedToCancelIntegrationEvent]] — Upstream Ordering event that triggers cancellation notification.
- [[command|CancelOrder]] — Ordering API HTTP command that cancels an order.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "CancelOrderCommand",
"type": "object",
"additionalProperties": false,
"required": ["id", "creationDate", "orderId", "totalMoney"],
"properties": {
"id": { "type": "string", "format": "uuid" },
"creationDate": { "type": "string", "format": "date-time" },
"orderId": { "type": "string", "format": "uuid" },
"fullName": { "type": ["string", "null"] },
"email": { "type": ["string", "null"] },
"totalMoney": { "type": "number" }
}
}
---
id: CompleteOrder
name: Complete order
version: 1.0.0
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
summary: Marks an existing Order as Completed when its current status is New.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
operation:
method: PATCH
path: /api/v1/orders/{orderId}/complete
statusCodes: ["200", "404"]
sidebar:
badge: "PATCH"
---
`CompleteOrder` transitions an existing order from `New` to `Completed` in [[service|order-api]] (`PATCH /ordering/api/v1/orders/{orderId}/complete`) and publishes an integration event so [[service|order-orchestration]] can dispatch completion notifications.
## Overview
| Property | Value |
| :--------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Ordering |
| **Owner Service** | [[service\|order-api]] |
| **Protocol / Format** | HTTP `PATCH`, `application/json` response |
| **Gateway Endpoint** | `PATCH /ordering/api/v1/orders/{orderId}/complete` (service path `/api/v1/orders/{orderId}/complete`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `customer` or `admin` role plus scopes `ordering_read`, `ordering_write` |
| **Idempotency / Concurrency** | Required `x-request-id` header (Redis-backed 3600s TTL; returns `409 Conflict` on duplicate); optimistic concurrency (`412 Precondition Failed` on conflict) |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` burst, `20` per `10s`, queue `5`) |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Path Parameters & Headers
Accepts no request body.
| Name | Type | Required | Constraints | Description |
| :------------- | :---------------- | :------- | :------------------------------------- | :----------------------------------------------------------------- |
| `orderId` | `string` (`uuid`) | Yes | Path parameter; valid UUID | Unique identifier of the order to complete |
| `x-request-id` | `string` | Yes | HTTP header; non-empty, non-whitespace | Client-generated idempotency key tracked in Redis for 3600 seconds |
### Success Response (`200 OK`)
| Name | Type | Required | Constraints | Description |
| :----------------- | :--------------------- | :------- | :---------------------------------- | :------------------------------------------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | Valid UUID | Unique identifier of the completed order |
| `date` | `string` (`date-time`) | Yes | ISO 8601 UTC timestamp | Creation timestamp |
| `total` | `number` | Yes | Rounded to 2 decimal places | Sum of `quantity * price` across all order items |
| `status` | `string` | Yes | `"Completed"` on success | Current lifecycle status |
| `items` | `object[]` | Yes | Array of line items | Purchased items belonging to the order |
| `items[].id` | `string` (`uuid`) | Yes | Valid UUID | Line item identifier |
| `items[].quantity` | `integer` | Yes | `> 0` | Purchased quantity for the item |
| `items[].price` | `number` | Yes | `>= 0`, rounded to 2 decimal places | Unit price captured at order creation |
| `items[].name` | `string \| null` | No | Nullable | Book title (`null` in this response because catalog enrichment is not performed) |
## Behavior & Side Effects
- **Access scoping:** Administrators can target any `New` order; customers can only target orders matching their authenticated buyer ID.
- **State transition:** Transitions `New` to `Completed`. Orders already in `Completed` or `Cancelled` status cannot transition again (admins receive `404 Not Found`; customers targeting their own non-`New` order receive `500 Internal Server Error`).
- **Event publishing:** Appends the completion event to the event store and publishes [[event|OrderStatusChangedToCompleteIntegrationEvent]] via transactional outbox to [[channel|bookworm.{env}.ordering.order-status-change-to-complete]] (partitioned by `OrderId`).
- **Idempotency key lifecycle:** Claims the `x-request-id` key in Redis for 3600 seconds (`409 Conflict` on replay) and deletes the key if the operation fails with `5xx` so retries can proceed.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :---------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------- |
| `400 Bad Request` | Missing or whitespace `x-request-id` header, or invalid user identifier claim | Provide a non-empty `x-request-id` header and valid token claims; do not retry unchanged |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID bearer token | Acquire a fresh Entra ID access token and retry |
| `403 Forbidden` | Caller lacks `customer`/`admin` role or `ordering_read`/`ordering_write` scopes | Request the required Entra ID role and scopes before retrying |
| `404 Not Found` | Order does not exist, is soft-deleted, belongs to another buyer, or (for `admin`) is not in `New` status | Verify the `orderId` and current order status; do not retry unchanged |
| `409 Conflict` | Duplicate `x-request-id` for this path within the 3600-second TTL | Treat as a duplicate submission and query order status before taking further action |
| `412 Precondition Failed` | Concurrent update conflict on the order or event stream | Refresh order state and retry with a new `x-request-id` if still `New` |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Customer attempted to complete an owned order already in `Completed` or `Cancelled` status, or unhandled server failure | Inspect the order's current status; do not retry non-`New` transitions |
## Related Documentation
- [[service|order-api]] — Service architecture, persistence, and endpoints.
- [[entity|order]] — Order aggregate invariants and lifecycle statuses.
- [[event|OrderStatusChangedToCompleteIntegrationEvent]] — Kafka event emitted on completion.
- [[channel|bookworm.{env}.ordering.order-status-change-to-complete]] — Kafka topic specification.
- [[command|CancelOrder]] — Transition a `New` order to `Cancelled`.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "CompleteOrderRequest",
"description": "Path and header parameters for completing an Order. The operation has no request body.",
"type": "object",
"required": ["orderId", "x-request-id"],
"properties": {
"orderId": {
"type": "string",
"description": "Unique identifier of the Order to complete."
},
"x-request-id": {
"type": "string",
"description": "Idempotency key for the completion request."
}
}
}
---
id: CompleteOrderCommand
name: Send order completed notification
version: 1.0.0
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
summary: |
Shared Finance completion command consumed by Notification to render
and submit a completed-order email.
schemaPath: schema.json
owners:
- platform-engineering-team
---
`CompleteOrderCommand` is an asynchronous Kafka integration command published by [[service|order-orchestration]] and consumed by [[service|notification-api]] to render and submit a completed-order customer email. It never mutates order state in [[service|order-api]].
## Overview
| Property | Value |
| :----------------------------------- | :----------------------------------------------------------------------------------- |
| **Bounded Context** | Platform / Notifications |
| **Producer** | [[service\|order-orchestration]] |
| **Consumer(s)** | [[service\|notification-api]] |
| **Protocol / Format** | Kafka + CloudEvents JSON (camelCase payload) |
| **Channel / Topic** | [[channel\|bookworm.{env}.finance.complete-order]] |
| **Dead-Letter Channel** | [[channel\|bookworm.{env}.notification.dead-letter-queue]] |
| **Partition Key** | `OrderId` |
| **Delivery / Idempotency Guarantee** | At-least-once delivery; consumed with Redis-backed 24-hour idempotency keyed by `id` |
:::note
`CompleteOrderCommand` requests a completion confirmation email only. To transition an order's authoritative status to `Completed`, call [[command|CompleteOrder]].
:::
## Payload Fields & Envelope
### Command Payload
| Name | Type | Required | Constraints | Description |
| :------------- | :--------------------- | :------- | :-------------------------------------------- | :------------------------------------------------------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | UUIDv7 | Unique message identifier used for 24-hour Redis deduplication |
| `creationDate` | `string` (`date-time`) | Yes | ISO 8601 UTC timestamp | UTC timestamp when the command was created |
| `orderId` | `string` (`uuid`) | Yes | Valid UUID; Kafka partition key | Identifier of the completed order |
| `fullName` | `string \| null` | No | Nullable (defaults to `"Customer"` when null) | Customer display name |
| `email` | `string \| null` | No | Nullable | Recipient email address; null, empty, or whitespace values skip email rendering and delivery |
| `totalMoney` | `number` | Yes | Non-negative monetary amount | Final order total displayed in the completion email template |
## Delivery Guarantees & Error Handling
| Condition | System Behavior | Recovery / Compensation |
| :--------------------------------- | :---------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------- |
| Duplicate delivery within 24 hours | Consumer skips reprocessing via Redis-backed 24-hour idempotency keyed by `id` | Safe at-least-once delivery; newly published commands with a different `id` execute again |
| Blank or `null` `email` | Consumer returns without error and skips template rendering and SMTP submission | No action required |
| Transient SMTP or network failure | Retried by the notification resilience pipeline (circuit breaker, exponential backoff with jitter, `30s` timeout) | Exhausted retries route to [[channel\|bookworm.{env}.notification.dead-letter-queue]] |
| Permanent SMTP failure | Retried with cooldown (`50ms`, `250ms`, `1s` with full jitter) | Routed to [[channel\|bookworm.{env}.notification.dead-letter-queue]] |
## Related Documentation
- [[service|notification-api]] — Stateless email worker architecture and SMTP configuration.
- [[service|order-orchestration]] — Producing orchestration service.
- [[channel|bookworm.{env}.finance.complete-order]] — Kafka channel specification.
- [[channel|bookworm.{env}.notification.dead-letter-queue]] — Dead-letter queue for failed Notification consumers.
- [[event|OrderStatusChangedToCompleteIntegrationEvent]] — Upstream Ordering event that triggers completion notification.
- [[command|CompleteOrder]] — Ordering API HTTP command that completes an order.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "CompleteOrderCommand",
"type": "object",
"additionalProperties": false,
"required": ["id", "creationDate", "orderId", "totalMoney"],
"properties": {
"id": { "type": "string", "format": "uuid" },
"creationDate": { "type": "string", "format": "date-time" },
"orderId": { "type": "string", "format": "uuid" },
"fullName": { "type": ["string", "null"] },
"email": { "type": ["string", "null"] },
"totalMoney": { "type": "number" }
}
}
---
id: CreateAuthor
name: Create author
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Creates an author in the Catalog.
owners:
- catalog-experience-team
schemaPath: schema.json
operation:
method: POST
path: /api/v1/authors
statusCodes: ["200", "400"]
sidebar:
badge: "POST"
---
`CreateAuthor` creates a new author record in [[service|catalog-api]] (`POST /catalog/api/v1/authors`) and returns its generated UUIDv7 identifier as a JSON string. Callers use the returned identifier when linking authors to books in [[command|CreateBook]] and [[command|UpdateBook]].
## Overview
| Property | Value |
| :--------------------------------- | :---------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | HTTP `POST`, `application/json` request and JSON string response |
| **Gateway Endpoint** | `POST /catalog/api/v1/authors` (service path `/api/v1/authors`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `business_user` policy (role `business_user` or `admin` and scopes `catalog_read`, `catalog_write`) |
| **Idempotency / Concurrency** | Not idempotent; no `x-request-id` header is required or enforced |
| **Rate Limit / Caching** | Global concurrency (`100`) and fixed-window (`30 req/min`) limiters plus per-user token bucket; invalidates author list cache |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Request Body (`application/json`)
Leading and trailing whitespace is trimmed from string properties during deserialization.
| Name | Type | Required | Constraints | Description |
| :----- | :------- | :------- | :------------------------------ | :------------------------- |
| `name` | `string` | Yes | Non-empty, max `100` characters | Display name of the author |
### Success Response (`200 OK`)
Returns `200 OK` without a `Location` header.
| Name | Type | Required | Constraints | Description |
| :--------- | :------- | :------- | :---------- | :------------------------------------------------ |
| Root value | `string` | Yes | UUIDv7 | Generated unique identifier of the created author |
## Behavior & Side Effects
- **Persistence:** Inserts a new [[entity|author]] record with a generated UUIDv7 primary key; duplicate author names are permitted and create distinct records.
- **Cache invalidation:** Clears the cached author list (`catalog:authors:v1`) upon successful creation.
- **Vector indexing:** No vector-index refresh is queued on author creation; vector updates are triggered only when an existing author is updated or deleted.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :---------------------------------------------------------------------------------------------- | :--------------------------------------------------- |
| `400 Bad Request` | `name` is missing, empty, whitespace-only, exceeds `100` characters, or payload is malformed | Fix the request body; do not retry unchanged input |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID JWT | Acquire a valid Entra ID access token and retry |
| `403 Forbidden` | Token lacks role `business_user` or `admin`, or lacks scopes `catalog_read` and `catalog_write` | Request the required Entra ID app role and scopes |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Unhandled server or database failure (`traceId` included) | Inspect service logs using `traceId` before retrying |
## Related Documentation
- [[service|catalog-api]] — Service overview, routing, and authorization policies.
- [[entity|author]] — Author entity model.
- [[command|UpdateAuthor]] — Rename an existing author.
- [[command|DeleteAuthor]] — Remove an author with no linked books.
- [[command|CreateBook]] — Link created authors to a new book listing.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "CreateAuthor",
"description": "Payload for CreateAuthor.",
"type": "object",
"additionalProperties": false,
"required": ["name"],
"properties": {
"name": {
"type": "string",
"minLength": 1,
"description": "Display name of the catalog resource."
}
}
}
---
id: CreateBasket
name: Create basket
version: 1.0.0
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
summary: Creates a basket containing the supplied item identifiers and quantities.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
operation:
method: POST
path: /api/v1/baskets
statusCodes: ["201", "400"]
sidebar:
badge: "POST"
---
`CreateBasket` creates a customer-scoped [[entity|basket]] in [[service|basket-api]] (`POST /basket/api/v1/baskets`) with an initial non-empty list of book items and quantities, returning the authenticated customer's identifier. It persists the basket directly in Redis and overwrites any existing basket for the same customer.
## Overview
| Property | Value |
| :--------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Shopping |
| **Owner Service** | [[service\|basket-api]] |
| **Protocol / Format** | HTTP `POST`, `application/json` request and response |
| **Gateway Endpoint** | `POST /basket/api/v1/baskets` (service path `/api/v1/baskets`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `customer` role plus scopes `basket_read`, `basket_write` |
| **Idempotency / Concurrency** | Overwrites any existing basket for the authenticated customer; no `x-request-id` header is enforced |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` tokens, `+20` per `10s`, queue `5`); stored in Redis with no TTL |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Request Body (`application/json`)
| Name | Type | Required | Constraints | Description |
| :----------------- | :--------- | :------- | :--------------- | :------------------------------------------------------------ |
| `items` | `object[]` | Yes | Non-empty array | Initial collection of books to store in the customer's basket |
| `items[].id` | `string` | Yes | Non-empty string | Identifier of the Catalog book |
| `items[].quantity` | `integer` | Yes | `>= 1` | Requested unit quantity for the book |
### Success Response (`201 Created`)
| Name | Type | Required | Constraints | Description |
| :---------------- | :------- | :------- | :----------------------------------------------- | :------------------------------------------ |
| `Location` header | `string` | Yes | Relative path `/api/v1/baskets?id=` | URI to retrieve the created basket |
| Root body | `string` | Yes | Derived from caller's `NameIdentifier` claim | Authenticated customer ID owning the basket |
## Behavior & Side Effects
- **Customer scoping:** Resolves the basket owner exclusively from the JWT `NameIdentifier` claim; callers cannot supply a customer ID in the request body or route.
- **Redis storage & overwrite semantics:** Persists the basket as camelCase JSON in Redis (`basket:{userId}`) with no expiration (TTL), overwriting any existing basket for the same customer.
- **Deferred catalog enrichment:** Stores only book IDs and quantities; book titles and prices are resolved on read via [[query|GetBasket]].
- **No integration events:** HTTP basket creation does not publish any Kafka integration events.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :--------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------- |
| `400 Bad Request` | Missing `items`, empty `items` array, empty `items[].id`, `items[].quantity <= 0`, or malformed JSON | Fix the failing fields and resubmit |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID bearer token | Acquire a valid Entra ID access token and retry |
| `403 Forbidden` | Valid token missing the `customer` role or `basket_read`/`basket_write` scopes | Request a token with the required role and scopes |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Redis write failed or unexpected server error (`traceId` included) | Retry with exponential backoff; inspect service logs using `traceId` |
## Related Documentation
- [[service|basket-api]] — Service overview, Redis storage, and authorization policy.
- [[entity|basket]] — Basket entity model.
- [[command|UpdateBasket]] — Replace all items in an existing basket.
- [[command|DeleteBasket]] — Remove the authenticated customer's basket.
- [[query|GetBasket]] — Retrieve the current basket enriched with Catalog titles and prices.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "CreateBasketCommand",
"type": "object",
"required": ["items"],
"properties": {
"items": {
"type": "array",
"items": {
"type": "object",
"required": ["id", "quantity"],
"properties": {
"id": {
"type": "string"
},
"quantity": {
"type": ["integer", "string"],
"format": "int32",
"pattern": "^-?(?:0|[1-9]\\d*)$"
}
}
}
}
}
}
---
id: CreateBook
name: Create book
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Creates a book listing and returns its generated UUID.
owners:
- catalog-experience-team
schemaPath: schema.json
operation:
method: POST
path: /api/v1/books
statusCodes: ["201", "400"]
sidebar:
badge: "POST"
---
`CreateBook` creates a new book listing in [[service|catalog-api]] (`POST /catalog/api/v1/books`) from a `multipart/form-data` payload, optionally associates a cover image, and returns `201 Created` with the generated UUIDv7 and a `Location` header.
## Overview
| Property | Value |
| :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | HTTP `POST`, `multipart/form-data` request, JSON string response |
| **Gateway Endpoint** | `POST /catalog/api/v1/books` (service path `/api/v1/books`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `business_user` policy (role `business_user` or `admin` and scopes `catalog_read`, `catalog_write`) |
| **Idempotency / Concurrency** | Not idempotent; no `x-request-id` header is required or enforced |
| **Rate Limit / Caching** | Global concurrency (`100`) and fixed-window (`30 req/min`) limiters plus per-user token bucket; invalidates book list and search caches |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Request Form Fields (`multipart/form-data`)
| Name | Type | Required | Constraints | Description |
| :------------ | :-------------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------ |
| `name` | `string` | Yes | Non-empty, max `50` characters | Book title |
| `description` | `string` | No | Default `""`, max `500` characters | Book summary text |
| `price` | `number` | Yes | Strictly `> 0` (`numeric(18,2)`) | Regular catalog price |
| `priceSale` | `number \| null` | No | When provided: strictly `> 0` and `<= price` | Optional promotional sale price |
| `categoryId` | `string` (`uuid`) | Yes | Non-empty UUID; must reference an existing category | Category identifier |
| `publisherId` | `string` (`uuid`) | Yes | Non-empty UUID; must reference an existing publisher | Publisher identifier |
| `authorIds` | `string[]` (`uuid[]`) | Yes | Non-empty array (`>= 1` UUID); repeat `authorIds` form fields for multiple authors | Author identifiers associated with the book |
| `image` | `string` (`binary`) | No | Max `1,048,576` bytes (1 MB); `image/jpeg` (`.jpg`, `.jpeg`), `image/png` (`.png`), or `image/webp` (`.webp`); extension must match content type | Optional cover image upload |
### Success Response (`201 Created`)
| Name | Type | Required | Constraints | Description |
| :---------------- | :------- | :------- | :--------------------------------- | :---------------------------------------------- |
| `Location` header | `string` | Yes | Relative path `/api/v1/books/{id}` | URI of the created book resource |
| Root body | `string` | Yes | UUIDv7 | Generated unique identifier of the created book |
## Behavior & Side Effects
- **Transactional persistence:** Saves the [[entity|book]] with initial status `InStock`, `averageRating = 0.0`, `totalReviews = 0`, and `isDeleted = false`.
- **Cache invalidation:** Invalidates cached book lists (`books:list`) and search results (`books:search`).
- **Vector index queueing:** Database triggers enqueue the new book ID for asynchronous vector embedding refresh by [[service|catalog-ingestion]] (every 5 minutes via [[channel|scheduler.process-vector-batch]]).
:::warning
**Known runtime behavior:** Due to a response-type mismatch in the mediator pre-processing pipeline for this command, the cover image upload step does not execute automatically during book creation. Upload or update cover images via [[command|UpdateBook]] until the pipeline registration is aligned.
:::
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------- |
| `400 Bad Request` | Validation failure (missing required fields, `price <= 0`, `priceSale <= 0` or `> price`, length exceeded, invalid image size/type/extension) or malformed multipart payload | Fix invalid form fields or file upload; do not retry unchanged input |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID JWT | Acquire a valid Entra ID access token and retry |
| `403 Forbidden` | Token lacks role `business_user` or `admin`, or lacks scopes `catalog_read` and `catalog_write` | Request the required Entra ID app role and scopes |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Foreign-key violation (non-existent `categoryId`, `publisherId`, or `authorIds`), blob upload failure, or unhandled server error (`traceId` included) | Verify referenced IDs exist and inspect service logs using `traceId` |
## Related Documentation
- [[service|catalog-api]] — Service overview, routing, and authorization policies.
- [[entity|book]] — Book entity model.
- [[command|UpdateBook]] — Replace an existing book listing and manage cover images.
- [[command|DeleteBook]] — Soft-delete an existing book listing.
- [[command|CreateAuthor]] — Create author records before linking them to books.
- [[command|CreateCategory]] — Create category records before linking them to books.
- [[command|CreatePublisher]] — Create publisher records before linking them to books.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "CreateBook",
"description": "Multipart payload for creating a book listing.",
"type": "object",
"additionalProperties": false,
"required": ["name", "price", "categoryId", "publisherId", "authorIds"],
"properties": {
"name": {
"type": "string",
"minLength": 1,
"description": "Book title."
},
"description": {
"type": "string",
"minLength": 1,
"description": "Book description."
},
"image": {
"type": ["string", "null"],
"contentEncoding": "base64",
"description": "Optional cover image file."
},
"price": {
"type": "number",
"minimum": 0,
"description": "Regular price."
},
"priceSale": {
"type": ["number", "null"],
"minimum": 0,
"description": "Optional sale price."
},
"categoryId": {
"type": "string",
"format": "uuid",
"description": "Category UUID."
},
"publisherId": {
"type": "string",
"format": "uuid",
"description": "Publisher UUID."
},
"authorIds": {
"type": "array",
"minItems": 1,
"items": {
"type": "string",
"format": "uuid",
"description": "A UUID identifying the resource."
},
"description": "Authors associated with the book."
}
}
}
---
id: CreateBuyer
name: Create buyer
version: 1.0.0
badges:
- content: Customer Management
backgroundColor: orange
textColor: orange
summary: Creates a Buyer profile for the authenticated customer from the supplied address.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
operation:
method: POST
path: /api/v1/buyers
statusCodes: ["201", "400"]
sidebar:
badge: "POST"
---
`CreateBuyer` creates a [[entity|buyer]] profile in [[service|order-api]] (`POST /ordering/api/v1/buyers`) using the supplied shipping address while deriving the buyer's identifier and display name from the authenticated Microsoft Entra ID token.
## Overview
| Property | Value |
| :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Ordering |
| **Owner Service** | [[service\|order-api]] |
| **Protocol / Format** | HTTP `POST`, `application/json` request and response |
| **Gateway Endpoint** | `POST /ordering/api/v1/buyers` (service path `/api/v1/buyers`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `customer` or `admin` role plus scopes `ordering_read`, `ordering_write` |
| **Idempotency / Concurrency** | Required `x-request-id` header (Redis-backed 3600s TTL; returns `409 Conflict` on duplicate) |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` burst, `20` per `10s`, queue `5`) |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Request Headers
| Name | Type | Required | Constraints | Description |
| :------------- | :------- | :------- | :------------------------ | :----------------------------------------------------------------- |
| `x-request-id` | `string` | Yes | Non-empty, non-whitespace | Client-generated idempotency key tracked in Redis for 3600 seconds |
### Request Body (`application/json`)
| Name | Type | Required | Constraints | Description |
| :--------- | :------- | :------- | :--------------------------------------------------- | :----------------------------- |
| `street` | `string` | Yes | Non-empty, max `50` characters; PII-redacted in logs | Street address of the buyer |
| `city` | `string` | Yes | Non-empty, max `50` characters; PII-redacted in logs | City or district of the buyer |
| `province` | `string` | Yes | Non-empty, max `50` characters; PII-redacted in logs | Province or state of the buyer |
### Success Response (`201 Created`)
| Name | Type | Required | Constraints | Description |
| :---------------- | :---------------- | :------- | :-------------------------------------- | :------------------------------------- |
| `Location` header | `string` | Yes | Relative path `/api/v1/buyers/{id}` | URI to fetch the created buyer profile |
| Root body | `string` (`uuid`) | Yes | Matches caller's `NameIdentifier` claim | Newly created buyer identifier |
## Behavior & Side Effects
- **Identity derivation:** Extracts the buyer ID from the `NameIdentifier` claim (must be a valid UUID) and the display name from the `name` claim (falling back to `"anonymous"` if absent; stored max length `20` characters).
- **Transactional persistence:** Persists the [[entity|buyer]] aggregate and address value object inside a database transaction; emits no domain or integration events.
- **PII redaction:** Address fields (`street`, `city`, `province`) are automatically redacted in structured logs.
- **Idempotency key lifecycle:** Claims `x-request-id` in Redis for 3600 seconds (`409 Conflict` on replay) and deletes the key if the operation fails with `5xx`.
:::warning
Because the buyer ID is derived directly from the authenticated user's token, a second `CreateBuyer` call for the same user with a new `x-request-id` collides with the existing primary key and fails with `500 Internal Server Error`. Use [[command|UpdateAddress]] to update an existing profile.
:::
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :--------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------- |
| `400 Bad Request` | Missing `x-request-id` header, empty/whitespace address field, field exceeding `50` characters, or non-UUID `NameIdentifier` claim | Fix headers, payload fields, or token claims; do not retry unchanged |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID bearer token | Acquire a fresh Entra ID access token and retry |
| `403 Forbidden` | Caller lacks `customer`/`admin` role or `ordering_read`/`ordering_write` scopes | Request the required Entra ID role and scopes before retrying |
| `409 Conflict` | Duplicate `x-request-id` for this path within the 3600-second TTL | Treat as a duplicate submission and fetch the profile via [[query\|GetBuyer]] |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Duplicate buyer profile for the authenticated user, display name exceeding `20` characters, or unhandled persistence error | Inspect service logs and verify whether the buyer profile already exists |
## Related Documentation
- [[service|order-api]] — Service architecture, persistence, and endpoints.
- [[entity|buyer]] — Buyer aggregate schema and address value object.
- [[command|UpdateAddress]] — Update the authenticated customer's address.
- [[command|DeleteBuyer]] — Administrative permanent removal of a buyer profile.
- [[query|GetBuyer]] — Retrieve a buyer profile.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "CreateBuyerCommand",
"description": "Address fields required to create a Buyer profile.",
"type": "object",
"required": ["street", "city", "province"],
"properties": {
"street": {
"type": "string"
},
"city": {
"type": "string"
},
"province": {
"type": "string"
}
}
}
---
id: CreateCategory
name: Create category
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Creates a category in the Catalog.
owners:
- catalog-experience-team
schemaPath: schema.json
operation:
method: POST
path: /api/v1/categories
statusCodes: ["200", "400"]
sidebar:
badge: "POST"
---
`CreateCategory` creates a new book category in [[service|catalog-api]] (`POST /catalog/api/v1/categories`) and returns its generated UUIDv7 identifier as a JSON string. Callers use the returned identifier when assigning categories in [[command|CreateBook]] and [[command|UpdateBook]].
## Overview
| Property | Value |
| :--------------------------------- | :------------------------------------------------------------------------------------------------------------------------------ |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | HTTP `POST`, `application/json` request and JSON string response |
| **Gateway Endpoint** | `POST /catalog/api/v1/categories` (service path `/api/v1/categories`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `business_user` policy (role `business_user` or `admin` and scopes `catalog_read`, `catalog_write`) |
| **Idempotency / Concurrency** | Not idempotent; duplicate names violate the unique name constraint, and no `x-request-id` header is enforced |
| **Rate Limit / Caching** | Global concurrency (`100`) and fixed-window (`30 req/min`) limiters plus per-user token bucket; invalidates category list cache |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Request Body (`application/json`)
Leading and trailing whitespace is trimmed from string properties during deserialization.
| Name | Type | Required | Constraints | Description |
| :----- | :------- | :------- | :------------------------------------- | :--------------------------- |
| `name` | `string` | Yes | Non-empty, max `50` characters, unique | Display name of the category |
### Success Response (`200 OK`)
Returns `200 OK` without a `Location` header.
| Name | Type | Required | Constraints | Description |
| :--------- | :------- | :------- | :---------- | :-------------------------------------------------- |
| Root value | `string` | Yes | UUIDv7 | Generated unique identifier of the created category |
## Behavior & Side Effects
- **Persistence & uniqueness:** Inserts a new [[entity|category]] record with a generated UUIDv7 primary key; category names are unique-indexed, so submitting an existing name fails with `500 Internal Server Error`.
- **Cache invalidation:** Clears the cached category list (`catalog:categories:v1`) upon successful creation.
- **Vector indexing:** No vector-index refresh is queued on category creation; vector updates are triggered only when an existing category is updated or deleted.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :---------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------ |
| `400 Bad Request` | `name` is missing, empty, whitespace-only, exceeds `50` characters, or payload is malformed | Fix the request body; do not retry unchanged input |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID JWT | Acquire a valid Entra ID access token and retry |
| `403 Forbidden` | Token lacks role `business_user` or `admin`, or lacks scopes `catalog_read` and `catalog_write` | Request the required Entra ID app role and scopes |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Duplicate `name` violating the unique constraint or unhandled server error (`traceId` included) | Check existing categories for a duplicate name and inspect logs using `traceId` |
## Related Documentation
- [[service|catalog-api]] — Service overview, routing, and authorization policies.
- [[entity|category]] — Category entity model.
- [[command|UpdateCategory]] — Rename an existing category.
- [[command|DeleteCategory]] — Remove a category with no active books.
- [[command|CreateBook]] — Assign a category to a new book listing.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "CreateCategory",
"description": "Payload for CreateCategory.",
"type": "object",
"additionalProperties": false,
"required": ["name"],
"properties": {
"name": {
"type": "string",
"minLength": 1,
"description": "Display name of the catalog resource."
}
}
}
---
id: CreateFeedback
name: Create feedback
version: 1.0.0
badges:
- content: Reviews
backgroundColor: purple
textColor: purple
summary: Creates a feedback rating for a Catalog book and returns its generated UUID.
owners:
- catalog-experience-team
schemaPath: schema.json
operation:
method: POST
path: /api/v1/feedbacks
statusCodes: ["200", "400"]
sidebar:
badge: "POST"
---
`CreateFeedback` creates an individual [[entity|feedback]] record for a Catalog book in [[service|rating-api]] (`POST /rating/api/v1/feedbacks`), persists it to Azure Cosmos DB, publishes [[event|FeedbackCreatedIntegrationEvent]] to Kafka, and returns the generated UUIDv7 feedback identifier (`200 OK`).
## Overview
| Property | Value |
| :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Reviews |
| **Owner Service** | [[service\|rating-api]] |
| **Protocol / Format** | HTTP `POST`, `application/json` request and response |
| **Gateway Endpoint** | `POST /rating/api/v1/feedbacks` (service path `/api/v1/feedbacks`) |
| **Authentication & Authorization** | None enforced (optional Microsoft Entra ID JWT partitions per-user rate limiting when present) |
| **Idempotency / Concurrency** | Not idempotent; Cosmos DB ETag optimistic concurrency on persistence |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` tokens, `+20` per `10s`, queue `5`); invalidates feedback list and empty summary caches |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Request Headers
| Name | Type | Required | Constraints | Description |
| :-------------- | :------- | :------- | :---------------------- | :------------------------------------------------------------- |
| `Content-Type` | `string` | Yes | `application/json` | JSON request media type |
| `Authorization` | `string` | No | `Bearer ` | Optional Entra ID JWT used to partition per-user rate limiting |
### Request Body (`application/json`)
| Name | Type | Required | Constraints | Description |
| :---------- | :---------------- | :------- | :--------------------------------------------------- | :-------------------------------------------- |
| `bookId` | `string` (`uuid`) | Yes | Non-empty UUID; Cosmos DB partition key | Identifier of the Catalog book being reviewed |
| `firstName` | `string` | Yes | Non-empty, max `50` characters; PII-redacted in logs | Reviewer's first name |
| `lastName` | `string` | Yes | Non-empty, max `50` characters; PII-redacted in logs | Reviewer's last name |
| `comment` | `string \| null` | No | Max `1000` characters when provided | Optional written review comment |
| `rating` | `integer` | Yes | Inclusive range `0`-`5` | Whole-number star rating for the book |
### Success Response (`200 OK`)
| Name | Type | Required | Constraints | Description |
| :--------- | :---------------- | :------- | :---------- | :--------------------------------------------------------- |
| Root value | `string` (`uuid`) | Yes | UUIDv7 | Generated unique identifier of the created feedback record |
## Behavior & Side Effects
- **Azure Cosmos DB persistence:** Persists the [[entity|feedback]] document to Cosmos DB (`ratingdb`/`feedbacks`, partitioned by `/bookId`).
- **Kafka integration event:** Publishes [[event|FeedbackCreatedIntegrationEvent]] to [[channel|bookworm.{env}.rating.feedback-create]] so [[service|catalog-api]] updates the book's derived rating summary.
- **Compensating rollback:** If [[service|catalog-api]] cannot find the target book and emits [[event|BookUpdatedRatingFailedIntegrationEvent]], [[service|rating-api]] deletes the orphaned feedback record and invalidates caches.
- **Cache invalidation:** Clears cached feedback list entries tagged for `bookId` and clears any cached AI summary whose `reviewCount` is `0`.
- **PII log redaction:** `firstName` and `lastName` are automatically redacted in structured logs.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------------------------------------------- |
| `400 Bad Request` | Empty `bookId`, empty or `>50`-char `firstName`/`lastName`, `>1000`-char `comment`, `rating` outside `0`-`5`, or malformed JSON | Fix the failing fields and resubmit |
| `409 Conflict` | Cosmos DB conflict or concurrency exception | Refresh state or verify whether feedback already exists before retrying |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Unexpected Cosmos DB, Kafka, or server failure (`traceId` included) | Retry with exponential backoff; inspect service logs using `traceId` |
## Related Documentation
- [[service|rating-api]] — Service overview, Azure Cosmos DB storage, and AI summarizer.
- [[entity|feedback]] — Feedback document model.
- [[command|DeleteFeedback]] — Remove a feedback record as an administrator.
- [[event|FeedbackCreatedIntegrationEvent]] — Kafka event published on creation.
- [[query|ListFeedbacks]] — Paginate feedback records for a book.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "CreateFeedbackCommand",
"type": "object",
"additionalProperties": false,
"required": ["bookId", "firstName", "lastName", "rating"],
"properties": {
"bookId": {
"type": "string",
"format": "uuid",
"description": "Identifier of the Catalog book being reviewed."
},
"firstName": {
"type": "string",
"minLength": 1,
"maxLength": 50,
"description": "First name of the reviewer."
},
"lastName": {
"type": "string",
"minLength": 1,
"maxLength": 50,
"description": "Last name of the reviewer."
},
"comment": {
"type": ["string", "null"],
"maxLength": 1000,
"description": "Optional written feedback."
},
"rating": {
"type": "integer",
"minimum": 0,
"maximum": 5,
"description": "Rating value from 0 through 5."
}
}
}
---
id: CreateOrder
name: Create order
version: 1.0.0
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
summary: Creates an Order for the authenticated Buyer using the current basket and Catalog pricing.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
operation:
method: POST
path: /api/v1/orders
statusCodes: ["201"]
sidebar:
badge: "POST"
---
`CreateOrder` creates a `New` order in [[service|order-api]] (`POST /ordering/api/v1/orders`) for the authenticated buyer by reading the caller's active basket from [[service|basket-api]] over gRPC and resolving current prices from [[service|catalog-api]] over gRPC.
## Overview
| Property | Value |
| :--------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Ordering |
| **Owner Service** | [[service\|order-api]] |
| **Protocol / Format** | HTTP `POST`, `application/json` UUID response |
| **Gateway Endpoint** | `POST /ordering/api/v1/orders` (service path `/api/v1/orders`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `customer` or `admin` role plus scopes `ordering_read`, `ordering_write` |
| **Idempotency / Concurrency** | Required `x-request-id` header (Redis-backed 3600s TTL; returns `409 Conflict` on duplicate); per-buyer Redis distributed lock (`order-create:{userId}`, 1-minute TTL) |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` burst, `20` per `10s`, queue `5`) |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Request Headers
Accepts no request body; basket items and unit prices are resolved server-side.
| Name | Type | Required | Constraints | Description |
| :------------- | :------- | :------- | :------------------------ | :----------------------------------------------------------------- |
| `x-request-id` | `string` | Yes | Non-empty, non-whitespace | Client-generated idempotency key tracked in Redis for 3600 seconds |
### Success Response (`201 Created`)
| Name | Type | Required | Constraints | Description |
| :---------------- | :---------------- | :------- | :---------------------------------- | :----------------------------- |
| `Location` header | `string` | Yes | Relative path `/api/v1/orders/{id}` | URI to fetch the created order |
| Root body | `string` (`uuid`) | Yes | UUIDv7 | Newly created order identifier |
## Behavior & Side Effects
- **Server-side basket and price resolution:** Fetches the buyer's basket via [[query|GetBasketGrpc]] (10s deadline) and resolves authoritative book pricing (`priceSale ?? price`) via [[query|GetBooksGrpc]] (10s deadline). Missing catalog books return `404 Not Found`.
- **Distributed per-buyer lock:** Acquires a 1-minute Redis distributed lock (`order-create:{userId}`) to prevent concurrent checkouts by the same buyer (`409 Conflict` if already held).
- **Persistence and event pipeline:** Saves the [[entity|order]] in `New` status, appends the placement event to the event store, and publishes [[event|UserCheckedOutIntegrationEvent]] via transactional outbox to [[channel|bookworm.{env}.ordering.user-checked-out]] (partitioned by `OrderId`) to start [[service|order-orchestration]].
- **Idempotency key lifecycle:** Claims `x-request-id` in Redis for 3600 seconds (`409 Conflict` on replay) and deletes the key if the operation fails with `5xx`.
:::note
[[query|GetBasketGrpc]] returns an empty response when no basket exists rather than `NotFound`, and `CreateOrder` does not reject an empty item list—an empty basket proceeds to persistence and returns `201 Created` if saved.
:::
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------- |
| `400 Bad Request` | Missing or whitespace `x-request-id` header, or non-UUID `NameIdentifier` claim | Provide a non-empty `x-request-id` header and valid token claims; do not retry unchanged |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID bearer token | Acquire a fresh Entra ID access token and retry |
| `403 Forbidden` | Caller lacks `customer`/`admin` role or `ordering_read`/`ordering_write` scopes | Request the required Entra ID role and scopes before retrying |
| `404 Not Found` | One or more basket book IDs do not exist in [[service\|catalog-api]] | Refresh the customer's basket to remove unavailable items before retrying with a new `x-request-id` |
| `409 Conflict` | Duplicate `x-request-id` within the 3600-second TTL, or concurrent checkout lock held for the same buyer | Wait for the in-flight checkout to finish and query order history before retrying |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Upstream gRPC timeout/error or persistence failure | Retry with backoff; the Redis idempotency key is cleared on `5xx` |
## Related Documentation
- [[service|order-api]] — Service architecture, persistence, and endpoints.
- [[entity|order]] — Order aggregate invariants and lifecycle statuses.
- [[event|UserCheckedOutIntegrationEvent]] — Kafka event published after order creation.
- [[channel|bookworm.{env}.ordering.user-checked-out]] — Kafka topic specification.
- [[service|basket-api]] — Upstream gRPC source for customer baskets.
- [[service|catalog-api]] — Upstream gRPC source for authoritative book pricing.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "CreateOrderRequest",
"description": "Required request header for creating an Order. The operation has no request body.",
"type": "object",
"required": ["x-request-id"],
"properties": {
"x-request-id": {
"type": "string",
"description": "Idempotency key for the Order creation request."
}
}
}
---
id: CreatePublisher
name: Create publisher
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Creates a publisher in the Catalog.
owners:
- catalog-experience-team
schemaPath: schema.json
operation:
method: POST
path: /api/v1/publishers
statusCodes: ["200", "400"]
sidebar:
badge: "POST"
---
`CreatePublisher` creates a new publisher record in [[service|catalog-api]] (`POST /catalog/api/v1/publishers`) and returns its generated UUIDv7 identifier as a JSON string. Callers use the returned identifier when linking publishers in [[command|CreateBook]] and [[command|UpdateBook]].
## Overview
| Property | Value |
| :--------------------------------- | :------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | HTTP `POST`, `application/json` request and JSON string response |
| **Gateway Endpoint** | `POST /catalog/api/v1/publishers` (service path `/api/v1/publishers`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `business_user` policy (role `business_user` or `admin` and scopes `catalog_read`, `catalog_write`) |
| **Idempotency / Concurrency** | Not idempotent; duplicate names violate the unique name constraint, and no `x-request-id` header is enforced |
| **Rate Limit / Caching** | Global concurrency (`100`) and fixed-window (`30 req/min`) limiters plus per-user token bucket; invalidates publisher list cache |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Request Body (`application/json`)
Leading and trailing whitespace is trimmed from string properties during deserialization.
| Name | Type | Required | Constraints | Description |
| :----- | :------- | :------- | :-------------------------------------- | :---------------------------- |
| `name` | `string` | Yes | Non-empty, max `100` characters, unique | Display name of the publisher |
:::note
`CreatePublisher` allows up to `100` characters, whereas [[command|UpdatePublisher]] currently enforces a `50`-character maximum.
:::
### Success Response (`200 OK`)
Returns `200 OK` without a `Location` header.
| Name | Type | Required | Constraints | Description |
| :--------- | :------- | :------- | :---------- | :--------------------------------------------------- |
| Root value | `string` | Yes | UUIDv7 | Generated unique identifier of the created publisher |
## Behavior & Side Effects
- **Persistence & uniqueness:** Inserts a new [[entity|publisher]] record with a generated UUIDv7 primary key; publisher names are unique-indexed, so submitting a duplicate name fails with `500 Internal Server Error`.
- **Cache invalidation:** Clears the cached publisher list (`catalog:publishers:v1`) upon successful creation.
- **Vector indexing:** No vector-index refresh is queued on publisher creation; vector updates are triggered only when an existing publisher is updated or deleted.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :---------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------ |
| `400 Bad Request` | `name` is missing, empty, whitespace-only, exceeds `100` characters, or payload is malformed | Fix the request body; do not retry unchanged input |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID JWT | Acquire a valid Entra ID access token and retry |
| `403 Forbidden` | Token lacks role `business_user` or `admin`, or lacks scopes `catalog_read` and `catalog_write` | Request the required Entra ID app role and scopes |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Duplicate `name` violating the unique constraint or unhandled server error (`traceId` included) | Check existing publishers for a duplicate name and inspect logs using `traceId` |
## Related Documentation
- [[service|catalog-api]] — Service overview, routing, and authorization policies.
- [[entity|publisher]] — Publisher entity model.
- [[command|UpdatePublisher]] — Rename an existing publisher.
- [[command|DeletePublisher]] — Remove a publisher with no active books.
- [[command|CreateBook]] — Assign a publisher to a new book listing.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "CreatePublisher",
"description": "Payload for CreatePublisher.",
"type": "object",
"additionalProperties": false,
"required": ["name"],
"properties": {
"name": {
"type": "string",
"minLength": 1,
"description": "Display name of the catalog resource."
}
}
}
---
id: DeleteAuthor
name: Delete author
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Deletes an existing author from the Catalog.
owners:
- catalog-experience-team
schemaPath: schema.json
operation:
method: DELETE
path: /api/v1/authors/{id}
statusCodes: ["204", "404"]
sidebar:
badge: "DELETE"
---
`DeleteAuthor` permanently deletes an author record from [[service|catalog-api]] (`DELETE /catalog/api/v1/authors/{id}`) and returns `204 No Content`. Deletion is rejected with `400 Bad Request` when any active book references the author.
## Overview
| Property | Value |
| :--------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | HTTP `DELETE`, path parameter only, empty response (`204 No Content`) |
| **Gateway Endpoint** | `DELETE /catalog/api/v1/authors/{id}` (service path `/api/v1/authors/{id}`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `business_user` policy (role `business_user` or `admin` and scopes `catalog_read`, `catalog_write`) |
| **Idempotency / Concurrency** | Not idempotent across retries; repeating a completed delete returns `404 Not Found`; no `x-request-id` header is enforced |
| **Rate Limit / Caching** | Global concurrency (`100`) and fixed-window (`30 req/min`) limiters plus per-user token bucket; invalidates author and book caches |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Path Parameters
| Name | Type | Required | Constraints | Description |
| :--- | :---------------- | :------- | :---------------------------------------------------- | :---------------------------------------- |
| `id` | `string` (`uuid`) | Yes | Valid UUID; must not be referenced by any active book | Unique identifier of the author to delete |
## Behavior & Side Effects
- **Referential integrity guard:** Rejects deletion with `400 Bad Request` (`"Author has books and cannot be deleted"`) if any active (non-soft-deleted) book references the author.
- **Hard delete:** Permanently removes the [[entity|author]] record (no soft delete). If a soft-deleted book still references the author, the database restrict constraint causes `500 Internal Server Error`.
- **Cache invalidation:** Clears `catalog:authors:v1` and invalidates `book` and `books:list` cache tags.
- **Vector index queueing:** Database triggers enqueue any linked book IDs for asynchronous vector reconciliation by [[service|catalog-ingestion]].
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :--------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------- |
| `400 Bad Request` | Author is still linked to one or more active books, or `{id}` is not a valid UUID | Reassign or delete linked books first, or fix the UUID; do not retry unchanged |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID JWT | Acquire a valid Entra ID access token and retry |
| `403 Forbidden` | Token lacks role `business_user` or `admin`, or lacks scopes `catalog_read` and `catalog_write` | Request the required Entra ID app role and scopes |
| `404 Not Found` | No author exists with the supplied `{id}` | Verify the UUID; treat as already absent only if your workflow allows it |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Database restrict constraint failure (e.g., soft-deleted book reference) or unhandled error (`traceId` included) | Inspect service logs using `traceId` |
## Related Documentation
- [[service|catalog-api]] — Service overview, routing, and authorization policies.
- [[entity|author]] — Author entity model.
- [[command|CreateAuthor]] — Create a new author record.
- [[command|UpdateAuthor]] — Rename an existing author.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "DeleteAuthor",
"description": "Path identifier for the author to delete.",
"type": "string",
"format": "uuid"
}
---
id: DeleteBasket
name: Delete basket
version: 1.0.0
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
summary: Deletes the current basket.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
operation:
method: DELETE
path: /api/v1/baskets
statusCodes: ["204", "404"]
sidebar:
badge: "DELETE"
---
`DeleteBasket` removes the authenticated customer's active [[entity|basket]] from Redis in [[service|basket-api]] (`DELETE /basket/api/v1/baskets`) and returns `204 No Content`. This endpoint handles customer-initiated deletion only; post-checkout basket cleanup runs asynchronously over Kafka via [[command|PlaceOrderCommand]].
## Overview
| Property | Value |
| :--------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Shopping |
| **Owner Service** | [[service\|basket-api]] |
| **Protocol / Format** | HTTP `DELETE`, empty request and response (`204 No Content`) |
| **Gateway Endpoint** | `DELETE /basket/api/v1/baskets` (service path `/api/v1/baskets`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `customer` role plus scopes `basket_read`, `basket_write` |
| **Idempotency / Concurrency** | Not idempotent across retries; repeat calls return `404 Not Found` |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` tokens, `+20` per `10s`, queue `5`) |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Request Parameters
Accepts no path parameters, query parameters, or request body.
### Success Response (`204 No Content`)
Empty response body confirms the basket was deleted.
## Behavior & Side Effects
- **Existence check before deletion:** Checks for an active basket under the authenticated user's ID in Redis and returns `404 Not Found` if none exists.
- **No integration events:** HTTP deletion does not publish [[event|BasketDeletedCompleteIntegrationEvent]] or [[event|BasketDeletedFailedIntegrationEvent]]; post-checkout cleanup is handled separately via [[command|PlaceOrderCommand]].
:::note
OpenAPI metadata declares `404 Not Found` as `application/problem+json`, whereas runtime responses return `application/json` with `{ "detail": "The requested resource was not found." }`.
:::
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :----------------------------------------------------------------------------- | :---------------------------------------------------------------------------------- |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID bearer token | Acquire a valid Entra ID access token and retry |
| `403 Forbidden` | Valid token missing the `customer` role or `basket_read`/`basket_write` scopes | Request a token with the required role and scopes |
| `404 Not Found` | No active basket exists in Redis for the authenticated customer | Treat the basket as already cleared or refresh client state; do not retry unchanged |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Unexpected Redis or server failure (`traceId` included) | Retry with exponential backoff; inspect service logs using `traceId` |
## Related Documentation
- [[service|basket-api]] — Service overview, Redis storage, and authorization policy.
- [[entity|basket]] — Basket entity model.
- [[command|CreateBasket]] — Initialize a basket.
- [[command|UpdateBasket]] — Replace all items in an existing basket.
- [[query|GetBasket]] — Retrieve the current basket.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "DeleteBasketRequest",
"description": "The OpenAPI operation defines no request body or parameters.",
"type": "object",
"additionalProperties": false
}
---
id: DeleteBasketCompleteCommand
name: Acknowledge basket deletion completed
version: 1.0.0
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
summary: |
Reports Finance's successful basket-cleanup outcome to Order API without
changing the Order's business status.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
---
`DeleteBasketCompleteCommand` (v1.0.0) is an asynchronous Kafka integration command published by [[service|order-orchestration]] to inform [[service|order-api]] that post-checkout basket cleanup succeeded. [[service|order-api]] logs the outcome for operational visibility without modifying the order's business status.
## Overview
| Property | Value |
| :----------------------------------- | :----------------------------------------------------------------------------- |
| **Bounded Context** | Ordering |
| **Producer** | [[service\|order-orchestration]] |
| **Consumer(s)** | [[service\|order-api]] |
| **Protocol / Format** | Kafka + CloudEvents JSON (camelCase payload) |
| **Channel / Topic** | [[channel\|bookworm.{env}.finance.delete-basket-complete]] |
| **Dead-Letter Channel** | [[channel\|bookworm.{env}.ordering.dead-letter-queue]] |
| **Partition Key** | `OrderId` |
| **Delivery / Idempotency Guarantee** | At-least-once delivery; consumer is side-effect-free (structured logging only) |
:::note
`DeleteBasketCompleteCommand` is distinct from [[event|BasketDeletedCompleteIntegrationEvent]]. [[service|basket-api]] publishes `BasketDeletedCompleteIntegrationEvent` to [[service|order-orchestration]], which then publishes `DeleteBasketCompleteCommand` to [[service|order-api]].
:::
## Payload Fields & Envelope
### Command Payload
| Name | Type | Required | Constraints | Description |
| :------------- | :--------------------- | :------- | :---------------------------------------------------- | :----------------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | UUIDv7 | Unique identifier assigned to the integration message |
| `creationDate` | `string` (`date-time`) | Yes | ISO 8601 UTC timestamp | UTC timestamp when the command was created |
| `orderId` | `string` (`uuid`) | Yes | Valid UUID; Kafka partition key; PII-redacted in logs | Identifier of the order whose basket cleanup succeeded |
| `totalMoney` | `number` | Yes | Non-negative monetary amount | Total purchase amount associated with the order |
## Delivery Guarantees & Error Handling
| Condition | System Behavior | Recovery / Compensation |
| :------------------------------------ | :------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------- |
| Duplicate delivery | Consumer logs the message again with no database or status side effects | Naturally idempotent (no state mutation) |
| Activity publish failure in producer | Durable orchestration retries up to 3 times (`5s` initial delay, `2.0` backoff) | Runs LIFO saga compensations if all retries fail |
| Deserialization or processing failure | Retried with cooldown (`50ms`, `250ms`, `1s` with full jitter) | Exhausted messages route to [[channel\|bookworm.{env}.ordering.dead-letter-queue]] |
## Related Documentation
- [[service|order-api]] — Consuming service and Kafka setup.
- [[service|order-orchestration]] — Producing orchestration service.
- [[channel|bookworm.{env}.finance.delete-basket-complete]] — Kafka topic specification.
- [[channel|bookworm.{env}.ordering.dead-letter-queue]] — Dead-letter queue for failed Ordering consumers.
- [[command|DeleteBasketFailedCommand]] — Companion compensation command that soft-deletes the order.
- [[event|BasketDeletedCompleteIntegrationEvent]] — Upstream event from [[service|basket-api]].
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "DeleteBasketCompleteCommand",
"type": "object",
"additionalProperties": false,
"required": ["id", "creationDate", "orderId", "totalMoney"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "Unique identifier assigned to the integration message."
},
"creationDate": {
"type": "string",
"format": "date-time",
"description": "UTC timestamp when the integration message was created."
},
"orderId": {
"type": "string",
"format": "uuid",
"description": "Identifier of the Order whose basket cleanup completed."
},
"totalMoney": {
"type": "number",
"format": "double",
"description": "Total purchase amount associated with the Order."
}
}
}
---
id: DeleteBasketFailedCommand
name: Handle basket deletion failed
version: 1.0.0
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
summary: |
Reports Finance's failed basket-cleanup outcome so Order API can
soft-delete the affected Order.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
---
`DeleteBasketFailedCommand` (v1.0.0) is an asynchronous Kafka integration command published by [[service|order-orchestration]] instructing [[service|order-api]] to soft-delete an order whose post-checkout basket cleanup failed or whose orchestration rolled back. [[service|order-api]] marks the order deleted without transitioning its business status to `Cancelled`.
## Overview
| Property | Value |
| :----------------------------------- | :----------------------------------------------------------------------------------- |
| **Bounded Context** | Ordering |
| **Producer** | [[service\|order-orchestration]] |
| **Consumer(s)** | [[service\|order-api]] |
| **Protocol / Format** | Kafka + CloudEvents JSON (camelCase payload) |
| **Channel / Topic** | [[channel\|bookworm.{env}.finance.delete-basket-failed]] |
| **Dead-Letter Channel** | [[channel\|bookworm.{env}.ordering.dead-letter-queue]] |
| **Partition Key** | `OrderId` |
| **Delivery / Idempotency Guarantee** | At-least-once delivery; consumed with Redis-backed 24-hour idempotency keyed by `id` |
:::note
`DeleteBasketFailedCommand` is distinct from [[event|BasketDeletedFailedIntegrationEvent]]. [[service|basket-api]] publishes `BasketDeletedFailedIntegrationEvent` to [[service|order-orchestration]], which then publishes `DeleteBasketFailedCommand` to [[service|order-api]].
:::
## Payload Fields & Envelope
### Command Payload
| Name | Type | Required | Constraints | Description |
| :------------- | :--------------------- | :------- | :------------------------------ | :-------------------------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | UUIDv7 | Unique message identifier used as the Redis idempotency key |
| `creationDate` | `string` (`date-time`) | Yes | ISO 8601 UTC timestamp | UTC timestamp when the command was created |
| `basketId` | `string` (`uuid`) | Yes | Valid UUID | Identifier of the basket whose cleanup failed |
| `email` | `string \| null` | Yes | Nullable email string | Customer email address when available (`null` when unavailable) |
| `orderId` | `string` (`uuid`) | Yes | Valid UUID; Kafka partition key | Identifier of the affected order to soft-delete |
| `totalMoney` | `number` | Yes | Non-negative monetary amount | Total purchase amount associated with the order |
## Delivery Guarantees & Error Handling
| Condition | System Behavior | Recovery / Compensation |
| :-------------------------------------- | :----------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------- |
| Duplicate delivery within 24 hours | Consumer skips reprocessing via Redis-backed 24-hour idempotency keyed by `id` | Safe at-least-once delivery |
| Order not found or already soft-deleted | Consumer exits cleanly without error | Naturally idempotent no-op |
| Transient database or broker failure | Retried with cooldown (`50ms`, `250ms`, `1s` with full jitter) | Exhausted messages route to [[channel\|bookworm.{env}.ordering.dead-letter-queue]] |
## Related Documentation
- [[service|order-api]] — Consuming service, soft-delete filter, and Kafka setup.
- [[service|order-orchestration]] — Producing orchestration service.
- [[channel|bookworm.{env}.finance.delete-basket-failed]] — Kafka topic specification.
- [[channel|bookworm.{env}.ordering.dead-letter-queue]] — Dead-letter queue for failed Ordering consumers.
- [[command|DeleteBasketCompleteCommand]] — Companion command for successful basket cleanup.
- [[event|BasketDeletedFailedIntegrationEvent]] — Upstream failure event from [[service|basket-api]].
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "DeleteBasketFailedCommand",
"type": "object",
"additionalProperties": false,
"required": ["id", "creationDate", "basketId", "email", "orderId", "totalMoney"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "Unique identifier assigned to the integration message."
},
"creationDate": {
"type": "string",
"format": "date-time",
"description": "UTC timestamp when the integration message was created."
},
"basketId": {
"type": "string",
"format": "uuid",
"description": "Identifier of the basket whose cleanup failed."
},
"email": {
"type": ["string", "null"],
"format": "email",
"description": "Customer email, when available."
},
"orderId": {
"type": "string",
"format": "uuid",
"description": "Identifier of the affected Order."
},
"totalMoney": {
"type": "number",
"format": "double",
"description": "Total purchase amount associated with the Order."
}
}
}
---
id: DeleteBook
name: Delete book
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Deletes an existing book from the Catalog.
owners:
- catalog-experience-team
schemaPath: schema.json
operation:
method: DELETE
path: /api/v1/books/{id}
statusCodes: ["204", "404"]
sidebar:
badge: "DELETE"
---
`DeleteBook` soft-deletes an existing book listing in [[service|catalog-api]] (`DELETE /catalog/api/v1/books/{id}`) and returns `204 No Content`. It does not permanently erase the database row or delete the book's cover image from blob storage.
## Overview
| Property | Value |
| :--------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | HTTP `DELETE`, path parameter only, empty response (`204 No Content`) |
| **Gateway Endpoint** | `DELETE /catalog/api/v1/books/{id}` (service path `/api/v1/books/{id}`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `business_user` policy (role `business_user` or `admin` and scopes `catalog_read`, `catalog_write`) |
| **Idempotency / Concurrency** | Not idempotent across retries; repeating a completed delete returns `404 Not Found`; no `x-request-id` header is enforced |
| **Rate Limit / Caching** | Global concurrency (`100`) and fixed-window (`30 req/min`) limiters plus per-user token bucket; invalidates book, summary, list, and search caches |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Path Parameters
| Name | Type | Required | Constraints | Description |
| :--- | :---------------- | :------- | :---------- | :------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | Valid UUID | Unique identifier of the book to soft-delete |
## Behavior & Side Effects
- **Soft delete:** Marks the [[entity|book]] as deleted (`is_deleted = true`), hiding it from standard catalog reads and subsequent `DELETE` calls.
- **Cover image retention:** Any cover image stored in `catalog-blob` remains in blob storage after a book is soft-deleted.
- **Cache invalidation:** Clears cached book details (`book:{id}`), book summary (`book:summary:{id}`), and invalidates `books:list` and `books:search` cache tags.
- **Vector index queueing:** Database triggers enqueue the book ID for asynchronous Qdrant vector index reconciliation by [[service|catalog-ingestion]].
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :---------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------ |
| `400 Bad Request` | `{id}` is not a valid UUID | Fix the path parameter; do not retry unchanged |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID JWT | Acquire a valid Entra ID access token and retry |
| `403 Forbidden` | Token lacks role `business_user` or `admin`, or lacks scopes `catalog_read` and `catalog_write` | Request the required Entra ID app role and scopes |
| `404 Not Found` | No active book exists with the supplied `{id}` | Verify the UUID; treat as already deleted only if your workflow allows it |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Unhandled server or database failure (`traceId` included) | Inspect service logs using `traceId` |
## Related Documentation
- [[service|catalog-api]] — Service overview, routing, and authorization policies.
- [[entity|book]] — Book entity model.
- [[command|CreateBook]] — Create a new book listing.
- [[command|UpdateBook]] — Replace book details and manage cover images.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "DeleteBook",
"description": "Path identifier for the book to delete.",
"type": "string",
"format": "uuid"
}
---
id: DeleteBuyer
name: Delete buyer
version: 1.0.0
badges:
- content: Customer Management
backgroundColor: orange
textColor: orange
summary: Deletes a Buyer profile by identifier; the operation is restricted to administrators.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
operation:
method: DELETE
path: /api/v1/buyers/{id}
statusCodes: ["204", "404"]
sidebar:
badge: "DELETE"
---
`DeleteBuyer` permanently removes a [[entity|buyer]] profile from [[service|order-api]] (`DELETE /ordering/api/v1/buyers/{id}`) and returns `204 No Content`. Access is restricted to callers holding the Microsoft Entra ID `admin` role.
## Overview
| Property | Value |
| :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Ordering |
| **Owner Service** | [[service\|order-api]] |
| **Protocol / Format** | HTTP `DELETE`, path parameter only, empty response (`204 No Content`) |
| **Gateway Endpoint** | `DELETE /ordering/api/v1/buyers/{id}` (service path `/api/v1/buyers/{id}`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `admin` policy (role `admin` plus scopes `ordering_read`, `ordering_write`) |
| **Idempotency / Concurrency** | Not idempotent across retries; repeat calls return `404 Not Found`; no `x-request-id` header is required |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` burst, `20` per `10s`, queue `5`) |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Path Parameters
Accepts no request body and requires no `x-request-id` header.
| Name | Type | Required | Constraints | Description |
| :--- | :---------------- | :------- | :------------------------- | :----------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | Path parameter; valid UUID | Unique identifier of the buyer profile to delete |
### Success Response (`204 No Content`)
Empty response body confirms the buyer profile was permanently deleted.
## Behavior & Side Effects
- **Permanent hard delete:** Permanently removes the [[entity|buyer]] row from PostgreSQL (unlike orders, buyers are not soft-deleted).
- **No events emitted:** Deleting a buyer raises no domain events and publishes no Kafka integration events.
:::warning
The `orders.buyer_id` foreign key column is non-nullable while the relationship is configured with `ON DELETE SET NULL`. Attempting to delete a buyer who has existing orders will fail at the database layer and return `500 Internal Server Error`.
:::
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :---------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------- |
| `400 Bad Request` | Path parameter `{id}` is not a valid UUID | Supply a valid UUID; do not retry unchanged |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID bearer token | Acquire a fresh Entra ID access token and retry |
| `403 Forbidden` | Caller lacks the `admin` role or `ordering_read`/`ordering_write` scopes | Authenticate with an `admin` token that includes the required scopes |
| `404 Not Found` | No buyer profile exists with the specified `{id}` | Verify the buyer identifier; treat as already absent if retrying a prior deletion |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Database foreign-key constraint error (e.g., buyer has orders) or unhandled failure | Inspect service logs and check whether dependent orders reference the buyer |
## Related Documentation
- [[service|order-api]] — Service architecture, persistence, and endpoints.
- [[entity|buyer]] — Buyer aggregate schema and constraints.
- [[command|CreateBuyer]] — Create a buyer profile for the authenticated caller.
- [[command|UpdateAddress]] — Update the authenticated customer's address.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "DeleteBuyerRequest",
"description": "Path identifier for the Buyer to delete. The operation has no request body.",
"type": "string"
}
---
id: DeleteCategory
name: Delete category
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Deletes an existing category from the Catalog.
owners:
- catalog-experience-team
schemaPath: schema.json
operation:
method: DELETE
path: /api/v1/categories/{id}
statusCodes: ["204", "404"]
sidebar:
badge: "DELETE"
---
`DeleteCategory` permanently deletes a category record from [[service|catalog-api]] (`DELETE /catalog/api/v1/categories/{id}`) and returns `204 No Content`. Deletion is rejected with `400 Bad Request` when any active book references the category.
## Overview
| Property | Value |
| :--------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | HTTP `DELETE`, path parameter only, empty response (`204 No Content`) |
| **Gateway Endpoint** | `DELETE /catalog/api/v1/categories/{id}` (service path `/api/v1/categories/{id}`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `business_user` policy (role `business_user` or `admin` and scopes `catalog_read`, `catalog_write`) |
| **Idempotency / Concurrency** | Not idempotent across retries; repeating a completed delete returns `404 Not Found`; no `x-request-id` header is enforced |
| **Rate Limit / Caching** | Global concurrency (`100`) and fixed-window (`30 req/min`) limiters plus per-user token bucket; invalidates category and book caches |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Path Parameters
| Name | Type | Required | Constraints | Description |
| :--- | :---------------- | :------- | :---------------------------------------------------- | :------------------------------------------ |
| `id` | `string` (`uuid`) | Yes | Valid UUID; must not be referenced by any active book | Unique identifier of the category to delete |
## Behavior & Side Effects
- **Referential integrity guard:** Rejects deletion with `400 Bad Request` (`"Category has books and cannot be deleted"`) if any active (non-soft-deleted) book references the category.
- **Hard delete:** Permanently removes the [[entity|category]] record (no soft delete); soft-deleted books referencing the category have their category reference set to `NULL`.
- **Cache invalidation:** Clears `catalog:categories:v1` and invalidates `book` and `books:list` cache tags.
- **Vector index queueing:** Database triggers enqueue any linked book IDs for asynchronous vector reconciliation by [[service|catalog-ingestion]].
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :---------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------- |
| `400 Bad Request` | Category is still linked to one or more active books, or `{id}` is not a valid UUID | Reassign or delete linked books first, or fix the UUID; do not retry unchanged |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID JWT | Acquire a valid Entra ID access token and retry |
| `403 Forbidden` | Token lacks role `business_user` or `admin`, or lacks scopes `catalog_read` and `catalog_write` | Request the required Entra ID app role and scopes |
| `404 Not Found` | No category exists with the supplied `{id}` | Verify the UUID; treat as already absent only if your workflow allows it |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Unhandled server or database failure (`traceId` included) | Inspect service logs using `traceId` |
## Related Documentation
- [[service|catalog-api]] — Service overview, routing, and authorization policies.
- [[entity|category]] — Category entity model.
- [[command|CreateCategory]] — Create a new category record.
- [[command|UpdateCategory]] — Rename an existing category.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "DeleteCategory",
"description": "Path identifier for the category to delete.",
"type": "string",
"format": "uuid"
}
---
id: DeleteFeedback
name: Delete feedback
version: 1.0.0
badges:
- content: Reviews
backgroundColor: purple
textColor: purple
summary: Deletes an existing feedback record by its UUID.
owners:
- catalog-experience-team
schemaPath: schema.json
operation:
method: DELETE
path: /api/v1/feedbacks/{id}
statusCodes: ["204", "404"]
sidebar:
badge: "DELETE"
---
`DeleteFeedback` is an administrator-only command in [[service|rating-api]] (`DELETE /rating/api/v1/feedbacks/{id}`) that deletes an existing [[entity|feedback]] record from Azure Cosmos DB, publishes [[event|FeedbackDeletedIntegrationEvent]] to Kafka, invalidates cached feedback lists and summaries, and returns `204 No Content`.
## Overview
| Property | Value |
| :--------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Reviews |
| **Owner Service** | [[service\|rating-api]] |
| **Protocol / Format** | HTTP `DELETE`, path parameter only, empty response (`204 No Content`) |
| **Gateway Endpoint** | `DELETE /rating/api/v1/feedbacks/{id}` (service path `/api/v1/feedbacks/{id}`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `admin` policy (role `admin` and scopes `rating_read`, `rating_write`) |
| **Idempotency / Concurrency** | Not idempotent across retries; repeat calls return `404 Not Found`; Cosmos DB ETag optimistic concurrency |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` tokens, `+20` per `10s`, queue `5`); invalidates feedback list and AI summary caches |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Path Parameters
Accepts no request body.
| Name | Type | Required | Constraints | Description |
| :--- | :---------------- | :------- | :---------- | :------------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | Valid UUID | Unique identifier of the feedback record to delete |
### Success Response (`204 No Content`)
Empty response body confirms the feedback record was deleted.
## Behavior & Side Effects
- **Azure Cosmos DB deletion:** Queries Cosmos DB (`ratingdb`/`feedbacks`, partition key `/bookId`), deletes the record with ETag concurrency protection, and returns `404 Not Found` if absent.
- **Kafka integration event:** Publishes [[event|FeedbackDeletedIntegrationEvent]] to [[channel|bookworm.{env}.rating.feedback-delete]] so [[service|catalog-api]] recalculates the book's derived rating summary.
- **Cache invalidation:** Clears cached feedback list entries tagged for `bookId` and the cached AI rating summary for that book.
:::note
OpenAPI metadata declares `404 Not Found` as `application/problem+json`, whereas runtime responses return `application/json` with `{ "detail": "The requested resource was not found." }`.
:::
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :-------------------------------------------------------------------------- | :------------------------------------------------------------------- |
| `400 Bad Request` | `id` path segment is not a valid UUID | Provide a valid feedback UUID in the path and retry |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID bearer token | Acquire a valid Entra ID access token and retry |
| `403 Forbidden` | Valid token missing the `admin` role or `rating_read`/`rating_write` scopes | Authenticate as a store administrator with the required scopes |
| `404 Not Found` | No feedback record exists with the specified `id` | Refresh the moderation list; do not retry unchanged |
| `409 Conflict` | Cosmos DB ETag concurrency conflict | Re-fetch the feedback state and retry if still present |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Unexpected Cosmos DB, Kafka, or server failure (`traceId` included) | Retry with exponential backoff; inspect service logs using `traceId` |
## Related Documentation
- [[service|rating-api]] — Service overview, Azure Cosmos DB storage, and authorization policies.
- [[entity|feedback]] — Feedback document model.
- [[command|CreateFeedback]] — Submit a new book feedback record.
- [[event|FeedbackDeletedIntegrationEvent]] — Kafka event published on deletion.
- [[query|ListFeedbacks]] — Retrieve feedback records to locate IDs.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "DeleteFeedbackRequest",
"description": "The feedback UUID is supplied as the id path parameter; the operation has no request body.",
"type": "object",
"additionalProperties": false
}
---
id: DeleteOrder
name: Delete order
version: 1.0.0
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
summary: Soft-deletes an Order by its identifier without changing its business status.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
operation:
method: DELETE
path: /api/v1/orders/{id}
statusCodes: ["204", "404"]
sidebar:
badge: "DELETE"
---
`DeleteOrder` soft-deletes an [[entity|order]] in [[service|order-api]] (`DELETE /ordering/api/v1/orders/{id}`) while leaving its business status unchanged. Access is restricted to callers holding the Microsoft Entra ID `admin` role.
## Overview
| Property | Value |
| :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Ordering |
| **Owner Service** | [[service\|order-api]] |
| **Protocol / Format** | HTTP `DELETE`, path parameter only, empty response (`204 No Content`) |
| **Gateway Endpoint** | `DELETE /ordering/api/v1/orders/{id}` (service path `/api/v1/orders/{id}`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `admin` policy (role `admin` plus scopes `ordering_read`, `ordering_write`) |
| **Idempotency / Concurrency** | Not idempotent across retries; repeat calls return `404 Not Found`; no `x-request-id` header is required |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` burst, `20` per `10s`, queue `5`) |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Path Parameters
Accepts no request body and requires no `x-request-id` header.
| Name | Type | Required | Constraints | Description |
| :--- | :---------------- | :------- | :------------------------- | :-------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | Path parameter; valid UUID | Unique identifier of the order to soft-delete |
### Success Response (`204 No Content`)
Empty response body confirms the order was soft-deleted.
## Behavior & Side Effects
- **Soft-delete without status transition:** Sets `isDeleted = true` without changing the order's `status` (`New`, `Completed`, or `Cancelled`).
- **Global query filter:** Soft-deleted orders are hidden from standard read queries and subsequent `DELETE` calls (`404 Not Found`).
- **No events emitted:** Raises no domain events and publishes no Kafka integration events. To cancel an active order and notify downstream workflows, use [[command|CancelOrder]].
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :----------------------------------------------------------------------- | :---------------------------------------------------------------------------------- |
| `400 Bad Request` | Path parameter `{id}` is not a valid UUID | Supply a valid UUID; do not retry unchanged |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID bearer token | Acquire a fresh Entra ID access token and retry |
| `403 Forbidden` | Caller lacks the `admin` role or `ordering_read`/`ordering_write` scopes | Authenticate with an `admin` token that includes the required scopes |
| `404 Not Found` | Order does not exist or was already soft-deleted | Verify the order identifier; treat as already soft-deleted if retrying a prior call |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Unhandled database failure | Retry with backoff and inspect service logs |
## Related Documentation
- [[service|order-api]] — Service architecture, persistence, and endpoints.
- [[entity|order]] — Order aggregate schema and soft-delete behavior.
- [[command|CancelOrder]] — Transition a `New` order to `Cancelled` and notify downstream workflows.
- [[command|DeleteBasketFailedCommand]] — Automated compensation command that also soft-deletes an order.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "DeleteOrderRequest",
"description": "Path identifier for the Order to soft-delete. The operation has no request body.",
"type": "string"
}
---
id: DeletePublisher
name: Delete publisher
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Deletes an existing publisher from the Catalog.
owners:
- catalog-experience-team
schemaPath: schema.json
operation:
method: DELETE
path: /api/v1/publishers/{id}
statusCodes: ["204", "404"]
sidebar:
badge: "DELETE"
---
`DeletePublisher` permanently deletes a publisher record from [[service|catalog-api]] (`DELETE /catalog/api/v1/publishers/{id}`) and returns `204 No Content`. Deletion is rejected with `400 Bad Request` when any active book references the publisher.
## Overview
| Property | Value |
| :--------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------ |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | HTTP `DELETE`, path parameter only, empty response (`204 No Content`) |
| **Gateway Endpoint** | `DELETE /catalog/api/v1/publishers/{id}` (service path `/api/v1/publishers/{id}`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `business_user` policy (role `business_user` or `admin` and scopes `catalog_read`, `catalog_write`) |
| **Idempotency / Concurrency** | Not idempotent across retries; repeating a completed delete returns `404 Not Found`; no `x-request-id` header is enforced |
| **Rate Limit / Caching** | Global concurrency (`100`) and fixed-window (`30 req/min`) limiters plus per-user token bucket; invalidates publisher and book caches |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Path Parameters
| Name | Type | Required | Constraints | Description |
| :--- | :---------------- | :------- | :---------------------------------------------------- | :------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | Valid UUID; must not be referenced by any active book | Unique identifier of the publisher to delete |
## Behavior & Side Effects
- **Referential integrity guard:** Rejects deletion with `400 Bad Request` (`"Publisher has books and cannot be deleted"`) if any active (non-soft-deleted) book references the publisher.
- **Hard delete:** Permanently removes the [[entity|publisher]] record (no soft delete); soft-deleted books referencing the publisher have their publisher reference set to `NULL`.
- **Cache invalidation:** Clears `catalog:publishers:v1` and invalidates `book` and `books:list` cache tags.
- **Vector index queueing:** Database triggers enqueue any linked book IDs for asynchronous vector reconciliation by [[service|catalog-ingestion]].
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :---------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------- |
| `400 Bad Request` | Publisher is still linked to one or more active books, or `{id}` is not a valid UUID | Reassign or delete linked books first, or fix the UUID; do not retry unchanged |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID JWT | Acquire a valid Entra ID access token and retry |
| `403 Forbidden` | Token lacks role `business_user` or `admin`, or lacks scopes `catalog_read` and `catalog_write` | Request the required Entra ID app role and scopes |
| `404 Not Found` | No publisher exists with the supplied `{id}` | Verify the UUID; treat as already absent only if your workflow allows it |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Unhandled server or database failure (`traceId` included) | Inspect service logs using `traceId` |
## Related Documentation
- [[service|catalog-api]] — Service overview, routing, and authorization policies.
- [[entity|publisher]] — Publisher entity model.
- [[command|CreatePublisher]] — Create a new publisher record.
- [[command|UpdatePublisher]] — Rename an existing publisher.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "DeletePublisher",
"description": "Path identifier for the publisher to delete.",
"type": "string",
"format": "uuid"
}
---
id: PlaceOrderCommand
name: Place order
version: 1.0.0
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
summary: |
Shared Finance order-placement command consumed by Notification to render
and submit a new-order email.
schemaPath: schema.json
owners:
- platform-engineering-team
---
`PlaceOrderCommand` is an asynchronous Kafka integration command published by [[service|order-orchestration]] after checkout and consumed independently by [[service|basket-api]] (to delete the customer's Redis basket) and [[service|notification-api]] (to send a new-order confirmation email). Neither consumer creates or modifies orders in [[service|order-api]].
## Overview
| Property | Value |
| :----------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Platform / Notifications & Shopping |
| **Producer** | [[service\|order-orchestration]] |
| **Consumer(s)** | [[service\|basket-api]], [[service\|notification-api]] |
| **Protocol / Format** | Kafka + CloudEvents JSON (camelCase payload) |
| **Channel / Topic** | [[channel\|bookworm.{env}.finance.place-order]] |
| **Dead-Letter Channel** | [[channel\|bookworm.{env}.basket.dead-letter-queue]], [[channel\|bookworm.{env}.notification.dead-letter-queue]] |
| **Partition Key** | `OrderId` |
| **Delivery / Idempotency Guarantee** | At-least-once delivery; [[service\|basket-api]] deduplicates by `OrderId` (24h TTL) and [[service\|notification-api]] deduplicates by `id` (24h TTL) |
:::note
`PlaceOrderCommand` initiates post-checkout basket cleanup and confirmation email delivery only. To submit a new order over HTTP, see [[command|CreateOrder]].
:::
## Payload Fields & Envelope
### Command Payload
| Name | Type | Required | Constraints | Description |
| :------------- | :--------------------- | :------- | :-------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | UUIDv7 | Unique message identifier used for 24-hour Redis deduplication in [[service\|notification-api]] |
| `creationDate` | `string` (`date-time`) | Yes | ISO 8601 UTC timestamp | UTC timestamp when the command was created |
| `basketId` | `string` (`uuid`) | Yes | Valid UUID | Buyer/basket identifier deleted from Redis by [[service\|basket-api]] (ignored by [[service\|notification-api]]) |
| `orderId` | `string` (`uuid`) | Yes | Valid UUID; Kafka partition key | Identifier of the placed order; used as the 24-hour deduplication key by [[service\|basket-api]] |
| `fullName` | `string \| null` | No | Nullable (defaults to `"Customer"` in Notification) | Customer display name (ignored by [[service\|basket-api]]) |
| `email` | `string \| null` | No | Nullable | Recipient email address; forwarded by [[service\|basket-api]] on deletion failure and used by [[service\|notification-api]] (blank/null skips email) |
| `totalMoney` | `number` | Yes | Non-negative monetary amount | Order total displayed in the new-order email and echoed in basket cleanup events |
## Delivery Guarantees & Error Handling
| Condition | System Behavior | Recovery / Compensation |
| :--------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------- |
| Basket deletion returns `false` in [[service\|basket-api]] | Publishes [[event\|BasketDeletedFailedIntegrationEvent]] | [[service\|order-orchestration]] instructs [[service\|order-api]] to compensate via [[command\|DeleteBasketFailedCommand]] |
| Transient Redis failure in [[service\|basket-api]] | Releases the `OrderId` idempotency lock and retries (`50ms`, `250ms`, `1s` with jitter) | Exhausted retries route to [[channel\|bookworm.{env}.basket.dead-letter-queue]] |
| Transient SMTP failure in [[service\|notification-api]] | Retried by the notification resilience pipeline (circuit breaker, exponential backoff with jitter, `30s` timeout) | Exhausted retries route to [[channel\|bookworm.{env}.notification.dead-letter-queue]] |
| Blank or `null` `email` in [[service\|notification-api]] | Consumer returns without error and skips template rendering and SMTP submission | No action required |
## Related Documentation
- [[service|notification-api]] — Stateless email worker architecture and SMTP configuration.
- [[service|basket-api]] — Redis basket storage and checkout cleanup behavior.
- [[service|order-orchestration]] — Producing orchestration service.
- [[channel|bookworm.{env}.finance.place-order]] — Kafka channel specification.
- [[command|CreateOrder]] — Ordering API HTTP command that creates the order.
- [[event|UserCheckedOutIntegrationEvent]] — Upstream Ordering event that starts checkout orchestration.
- [[event|BasketDeletedCompleteIntegrationEvent]] — Success event published by [[service|basket-api]].
- [[event|BasketDeletedFailedIntegrationEvent]] — Failure event published by [[service|basket-api]].
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "PlaceOrderCommand",
"type": "object",
"additionalProperties": false,
"required": ["id", "creationDate", "basketId", "orderId", "totalMoney"],
"properties": {
"id": { "type": "string", "format": "uuid" },
"creationDate": { "type": "string", "format": "date-time" },
"basketId": { "type": "string", "format": "uuid" },
"orderId": { "type": "string", "format": "uuid" },
"fullName": { "type": ["string", "null"] },
"email": { "type": ["string", "null"] },
"totalMoney": { "type": "number" }
}
}
---
id: UpdateAddress
name: Update buyer address
version: 1.0.0
badges:
- content: Customer Management
backgroundColor: orange
textColor: orange
summary: Updates the authenticated Buyer's address using the supplied street, city, and province.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
operation:
method: PATCH
path: /api/v1/buyers/address
statusCodes: ["200", "400", "404"]
sidebar:
badge: "PATCH"
---
`UpdateAddress` replaces the shipping address on the authenticated customer's [[entity|buyer]] profile in [[service|order-api]] (`PATCH /ordering/api/v1/buyers/address`) and returns the updated buyer profile. Access is restricted strictly to the Microsoft Entra ID `customer` role (administrators cannot invoke this endpoint on another user's behalf).
## Overview
| Property | Value |
| :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Ordering |
| **Owner Service** | [[service\|order-api]] |
| **Protocol / Format** | HTTP `PATCH`, `application/json` request and response |
| **Gateway Endpoint** | `PATCH /ordering/api/v1/buyers/address` (service path `/api/v1/buyers/address`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `customer` policy only (role `customer` plus scopes `ordering_read`, `ordering_write`) |
| **Idempotency / Concurrency** | Naturally idempotent full address replacement; no `x-request-id` header is required |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` burst, `20` per `10s`, queue `5`) |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Request Body (`application/json`)
All three address fields are required together to replace the address value object.
| Name | Type | Required | Constraints | Description |
| :--------- | :------- | :------- | :--------------------------------------------------- | :------------------------ |
| `street` | `string` | Yes | Non-empty, max `50` characters; PII-redacted in logs | Updated street address |
| `city` | `string` | Yes | Non-empty, max `50` characters; PII-redacted in logs | Updated city or district |
| `province` | `string` | Yes | Non-empty, max `50` characters; PII-redacted in logs | Updated province or state |
### Success Response (`200 OK`)
| Name | Type | Required | Constraints | Description |
| :-------- | :---------------- | :------- | :------------------------------------------------------------------ | :--------------------------------------- |
| `id` | `string` (`uuid`) | Yes | Valid UUID | Identifier of the authenticated buyer |
| `name` | `string \| null` | No | PII-redacted in logs | Buyer display name stored on the profile |
| `address` | `string \| null` | No | Formatted as `"{Street}, {City}, {Province}"`; PII-redacted in logs | Formatted full address |
## Behavior & Side Effects
- **Session-bound lookup:** Derives the buyer ID from the authenticated user's `NameIdentifier` claim (no buyer ID is accepted in the route or body). Returns `404 Not Found` if no profile exists yet; callers must first create a profile via [[command|CreateBuyer]].
- **Atomic address replacement:** Replaces the address value object inside a database transaction; emits no domain or integration events.
- **PII redaction:** Request address fields and response `name`/`address` fields are automatically redacted in structured logs.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :---------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------- |
| `400 Bad Request` | Empty/whitespace address field, field exceeding `50` characters, or non-UUID `NameIdentifier` claim | Fix the request body or token claims; do not retry unchanged |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID bearer token | Acquire a fresh Entra ID access token and retry |
| `403 Forbidden` | Caller lacks the `customer` role (including `admin`-only tokens) or lacks `ordering_read`/`ordering_write` scopes | Authenticate as a `customer` with the required scopes |
| `404 Not Found` | Authenticated caller does not have an existing buyer profile | Create the profile first using [[command\|CreateBuyer]] |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Unhandled database or server failure | Retry with backoff and inspect service logs |
## Related Documentation
- [[service|order-api]] — Service architecture, persistence, and endpoints.
- [[entity|buyer]] — Buyer aggregate schema and address value object.
- [[command|CreateBuyer]] — Create a buyer profile before updating its address.
- [[command|DeleteBuyer]] — Administrative permanent removal of a buyer profile.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "UpdateAddressCommand",
"description": "Address fields required to update the authenticated Buyer's address.",
"type": "object",
"required": ["street", "city", "province"],
"properties": {
"street": {
"type": "string"
},
"city": {
"type": "string"
},
"province": {
"type": "string"
}
}
}
---
id: UpdateAuthor
name: Update author
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Updates an existing author in the Catalog.
owners:
- catalog-experience-team
schemaPath: schema.json
operation:
method: PUT
path: /api/v1/authors
statusCodes: ["204", "400", "404"]
sidebar:
badge: "PUT"
---
`UpdateAuthor` updates the display name of an existing author in [[service|catalog-api]] (`PUT /catalog/api/v1/authors`) and returns `204 No Content`. Callers pass both `id` and `name` in the JSON request body rather than as a path parameter.
## Overview
| Property | Value |
| :--------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | HTTP `PUT`, `application/json` request and empty response (`204 No Content`) |
| **Gateway Endpoint** | `PUT /catalog/api/v1/authors` (service path `/api/v1/authors`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `business_user` policy (role `business_user` or `admin` and scopes `catalog_read`, `catalog_write`) |
| **Idempotency / Concurrency** | Naturally idempotent for repeated requests with the same `id` and `name`; no `x-request-id` header is enforced |
| **Rate Limit / Caching** | Global concurrency (`100`) and fixed-window (`30 req/min`) limiters plus per-user token bucket; invalidates author and book caches |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Request Body (`application/json`)
Leading and trailing whitespace is trimmed from string properties during deserialization.
| Name | Type | Required | Constraints | Description |
| :----- | :---------------- | :------- | :------------------------------ | :-------------------------------------- |
| `id` | `string` (`uuid`) | Yes | Non-empty UUID | Identifier of the author to update |
| `name` | `string` | Yes | Non-empty, max `100` characters | Replacement display name for the author |
## Behavior & Side Effects
- **Persistence:** Updates the [[entity|author]] display name; author names have no unique constraint.
- **Cache invalidation:** Clears `catalog:authors:v1` and invalidates `book` and `books:list` cache tags so cached book details reflect the renamed author.
- **Vector index queueing:** Database triggers enqueue all linked book IDs for asynchronous vector embedding refresh by [[service|catalog-ingestion]].
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------- |
| `400 Bad Request` | `id` is empty or invalid UUID, or `name` is missing, empty, whitespace-only, or exceeds `100` characters | Fix the request body; do not retry unchanged input |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID JWT | Acquire a valid Entra ID access token and retry |
| `403 Forbidden` | Token lacks role `business_user` or `admin`, or lacks scopes `catalog_read` and `catalog_write` | Request the required Entra ID app role and scopes |
| `404 Not Found` | No author exists with the supplied `id` | Verify the UUID; do not treat `404` as a completed update |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Unhandled server or database failure (`traceId` included) | Inspect service logs using `traceId` |
## Related Documentation
- [[service|catalog-api]] — Service overview, routing, and authorization policies.
- [[entity|author]] — Author entity model.
- [[command|CreateAuthor]] — Create a new author record.
- [[command|DeleteAuthor]] — Permanently delete an author with no linked books.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "UpdateAuthor",
"description": "Payload for updating a author.",
"type": "object",
"additionalProperties": false,
"required": ["id", "name"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "Identifier of the author to update."
},
"name": {
"type": "string",
"minLength": 1,
"description": "New display name for the author."
}
}
}
---
id: UpdateBasket
name: Update basket
version: 1.0.0
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
summary: Replaces a basket's item collection with the supplied items.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
operation:
method: PUT
path: /api/v1/baskets
statusCodes: ["204", "400", "404"]
sidebar:
badge: "PUT"
---
`UpdateBasket` replaces the entire item collection of the authenticated customer's existing [[entity|basket]] in [[service|basket-api]] (`PUT /basket/api/v1/baskets`) and returns `204 No Content`. It requires an active basket to exist and rejects requests targeting a missing basket with `404 Not Found`.
## Overview
| Property | Value |
| :--------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Shopping |
| **Owner Service** | [[service\|basket-api]] |
| **Protocol / Format** | HTTP `PUT`, `application/json` request, empty response (`204 No Content`) |
| **Gateway Endpoint** | `PUT /basket/api/v1/baskets` (service path `/api/v1/baskets`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `customer` role plus scopes `basket_read`, `basket_write` |
| **Idempotency / Concurrency** | Naturally idempotent full-list replacement (last write wins) |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` tokens, `+20` per `10s`, queue `5`); stored in Redis with no TTL |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Request Body (`application/json`)
| Name | Type | Required | Constraints | Description |
| :----------------- | :--------- | :------- | :--------------- | :----------------------------------------------------------- |
| `items` | `object[]` | Yes | Non-empty array | Complete replacement list of items for the customer's basket |
| `items[].id` | `string` | Yes | Non-empty string | Identifier of the Catalog book |
| `items[].quantity` | `integer` | Yes | `>= 1` | Updated unit quantity for the book |
### Success Response (`204 No Content`)
Empty response body confirms the basket items were replaced.
## Behavior & Side Effects
- **Full-list replacement:** Replaces all existing items in Redis (`basket:{userId}`) with the submitted items (last write wins, no TTL).
- **No implicit creation:** Returns `404 Not Found` if no active basket exists; call [[command|CreateBasket]] first or [[command|DeleteBasket]] to remove all items.
- **Deferred catalog enrichment:** Stores only book IDs and quantities; titles and prices are resolved on read via [[query|GetBasket]].
- **No integration events:** HTTP basket updates do not publish any Kafka integration events.
:::note
OpenAPI metadata declares `404 Not Found` as `application/problem+json`, whereas runtime responses return `application/json` with `{ "detail": "The requested resource was not found." }`.
:::
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :--------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------- |
| `400 Bad Request` | Missing `items`, empty `items` array, empty `items[].id`, `items[].quantity <= 0`, or malformed JSON | Fix the failing fields and resubmit |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID bearer token | Acquire a valid Entra ID access token and retry |
| `403 Forbidden` | Valid token missing the `customer` role or `basket_read`/`basket_write` scopes | Request a token with the required role and scopes |
| `404 Not Found` | No active basket exists in Redis for the authenticated customer | Create a basket via [[command\|CreateBasket]] before updating |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Unexpected Redis or server failure (`traceId` included) | Retry with exponential backoff; inspect service logs using `traceId` |
## Related Documentation
- [[service|basket-api]] — Service overview, Redis storage, and authorization policy.
- [[entity|basket]] — Basket entity model.
- [[command|CreateBasket]] — Initialize a new basket.
- [[command|DeleteBasket]] — Delete an active basket.
- [[query|GetBasket]] — Retrieve the current basket enriched with Catalog data.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "UpdateBasketCommand",
"type": "object",
"required": ["items"],
"properties": {
"items": {
"type": "array",
"items": {
"type": "object",
"required": ["id", "quantity"],
"properties": {
"id": {
"type": "string"
},
"quantity": {
"type": ["integer", "string"],
"format": "int32",
"pattern": "^-?(?:0|[1-9]\\d*)$"
}
}
}
}
}
}
---
id: UpdateBook
name: Update book
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Updates an existing book listing, including optional image and catalog relationships.
owners:
- catalog-experience-team
schemaPath: schema.json
operation:
method: PUT
path: /api/v1/books
statusCodes: ["204", "400", "404"]
sidebar:
badge: "PUT"
---
`UpdateBook` replaces the full metadata, pricing, relationships, and optional cover image of an existing book in [[service|catalog-api]] (`PUT /catalog/api/v1/books`) from a `multipart/form-data` payload and returns `204 No Content`. Callers can supply an `If-Match` header with the book's `ETag` to enforce optimistic concurrency control.
## Overview
| Property | Value |
| :--------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | HTTP `PUT`, `multipart/form-data` request, empty response (`204 No Content`) |
| **Gateway Endpoint** | `PUT /catalog/api/v1/books` (service path `/api/v1/books`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `business_user` policy (role `business_user` or `admin` and scopes `catalog_read`, `catalog_write`) |
| **Idempotency / Concurrency** | Optional `If-Match` ETag header for optimistic concurrency (`412 Precondition Failed` on mismatch); idempotent when resubmitting identical fields without a new `image` upload |
| **Rate Limit / Caching** | Global concurrency (`100`) and fixed-window (`30 req/min`) limiters plus per-user token bucket; invalidates book, summary, list, and search caches |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
:::note
`PUT /catalog/api/v1/books` is a **full replacement**, not a partial patch. Every request requires `id`, `name`, `price`, `categoryId`, `publisherId`, and `authorIds`; omitting optional fields (`description`, `priceSale`) overwrites them with their defaults (`""` and `null`).
:::
## Request & Response Contract
### Request Headers
| Name | Type | Required | Constraints | Description |
| :-------------- | :------- | :------- | :----------------------------------------------------------------------------------------------------- | :------------------------------------------------------ |
| `Authorization` | `string` | Yes | `Bearer ` | Entra ID JWT satisfying the `business_user` policy |
| `If-Match` | `string` | No | Strong (`""`) or weak (`W/""`) unsigned integer ETag from [[query\|GetBook]] | Expected row version for optimistic concurrency control |
### Request Form Fields (`multipart/form-data`)
| Name | Type | Required | Constraints | Description |
| :-------------- | :-------------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | Non-empty UUID | Identifier of the book to replace |
| `name` | `string` | Yes | Non-empty, max `50` characters | Book title |
| `description` | `string` | No | Default `""`, max `500` characters | Book summary text; omitting clears the stored description |
| `price` | `number` | Yes | Strictly `> 0` (`numeric(18,2)`) | Regular catalog price |
| `priceSale` | `number \| null` | No | When provided: strictly `> 0` and `<= price` | Optional promotional sale price; omitting clears any existing sale price |
| `categoryId` | `string` (`uuid`) | Yes | Non-empty UUID; must reference an existing category | Category identifier |
| `publisherId` | `string` (`uuid`) | Yes | Non-empty UUID; must reference an existing publisher | Publisher identifier |
| `authorIds` | `string[]` (`uuid[]`) | Yes | Non-empty array (`>= 1` UUID); repeat `authorIds` form fields for multiple authors | Complete replacement list of author identifiers |
| `image` | `string` (`binary`) | No | Max `1,048,576` bytes (1 MB); `image/jpeg` (`.jpg`, `.jpeg`), `image/png` (`.png`), or `image/webp` (`.webp`); extension must match content type | Optional cover image upload replacing the stored cover URN |
| `isRemoveImage` | `boolean` | No | Default `false` | When `true`, clears the stored cover image reference (takes precedence over `image`) |
## Behavior & Side Effects
- **Optimistic concurrency:** When `If-Match` contains a valid integer ETag, it is checked against the book's current row version; mismatches return `412 Precondition Failed`.
- **Transactional persistence:** Atomically replaces book fields and author associations within a database transaction.
- **Cover image handling:** Uploading `image` stores a new blob in `catalog-blob` and updates the book's image URN; omitting both `image` and `isRemoveImage=true` preserves the existing cover; setting `isRemoveImage=true` clears the stored image reference in PostgreSQL without deleting previously stored blobs.
- **Cache invalidation:** Clears cached book details (`book:{id}`), book summary (`book:summary:{id}`), and invalidates `books:list` and `books:search` cache tags.
- **Vector index queueing:** Database triggers enqueue the book ID for asynchronous Qdrant embedding refresh by [[service|catalog-ingestion]].
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------- |
| `400 Bad Request` | Validation failure (missing required fields, `price <= 0`, `priceSale <= 0` or `> price`, length exceeded, invalid image size/type/extension) or malformed multipart payload | Fix invalid form fields or file upload; do not retry unchanged input |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID JWT | Acquire a valid Entra ID access token and retry |
| `403 Forbidden` | Token lacks role `business_user` or `admin`, or lacks scopes `catalog_read` and `catalog_write` | Request the required Entra ID app role and scopes |
| `404 Not Found` | No active book exists with the supplied `id` | Verify the book UUID; do not treat `404` as a completed update |
| `412 Precondition Failed` | `If-Match` version does not match the book's current row version | Fetch the latest book and `ETag` via [[query\|GetBook]], merge changes, and retry |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Foreign-key violation, blob storage failure, or unhandled server error (`traceId` included) | Verify referenced IDs exist and inspect service logs using `traceId` |
## Related Documentation
- [[service|catalog-api]] — Service overview, routing, and authorization policies.
- [[entity|book]] — Book entity model.
- [[command|CreateBook]] — Create a new book listing with multipart upload.
- [[command|DeleteBook]] — Soft-delete an existing book listing.
- [[query|GetBook]] — Retrieve current book details and `ETag`.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "UpdateBook",
"description": "Multipart payload for updating a book listing.",
"type": "object",
"additionalProperties": false,
"required": ["id", "name", "price", "categoryId", "publisherId", "authorIds"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "Book UUID to update."
},
"name": {
"type": "string",
"minLength": 1
},
"description": {
"type": "string"
},
"image": {
"type": ["string", "null"],
"contentEncoding": "base64"
},
"price": {
"type": "number",
"minimum": 0
},
"priceSale": {
"type": ["number", "null"],
"minimum": 0
},
"categoryId": {
"type": "string",
"format": "uuid",
"description": "A UUID identifying the resource."
},
"publisherId": {
"type": "string",
"format": "uuid",
"description": "A UUID identifying the resource."
},
"authorIds": {
"type": "array",
"items": {
"type": "string",
"format": "uuid",
"description": "A UUID identifying the resource."
}
},
"isRemoveImage": {
"type": "boolean",
"description": "Remove the existing cover when true."
}
}
}
---
id: UpdateCategory
name: Update category
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Updates an existing category in the Catalog.
owners:
- catalog-experience-team
schemaPath: schema.json
operation:
method: PUT
path: /api/v1/categories
statusCodes: ["204", "400", "404"]
sidebar:
badge: "PUT"
---
`UpdateCategory` updates the display name of an existing category in [[service|catalog-api]] (`PUT /catalog/api/v1/categories`) and returns `204 No Content`. Callers pass both `id` and `name` in the JSON request body rather than as a path parameter.
## Overview
| Property | Value |
| :--------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | HTTP `PUT`, `application/json` request and empty response (`204 No Content`) |
| **Gateway Endpoint** | `PUT /catalog/api/v1/categories` (service path `/api/v1/categories`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `business_user` policy (role `business_user` or `admin` and scopes `catalog_read`, `catalog_write`) |
| **Idempotency / Concurrency** | Naturally idempotent for repeated requests with the same `id` and `name`; no `x-request-id` header is enforced |
| **Rate Limit / Caching** | Global concurrency (`100`) and fixed-window (`30 req/min`) limiters plus per-user token bucket; invalidates category and book caches |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Request Body (`application/json`)
Leading and trailing whitespace is trimmed from string properties during deserialization.
| Name | Type | Required | Constraints | Description |
| :----- | :---------------- | :------- | :------------------------------------- | :---------------------------------------- |
| `id` | `string` (`uuid`) | Yes | Non-empty UUID | Identifier of the category to update |
| `name` | `string` | Yes | Non-empty, max `50` characters, unique | Replacement display name for the category |
## Behavior & Side Effects
- **Persistence & uniqueness:** Updates the [[entity|category]] display name; category names are unique-indexed, so renaming to an existing category's name fails with `500 Internal Server Error`.
- **Cache invalidation:** Clears `catalog:categories:v1` and invalidates `book` and `books:list` cache tags.
- **Vector index queueing:** Database triggers enqueue all linked book IDs for asynchronous vector embedding refresh by [[service|catalog-ingestion]].
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------- |
| `400 Bad Request` | `id` is empty or invalid UUID, or `name` is missing, empty, whitespace-only, or exceeds `50` characters | Fix the request body; do not retry unchanged input |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID JWT | Acquire a valid Entra ID access token and retry |
| `403 Forbidden` | Token lacks role `business_user` or `admin`, or lacks scopes `catalog_read` and `catalog_write` | Request the required Entra ID app role and scopes |
| `404 Not Found` | No category exists with the supplied `id` | Verify the UUID; do not treat `404` as a completed update |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Duplicate `name` violating the unique constraint or unhandled server error (`traceId` included) | Check for a conflicting category name and inspect logs using `traceId` |
## Related Documentation
- [[service|catalog-api]] — Service overview, routing, and authorization policies.
- [[entity|category]] — Category entity model.
- [[command|CreateCategory]] — Create a new category record.
- [[command|DeleteCategory]] — Permanently delete a category with no active books.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "UpdateCategory",
"description": "Payload for updating a category.",
"type": "object",
"additionalProperties": false,
"required": ["id", "name"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "Identifier of the category to update."
},
"name": {
"type": "string",
"minLength": 1,
"description": "New display name for the category."
}
}
}
---
id: UpdatePublisher
name: Update publisher
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Updates an existing publisher in the Catalog.
owners:
- catalog-experience-team
schemaPath: schema.json
operation:
method: PUT
path: /api/v1/publishers
statusCodes: ["204", "400", "404"]
sidebar:
badge: "PUT"
---
`UpdatePublisher` updates the display name of an existing publisher in [[service|catalog-api]] (`PUT /catalog/api/v1/publishers`) and returns `204 No Content`. Callers pass both `id` and `name` in the JSON request body rather than as a path parameter.
## Overview
| Property | Value |
| :--------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------ |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | HTTP `PUT`, `application/json` request and empty response (`204 No Content`) |
| **Gateway Endpoint** | `PUT /catalog/api/v1/publishers` (service path `/api/v1/publishers`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `business_user` policy (role `business_user` or `admin` and scopes `catalog_read`, `catalog_write`) |
| **Idempotency / Concurrency** | Naturally idempotent for repeated requests with the same `id` and `name`; no `x-request-id` header is enforced |
| **Rate Limit / Caching** | Global concurrency (`100`) and fixed-window (`30 req/min`) limiters plus per-user token bucket; invalidates publisher and book caches |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Request Body (`application/json`)
Leading and trailing whitespace is trimmed from string properties during deserialization.
| Name | Type | Required | Constraints | Description |
| :----- | :---------------- | :------- | :------------------------------------- | :----------------------------------------- |
| `id` | `string` (`uuid`) | Yes | Non-empty UUID | Identifier of the publisher to update |
| `name` | `string` | Yes | Non-empty, max `50` characters, unique | Replacement display name for the publisher |
:::note
`UpdatePublisher` enforces a `50`-character maximum, which is narrower than the `100`-character limit allowed by [[command|CreatePublisher]]. Updating a publisher to a name between 51 and 100 characters returns `400 Bad Request`.
:::
## Behavior & Side Effects
- **Persistence & uniqueness:** Updates the [[entity|publisher]] display name; publisher names are unique-indexed, so renaming to an existing publisher's name fails with `500 Internal Server Error`.
- **Cache invalidation:** Clears `catalog:publishers:v1` and invalidates `book` and `books:list` cache tags.
- **Vector index queueing:** Database triggers enqueue all linked book IDs for asynchronous vector embedding refresh by [[service|catalog-ingestion]].
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :------------------------------------------------------------------------------------------------------ | :---------------------------------------------------------------------- |
| `400 Bad Request` | `id` is empty or invalid UUID, or `name` is missing, empty, whitespace-only, or exceeds `50` characters | Fix the request body; do not retry unchanged input |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID JWT | Acquire a valid Entra ID access token and retry |
| `403 Forbidden` | Token lacks role `business_user` or `admin`, or lacks scopes `catalog_read` and `catalog_write` | Request the required Entra ID app role and scopes |
| `404 Not Found` | No publisher exists with the supplied `id` | Verify the UUID; do not treat `404` as a completed update |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` interval before retrying |
| `500 Internal Server Error` | Duplicate `name` violating the unique constraint or unhandled server error (`traceId` included) | Check for a conflicting publisher name and inspect logs using `traceId` |
## Related Documentation
- [[service|catalog-api]] — Service overview, routing, and authorization policies.
- [[entity|publisher]] — Publisher entity model.
- [[command|CreatePublisher]] — Create a new publisher record.
- [[command|DeletePublisher]] — Permanently delete a publisher with no active books.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "UpdatePublisher",
"description": "Payload for updating a publisher.",
"type": "object",
"additionalProperties": false,
"required": ["id", "name"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "Identifier of the publisher to update."
},
"name": {
"type": "string",
"minLength": 1,
"description": "New display name for the publisher."
}
}
}
---
id: GetAnonymizers
name: Get anonymizers
version: 1.0.0
badges:
- content: Privacy
backgroundColor: red
textColor: red
summary: Returns the names of the built-in anonymization operators supported by Presidio Anonymizer.
owners:
- platform-engineering-team
schemaPath: schema.json
operation:
method: GET
path: /anonymizers
statusCodes: ["200"]
sidebar:
badge: "GET"
---
`GetAnonymizers` queries the internal [[service|presidio-api]] Anonymizer sidecar (`GET /anonymizers`) to list its built-in anonymization operator names. This endpoint is an upstream capability discovery query; BookWorm's runtime PII middleware calls only `POST /anonymize` with the `replace` operator.
## Overview
| Property | Value |
| :--------------------------------- | :---------------------------------------------------------------- |
| **Bounded Context** | Data Privacy (External Integration) |
| **Owner Service** | [[service\|presidio-api]] (`presidio-anonymizer`) |
| **Protocol / Format** | HTTP `GET /anonymizers`, `application/json` response |
| **Gateway Endpoint** | Internal sidecar `GET /anonymizers` (not exposed via API Gateway) |
| **Authentication & Authorization** | None (internal service-to-service network boundary) |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | None (sidecar) |
| **Contract Version** | `1.0.0` |
:::note
**Capability discovery only:** BookWorm's runtime privacy middleware does not call `GET /anonymizers`; it uses the built-in `replace` operator (`""`) via [[command|AnonymizeText]].
:::
## Request & Response Contract
### Request Parameters
Accepts no path parameters, query parameters, or request body.
### Success Response (`200 OK`)
| Name | Type | Required | Constraints | Description |
| :--------- | :--------- | :------- | :---------------------------- | :----------------------------------------------------------------------------------------------- |
| Root value | `string[]` | Yes | Array of operator identifiers | Names of built-in anonymization operators (e.g., `hash`, `mask`, `redact`, `replace`, `encrypt`) |
## Behavior & Side Effects
- **Read-only discovery:** Returns supported operator names from the sidecar without mutating state.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :------------------------------------ | :------------------------------------------------------- |
| `500 Internal Server Error` | Sidecar unreachable or internal error | Verify the `presidio-anonymizer` sidecar health endpoint |
## Related Documentation
- [[service|presidio-api]] — Service overview and privacy middleware integration.
- [[command|AnonymizeText]] — Runtime `POST /anonymize` command used by [[service|chat-api]] and [[service|rating-api]].
- [[query|GetRecognizers]] — List available PII recognizers in Presidio Analyzer.
- [[query|GetSupportedEntities]] — List detectable PII entity types in Presidio Analyzer.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "GetAnonymizersResponse",
"description": "Built-in anonymization operator names supported by Presidio Anonymizer.",
"type": "array",
"items": { "type": "string" }
}
---
id: GetBasket
name: Get basket
version: 1.0.0
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
summary: Returns the current basket and its item details.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
operation:
method: GET
path: /api/v1/baskets
statusCodes: ["200", "404"]
sidebar:
badge: "GET"
---
`GetBasket` retrieves the authenticated customer's active basket from [[service|basket-api]] (`GET /basket/api/v1/baskets`) and enriches non-empty basket items with live titles and pricing from [[service|catalog-api]] over gRPC. The caller's customer identity is resolved from the Microsoft Entra ID access token; no basket identifier parameter is accepted.
## Overview
| Property | Value |
| :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Shopping |
| **Owner Service** | [[service\|basket-api]] |
| **Protocol / Format** | HTTP `GET`, `application/json` response |
| **Gateway Endpoint** | `GET /basket/api/v1/baskets` (service path `/api/v1/baskets`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `customer` role plus scopes `basket_read`, `basket_write` |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` limit, `20` per `10s`, queue `5`) |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Request Parameters
Accepts no path parameters, query parameters, or request body; resolves the customer ID from the authenticated token.
### Success Response (`200 OK`)
| Name | Type | Required | Constraints | Description |
| :------------------ | :------------------------- | :------- | :-------------------- | :------------------------------------------------------------------------------------------ |
| `id` | `string \| null` | Yes | — | Identifier of the customer's basket |
| `items` | `object[]` | Yes | Array (may be empty) | Line items currently stored in the basket |
| `items[].id` | `string \| null` | Yes | — | Catalog book identifier |
| `items[].quantity` | `integer \| string` | Yes | `int32` | Requested unit quantity |
| `items[].name` | `string \| null` | No | Nullable | Book title enriched from [[service\|catalog-api]] (`null` when unavailable) |
| `items[].price` | `number \| string` | No | `double`, default `0` | Regular unit price enriched from [[service\|catalog-api]] |
| `items[].priceSale` | `number \| string \| null` | No | `double` or `null` | Promotional sale price enriched from [[service\|catalog-api]] (`null` when no sale applies) |
## Behavior & Side Effects
- **Read-time catalog enrichment:** Reads basket state from Redis and, when `items` is non-empty, deduplicates book IDs and enriches items via [[query|GetBooksGrpc]].
- **No state mutation:** Pure read query with no database writes or integration events.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :---------------------- | :---------------------------------------------------------------------------------- | :-------------------------------------------------------------------- |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID bearer token | Re-authenticate the customer and retry |
| `403 Forbidden` | Principal lacks the `customer` role or required `basket_read`/`basket_write` scopes | Request a token with the required customer scopes |
| `404 Not Found` | No active basket exists in Redis for the authenticated customer | Treat as an empty/uninitialized basket until the customer creates one |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` duration before retrying |
## Related Documentation
- [[service|basket-api]] — Service overview, Redis persistence, and endpoints.
- [[entity|basket]] — Basket entity model.
- [[query|GetBasketGrpc]] — Internal gRPC contract used by [[service|order-api]] during checkout.
- [[query|GetBooksGrpc]] — Batch gRPC book lookup used to enrich basket items.
- [[command|CreateBasket]] — Create a new customer basket.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "CustomerBasketDto",
"type": "object",
"required": ["id", "items"],
"properties": {
"id": {
"type": ["string", "null"]
},
"items": {
"type": "array",
"items": {
"type": "object",
"required": ["id", "quantity"],
"properties": {
"id": {
"type": ["string", "null"]
},
"quantity": {
"type": ["integer", "string"],
"format": "int32",
"pattern": "^-?(?:0|[1-9]\\d*)$"
},
"name": {
"type": ["string", "null"]
},
"price": {
"type": ["number", "string"],
"format": "double",
"pattern": "^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?$",
"default": 0
},
"priceSale": {
"type": ["number", "string", "null"],
"format": "double",
"pattern": "^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?$"
}
}
}
}
}
}
---
id: GetBasketGrpc
name: Get basket over gRPC
version: 1.0.0
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
summary: Returns the current basket through the basket.v1 gRPC contract.
owners:
- commerce-fulfillment-team
schemaPath: schema.proto
sidebar:
badge: "gRPC"
---
`GetBasketGrpc` invokes the internal `basket.v1.BasketGrpcService/GetBasket` gRPC unary RPC on [[service|basket-api]] to retrieve the authenticated customer's basket items and quantities. [[service|order-api]] calls this RPC synchronously during order creation using an On-Behalf-Of (OBO) Microsoft Entra ID access token exchanged for Basket API.
## Overview
| Property | Value |
| :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Shopping |
| **Owner Service** | [[service\|basket-api]] |
| **Protocol / Format** | gRPC unary RPC (`basket.v1.BasketGrpcService/GetBasket`), Protobuf `edition = "2023"` |
| **Gateway Endpoint** | Internal gRPC RPC `basket.v1.BasketGrpcService/GetBasket` (not exposed via API Gateway) |
| **Authentication & Authorization** | Microsoft Entra ID JWT via `Authorization: Bearer ` metadata (customer OBO token with `basket_read`/`basket_write` scopes) |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | Per-user token bucket (`30` limit, `20` per `10s`, queue `5`); backed by Redis |
| **Contract Version** | `1.0.0` |
## Request & Response Contract
### Request Message (`google.protobuf.Empty`)
Empty `google.protobuf.Empty` message; customer identity is derived from the authenticated gRPC call context.
### Success Response (`GetBasketResponse`)
| Name | Type | Required | Constraints | Description |
| :----------------- | :------- | :------- | :--------------------------------------------------- | :----------------------------------- |
| `id` | `string` | Yes | Tag `1` (empty string if no basket exists) | Basket identifier |
| `items` | `Item[]` | Yes | Tag `2` (`repeated`; empty list if no basket exists) | Items currently stored in the basket |
| `items[].id` | `string` | Yes | Tag `1` | Catalog book identifier |
| `items[].quantity` | `int32` | Yes | Tag `2` | Quantity of the book in the basket |
:::note
When no basket exists in Redis for the authenticated customer, this RPC returns an empty `GetBasketResponse` (`id = ""`, `items = []`) rather than `NotFound` (`5`). Callers must check `items` length before proceeding.
:::
## Behavior & Side Effects
- **Redis lookup:** Reads `basket:{userId}` directly from Redis without Catalog enrichment.
- **No state mutation:** Pure read RPC with no database writes or integration events.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :------------------------ | :------------------------------------------------------------ | :-------------------------------------------------------------------- |
| `Unauthenticated` (`16`) | Missing/invalid Entra ID token or empty user identity | Exchange a valid customer OBO token for Basket API and retry |
| `PermissionDenied` (`7`) | Authenticated principal fails Basket API authorization policy | Verify customer role and `basket_read`/`basket_write` scopes |
| `ResourceExhausted` (`8`) | Caller exceeded per-user rate limit | Retry with exponential backoff |
| `Unavailable` (`14`) | Basket API or backing Redis instance is unreachable | Retry within budgeted resilience policy; fail checkout if unavailable |
## Related Documentation
- [[service|basket-api]] — Service overview, Redis persistence, and endpoints.
- [[entity|basket]] — Basket entity model.
- [[query|GetBasket]] — Public HTTP endpoint that enriches basket items with Catalog details.
- [[command|CreateOrder]] — Ordering API checkout flow that calls `GetBasket`.
## Raw Schema:schema.proto
edition = "2023";
import "google/protobuf/empty.proto";
option csharp_namespace = "BookWorm.Basket.Grpc.Services";
package basket.v1;
service BasketGrpcService {
rpc GetBasket (google.protobuf.Empty) returns (GetBasketResponse);
}
message GetBasketResponse {
string id = 1;
repeated Item items = 2;
}
message Item {
string id = 1;
int32 quantity = 2;
}
---
id: GetBook
name: Get book
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Returns one book and its catalog relationships by identifier.
owners:
- catalog-experience-team
schemaPath: schema.json
operation:
method: GET
path: /api/v1/books/{id}
statusCodes: ["200", "404"]
sidebar:
badge: "GET"
---
`GetBook` queries [[service|catalog-api]] (`GET /catalog/api/v1/books/{id}`) to retrieve a single book's full projection, including pricing, stock status, category, publisher, authors, and derived rating summary. The endpoint is publicly readable, supports HTTP `ETag` conditional requests, and caches book details.
## Overview
| Property | Value |
| :--------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | HTTP `GET`, `application/json` response |
| **Gateway Endpoint** | `GET /catalog/api/v1/books/{id}` (service path `/api/v1/books/{id}`) |
| **Authentication & Authorization** | None required (public read endpoint) |
| **Idempotency / Concurrency** | Read-only; supports conditional requests via `ETag` / `If-None-Match` (`304 Not Modified`) |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` limit, `20` per `10s`, queue `5`); cached in L1 + Redis L2 |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Path Parameters
| Name | Type | Required | Constraints | Description |
| :--- | :---------------- | :------- | :---------- | :---------------------------------------- |
| `id` | `string` (`uuid`) | Yes | Valid UUID | Unique identifier of the book to retrieve |
### Success Response (`200 OK`)
Returns a `BookDto` JSON object with an `ETag` response header.
| Name | Type | Required | Constraints | Description |
| :-------------- | :---------------- | :------- | :--------------------------------------------- | :------------------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | Valid UUID | Unique identifier of the book |
| `name` | `string \| null` | Yes | Nullable | Book title |
| `description` | `string \| null` | Yes | Nullable | Book description |
| `imageUrl` | `string \| null` | Yes | URI or `null` | Publicly accessible cover image URI |
| `price` | `number` | Yes | Decimal | Regular unit price |
| `priceSale` | `number \| null` | Yes | Decimal or `null` | Promotional sale price (`null` when no discount applies) |
| `status` | `string` | Yes | Enum: `InStock`, `OutOfStock` | Current stock availability status |
| `category` | `object \| null` | Yes | `{ id: uuid, name: string \| null }` or `null` | Assigned book category |
| `publisher` | `object \| null` | Yes | `{ id: uuid, name: string \| null }` or `null` | Assigned publisher |
| `authors` | `object[]` | Yes | Array of `{ id: uuid, name: string \| null }` | Authors associated with the book |
| `averageRating` | `number` | Yes | `>= 0` | Derived average customer rating projected from Reviews |
| `totalReviews` | `integer` | Yes | `>= 0` | Derived total feedback count projected from Reviews |
## Behavior & Side Effects
- **Read-through caching:** Serves cached book details from L1/Redis L2 and invalidates automatically on book, author, category, publisher, or rating updates.
- **ETag concurrency support:** Returns the book's row version as an `ETag` header for conditional reads (`If-None-Match`) and optimistic concurrency updates via [[command|UpdateBook]].
- **No state mutation:** Pure read query with no database writes or integration events.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :---------------------- | :-------------------------------------------------------- | :------------------------------------------------------- |
| `304 Not Modified` | Request included a matching `If-None-Match` ETag header | Reuse the client's cached book payload |
| `404 Not Found` | No active book exists for the supplied UUID | Render a not-found state; do not fabricate an empty book |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` duration before retrying |
## Related Documentation
- [[service|catalog-api]] — Service overview, persistence, and endpoints.
- [[entity|book]] — Book entity model.
- [[query|ListBooks]] — Search, filter, and paginate books.
- [[query|GetBookDetailsGrpc]] — Internal gRPC contract returning full book details.
- [[command|UpdateBook]] — Update book details using the `ETag` returned by this query.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "GetBookResponse",
"description": "Book representation returned by the Catalog API.",
"type": "object",
"allOf": [
{
"type": "object",
"additionalProperties": false,
"required": [
"id",
"name",
"description",
"imageUrl",
"price",
"priceSale",
"status",
"category",
"publisher",
"authors",
"averageRating",
"totalReviews"
],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "A UUID identifying the resource."
},
"name": {
"type": ["string", "null"]
},
"description": {
"type": ["string", "null"]
},
"imageUrl": {
"type": ["string", "null"],
"format": "uri"
},
"price": {
"type": "number"
},
"priceSale": {
"type": ["number", "null"]
},
"status": {
"type": "string",
"enum": ["InStock", "OutOfStock"]
},
"category": {
"type": ["object", "null"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "A UUID identifying the resource."
},
"name": {
"type": ["string", "null"]
}
},
"required": ["id", "name"]
},
"publisher": {
"type": ["object", "null"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "A UUID identifying the resource."
},
"name": {
"type": ["string", "null"]
}
},
"required": ["id", "name"]
},
"authors": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "A UUID identifying the resource."
},
"name": {
"type": ["string", "null"]
}
},
"required": ["id", "name"]
}
},
"averageRating": {
"type": "number",
"minimum": 0
},
"totalReviews": {
"type": "integer",
"minimum": 0
}
}
}
]
}
---
id: GetBookDetailsGrpc
name: Get book details over gRPC
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Returns full Catalog book details by identifier through the book.v1 gRPC contract.
owners:
- catalog-experience-team
schemaPath: schema.proto
sidebar:
badge: "gRPC"
---
`GetBookDetailsGrpc` invokes the internal `book.v1.BookGrpcService/GetBookDetails` gRPC unary RPC on [[service|catalog-api]] to retrieve a single book's complete projection, including description, cover image URI, pricing, stock status, category, publisher, authors, and derived rating summary. [[service|mcp-server]] calls this RPC to power its `get_book` tool.
## Overview
| Property | Value |
| :--------------------------------- | :--------------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | gRPC unary RPC (`book.v1.BookGrpcService/GetBookDetails`), Protobuf `edition = "2023"` |
| **Gateway Endpoint** | Internal gRPC RPC `book.v1.BookGrpcService/GetBookDetails` (not exposed via API Gateway) |
| **Authentication & Authorization** | Internal service-to-service anonymous read |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | Backed by PostgreSQL and cached in L1 + Redis L2 |
| **Contract Version** | `1.0.0` |
## Request & Response Contract
### Request Message (`GetBookDetailsRequest`)
| Name | Type | Required | Constraints | Description |
| :-------- | :---------------- | :------- | :------------------ | :---------------------------------------- |
| `book_id` | `string` (`uuid`) | Yes | Tag `1`; valid UUID | Unique identifier of the book to retrieve |
### Success Response (`GetBookDetailsResponse` / `book.*`)
`GetBookDetailsResponse` wraps a single `book` (`BookItem`) field (tag `1`).
| Name | Type | Required | Constraints | Description |
| :--------------- | :---------------- | :------- | :------------------------------------------------------------------- | :-------------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | Tag `1` | Book UUID |
| `name` | `string` | Yes | Tag `2` (empty string if null) | Book title |
| `description` | `string` | Yes | Tag `3` (empty string if null) | Book description |
| `image_url` | `string` | Yes | Tag `4` (empty string if null) | Cover image URI |
| `price` | `DecimalValue` | Yes | Tag `5` (`int64 units`, `sfixed32 nanos`) | Regular unit price |
| `price_sale` | `DecimalValue` | No | Tag `6` (omitted when no sale applies) | Promotional sale price |
| `status` | `BookStatus` | Yes | Tag `7` (`BOOK_STATUS_IN_STOCK = 1`, `BOOK_STATUS_OUT_OF_STOCK = 2`) | Current stock availability status |
| `category` | `CategoryItem` | No | Tag `8` (`id`, `name`) | Optional category |
| `publisher` | `PublisherItem` | No | Tag `9` (`id`, `name`) | Optional publisher |
| `authors` | `AuthorItem[]` | Yes | Tag `10` (`repeated`; `id`, `name`) | Authors associated with the book |
| `average_rating` | `double` | Yes | Tag `11`; `>= 0` | Derived average rating projected from Reviews |
| `total_reviews` | `int32` | Yes | Tag `12`; `>= 0` | Derived total feedback count projected from Reviews |
## Behavior & Side Effects
- **Read-through caching:** Delegates to the same cached projection used by [[query|GetBook]] (L1 + Redis L2).
- **No state mutation:** Pure read RPC with no database writes or integration events.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :---------------------- | :------------------------------------------------ | :------------------------------------------------------- |
| `InvalidArgument` (`3`) | `book_id` is not a valid UUID | Validate the UUID before calling; do not retry unchanged |
| `NotFound` (`5`) | No active book exists with the supplied `book_id` | Surface a not-found result to the caller |
| `Unavailable` (`14`) | Catalog API is unreachable | Retry within the budgeted resilience policy |
## Related Documentation
- [[service|catalog-api]] — Service overview, persistence, and gRPC services.
- [[service|mcp-server]] — Primary caller exposing the `get_book` MCP tool.
- [[entity|book]] — Book entity model.
- [[query|GetBook]] — Public HTTP endpoint returning full book details.
- [[query|GetBookGrpc]] — Compact single-book gRPC RPC without descriptions or relationships.
## Raw Schema:schema.proto
edition = "2023";
package book.v1;
service BookGrpcService {
rpc GetBookDetails (GetBookDetailsRequest) returns (GetBookDetailsResponse);
}
message GetBookDetailsRequest {
string book_id = 1;
}
message GetBookDetailsResponse {
BookItem book = 1;
}
message BookItem {
string id = 1;
string name = 2;
string description = 3;
string image_url = 4;
DecimalValue price = 5;
DecimalValue price_sale = 6;
BookStatus status = 7;
CategoryItem category = 8;
PublisherItem publisher = 9;
repeated AuthorItem authors = 10;
double average_rating = 11;
int32 total_reviews = 12;
}
enum BookStatus {
BOOK_STATUS_UNSPECIFIED = 0;
BOOK_STATUS_IN_STOCK = 1;
BOOK_STATUS_OUT_OF_STOCK = 2;
}
message DecimalValue {
int64 units = 1;
sfixed32 nanos = 2;
}
message CategoryItem {
string id = 1;
string name = 2;
}
message PublisherItem {
string id = 1;
string name = 2;
}
message AuthorItem {
string id = 1;
string name = 2;
}
---
id: GetBookGrpc
name: Get book over gRPC
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Returns one Catalog book by identifier through the book.v1 gRPC contract.
owners:
- catalog-experience-team
schemaPath: schema.proto
sidebar:
badge: "gRPC"
---
`GetBookGrpc` invokes the internal `book.v1.BookGrpcService/GetBook` gRPC unary RPC on [[service|catalog-api]] to retrieve a compact commercial summary (ID, name, regular price, sale price, and stock status) for a single book. While [[service|basket-api]] and [[service|order-api]] wire client methods for this RPC, active checkout and enrichment flows use the batch [[query|GetBooksGrpc]] RPC instead.
## Overview
| Property | Value |
| :--------------------------------- | :-------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | gRPC unary RPC (`book.v1.BookGrpcService/GetBook`), Protobuf `edition = "2023"` |
| **Gateway Endpoint** | Internal gRPC RPC `book.v1.BookGrpcService/GetBook` (not exposed via API Gateway) |
| **Authentication & Authorization** | Internal service-to-service anonymous read |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | Cached in L1 + Redis L2 keyed by book summary |
| **Contract Version** | `1.0.0` |
## Request & Response Contract
### Request Message (`GetBookRequest`)
| Name | Type | Required | Constraints | Description |
| :-------- | :---------------- | :------- | :------------------ | :---------------------------------------- |
| `book_id` | `string` (`uuid`) | Yes | Tag `1`; valid UUID | Unique identifier of the book to retrieve |
### Success Response (`GetBookResponse`)
| Name | Type | Required | Constraints | Description |
| :----------- | :---------------- | :------- | :------------------------------------------------------------------- | :-------------------------------- |
| `id` | `string` (`uuid`) | Yes | Tag `1` | Book UUID |
| `name` | `string` | Yes | Tag `2` | Book title |
| `price` | `DecimalValue` | Yes | Tag `3` (`int64 units`, `sfixed32 nanos`) | Regular unit price |
| `price_sale` | `DecimalValue` | No | Tag `4` (omitted when no sale applies) | Promotional sale price |
| `status` | `BookStatus` | Yes | Tag `5` (`BOOK_STATUS_IN_STOCK = 1`, `BOOK_STATUS_OUT_OF_STOCK = 2`) | Current stock availability status |
## Behavior & Side Effects
- **Read-through caching:** Resolves book summaries from L1/Redis L2 cache before querying PostgreSQL.
- **No state mutation:** Pure read RPC with no database writes or integration events.
:::note
Supplying a malformed `book_id` returns gRPC `Unknown` (`2`) rather than `InvalidArgument` (`3`); callers must validate UUID formatting before invoking this RPC.
:::
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :------------------- | :------------------------------------------------ | :---------------------------------------------------- |
| `NotFound` (`5`) | No active book exists with the supplied `book_id` | Treat the book as unavailable; do not retry unchanged |
| `Unknown` (`2`) | `book_id` is not a valid UUID | Validate UUID format before calling |
| `Unavailable` (`14`) | Catalog API is unreachable | Retry within the budgeted resilience policy |
## Related Documentation
- [[service|catalog-api]] — Service overview, persistence, and gRPC services.
- [[entity|book]] — Book entity model.
- [[query|GetBooksGrpc]] — Preferred batch gRPC RPC used by [[service|basket-api]] and [[service|order-api]].
- [[query|GetBookDetailsGrpc]] — Full-detail gRPC RPC returning complete book metadata.
## Raw Schema:schema.proto
edition = "2023";
package book.v1;
service BookGrpcService {
rpc GetBook (GetBookRequest) returns (GetBookResponse);
}
message GetBookRequest {
string book_id = 1;
}
message GetBookResponse {
string id = 1;
string name = 2;
DecimalValue price = 3;
DecimalValue price_sale = 4;
BookStatus status = 5;
}
enum BookStatus {
BOOK_STATUS_UNSPECIFIED = 0;
BOOK_STATUS_IN_STOCK = 1;
BOOK_STATUS_OUT_OF_STOCK = 2;
}
message DecimalValue {
int64 units = 1;
sfixed32 nanos = 2;
}
---
id: GetBooksGrpc
name: Get books over gRPC
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Returns multiple Catalog books by identifier through the book.v1 gRPC contract.
owners:
- catalog-experience-team
schemaPath: schema.proto
sidebar:
badge: "gRPC"
---
`GetBooksGrpc` invokes the internal `book.v1.BookGrpcService/GetBooks` gRPC unary RPC on [[service|catalog-api]] to fetch compact commercial summaries (ID, name, price, sale price, and stock status) for multiple books in a single round trip. [[service|basket-api]] calls this RPC to enrich basket items on read, and [[service|order-api]] calls it during checkout and order detail enrichment.
## Overview
| Property | Value |
| :--------------------------------- | :----------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | gRPC unary RPC (`book.v1.BookGrpcService/GetBooks`), Protobuf `edition = "2023"` |
| **Gateway Endpoint** | Internal gRPC RPC `book.v1.BookGrpcService/GetBooks` (not exposed via API Gateway) |
| **Authentication & Authorization** | Internal service-to-service anonymous read |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | Deduplicates `book_ids`, resolves hits per ID in L1 + Redis L2, and batch-queries PostgreSQL only for misses |
| **Contract Version** | `1.0.0` |
:::note
`GetBooks` silently omits unknown book IDs rather than returning `NotFound`, and returns an empty `GetBooksResponse` when `book_ids` is empty. Callers must reconcile returned `books` against requested `book_ids`.
:::
## Request & Response Contract
### Request Message (`GetBooksRequest`)
| Name | Type | Required | Constraints | Description |
| :--------- | :-------------------- | :------- | :-------------------------------- | :----------------------------------------------------- |
| `book_ids` | `string[]` (`uuid[]`) | Yes | Tag `1` (`repeated`); valid UUIDs | List of book UUIDs to fetch (deduplicated server-side) |
### Success Response (`GetBooksResponse`)
| Name | Type | Required | Constraints | Description |
| :------------------- | :------------------ | :------- | :------------------------------------------------------------------- | :--------------------------------------------------- |
| `books` | `GetBookResponse[]` | Yes | Tag `1` (`repeated`) | Matched book summaries in deduplicated request order |
| `books[].id` | `string` (`uuid`) | Yes | Tag `1` | Book UUID |
| `books[].name` | `string` | Yes | Tag `2` | Book title |
| `books[].price` | `DecimalValue` | Yes | Tag `3` (`int64 units`, `sfixed32 nanos`) | Regular unit price |
| `books[].price_sale` | `DecimalValue` | No | Tag `4` (omitted when no sale applies) | Promotional sale price |
| `books[].status` | `BookStatus` | Yes | Tag `5` (`BOOK_STATUS_IN_STOCK = 1`, `BOOK_STATUS_OUT_OF_STOCK = 2`) | Current stock availability status |
## Behavior & Side Effects
- **Per-ID cache batching:** Resolves cached book summaries first and batch-queries PostgreSQL only for cache misses, populating cache entries for subsequent reads.
- **No state mutation:** Pure read RPC with no database writes or integration events.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :------------------- | :------------------------------------------ | :------------------------------------------ |
| `Unknown` (`2`) | Any entry in `book_ids` is not a valid UUID | Validate all UUIDs before calling |
| `Unavailable` (`14`) | Catalog API is unreachable | Retry within the budgeted resilience policy |
## Related Documentation
- [[service|catalog-api]] — Service overview, persistence, and gRPC services.
- [[entity|book]] — Book entity model.
- [[query|GetBasket]] — Basket API endpoint that enriches items via `GetBooks`.
- [[query|GetOrder]] — Ordering API endpoint that enriches order line-item names via `GetBooks`.
- [[query|GetBookGrpc]] — Single-book compact gRPC RPC.
## Raw Schema:schema.proto
edition = "2023";
package book.v1;
service BookGrpcService {
rpc GetBooks (GetBooksRequest) returns (GetBooksResponse);
}
message GetBooksRequest {
repeated string book_ids = 1;
}
message GetBooksResponse {
repeated GetBookResponse books = 1;
}
message GetBookResponse {
string id = 1;
string name = 2;
DecimalValue price = 3;
DecimalValue price_sale = 4;
BookStatus status = 5;
}
enum BookStatus {
BOOK_STATUS_UNSPECIFIED = 0;
BOOK_STATUS_IN_STOCK = 1;
BOOK_STATUS_OUT_OF_STOCK = 2;
}
message DecimalValue {
int64 units = 1;
sfixed32 nanos = 2;
}
---
id: GetBuyer
name: Get buyer
version: 1.0.0
badges:
- content: Customer Management
backgroundColor: orange
textColor: orange
summary: Returns the Buyer profile selected by identifier, subject to the caller's authorization.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
operation:
method: GET
path: /api/v1/buyers/me
statusCodes: ["200", "404"]
sidebar:
badge: "GET"
---
`GetBuyer` queries [[service|order-api]] (`GET /ordering/api/v1/buyers/me`) to retrieve a buyer's profile (`id`, `name`, and `address`). Callers with the `admin` role retrieve the profile specified by the `Id` query parameter; all other authenticated callers are resolved to the buyer linked to their Microsoft Entra ID `NameIdentifier` claim.
## Overview
| Property | Value |
| :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Ordering |
| **Owner Service** | [[service\|order-api]] |
| **Protocol / Format** | HTTP `GET`, `application/json` response |
| **Gateway Endpoint** | `GET /ordering/api/v1/buyers/me` (service path `/api/v1/buyers/me`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `customer` or `admin` role plus scopes `ordering_read`, `ordering_write` |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` limit, `20` per `10s`, queue `5`) |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Query Parameters
| Name | Type | Required | Constraints | Description |
| :--- | :---------------- | :------- | :---------- | :---------------------------------------------------------------------------------------------------------------------------- |
| `Id` | `string` (`uuid`) | Yes | Valid UUID | Buyer identifier requested by `admin` callers; ignored for non-admin callers whose buyer ID is resolved from `NameIdentifier` |
:::note
Because `Id` binds as a non-nullable UUID, non-admin clients must still supply a valid UUID query parameter even though the service resolves their own authenticated buyer ID.
:::
### Success Response (`200 OK`)
| Name | Type | Required | Constraints | Description |
| :-------- | :---------------- | :------- | :---------- | :--------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | Valid UUID | Unique identifier of the buyer profile |
| `name` | `string \| null` | Yes | Nullable | Buyer display name (`null` when unset) |
| `address` | `string \| null` | Yes | Nullable | Formatted shipping address (`null` when unset) |
## Behavior & Side Effects
- **Role-scoped resolution:** Administrators query by the supplied `Id` parameter; standard customers always resolve their own profile from their token's `NameIdentifier` claim.
- **No state mutation:** Pure read query with no database writes or integration events.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :---------------------- | :-------------------------------------------------------- | :---------------------------------------------------------------------- |
| `400 Bad Request` | Missing or malformed `Id` UUID query parameter | Supply a valid UUID in the `Id` query parameter; do not retry unchanged |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID bearer token | Re-authenticate and retry |
| `403 Forbidden` | Caller lacks Ordering API roles or scopes | Request a token with `customer` or `admin` role and Ordering scopes |
| `404 Not Found` | No buyer profile exists for the resolved buyer ID | Prompt the user to create a buyer profile via [[command\|CreateBuyer]] |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` duration before retrying |
## Related Documentation
- [[service|order-api]] — Service overview, persistence, and endpoints.
- [[entity|buyer]] — Buyer entity model.
- [[query|ListBuyers]] — Admin-only paginated listing of all buyer profiles.
- [[command|CreateBuyer]] — Create a new buyer profile.
- [[command|UpdateAddress]] — Update a buyer's shipping address.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "BuyerDto",
"description": "Buyer profile response documented by the Ordering API OpenAPI contract.",
"type": "object",
"required": ["id", "name", "address"],
"properties": {
"id": {
"type": "string",
"format": "uuid"
},
"name": {
"type": ["string", "null"]
},
"address": {
"type": ["string", "null"]
}
}
}
---
id: GetDashboardGrpc
name: Get catalog dashboard over gRPC
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Returns Catalog totals and category counts through the admin-protected book.v1 gRPC contract.
owners:
- catalog-experience-team
schemaPath: schema.proto
sidebar:
badge: "gRPC"
---
`GetDashboardGrpc` invokes the admin-protected `book.v1.BookGrpcService/GetDashboard` gRPC unary RPC on [[service|catalog-api]] to retrieve total catalog book counts and per-category book counts. [[service|order-api]] calls this RPC with an exchanged Microsoft Entra ID administrator token when refreshing the Backoffice dashboard.
## Overview
| Property | Value |
| :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | gRPC unary RPC (`book.v1.BookGrpcService/GetDashboard`), Protobuf `edition = "2023"` |
| **Gateway Endpoint** | Internal gRPC RPC `book.v1.BookGrpcService/GetDashboard` (not exposed via API Gateway) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `admin` policy (`admin` role and `catalog_read`/`catalog_write` scopes) via `Authorization: Bearer ` metadata |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | Cached in L1 + Redis L2 for `15 seconds` |
| **Contract Version** | `1.0.0` |
## Request & Response Contract
### Request Message (`GetDashboardRequest`)
Empty Protobuf message with no fields.
### Success Response (`GetDashboardResponse`)
| Name | Type | Required | Constraints | Description |
| :------------------- | :-------------------- | :------- | :------------------- | :--------------------------------------- |
| `total_books` | `int64` | Yes | Tag `1`; `>= 0` | Sum of book counts across all categories |
| `categories` | `DashboardCategory[]` | Yes | Tag `2` (`repeated`) | Per-category book counts |
| `categories[].name` | `string` | Yes | Tag `1` | Category display name |
| `categories[].value` | `int64` | Yes | Tag `2`; `>= 0` | Number of books assigned to the category |
## Behavior & Side Effects
- **Short-lived aggregation cache:** Aggregates book counts per category from PostgreSQL and caches the result for 15 seconds.
- **No state mutation:** Pure read RPC with no database writes or integration events.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :----------------------- | :------------------------------------------------------------------ | :-------------------------------------------------------------------- |
| `Unauthenticated` (`16`) | Missing, expired, or invalid Entra ID bearer token in gRPC metadata | Exchange a valid administrator token scoped for Catalog API and retry |
| `PermissionDenied` (`7`) | Authenticated caller does not satisfy the `admin` policy | Authenticate with an `admin` role principal |
| `Unavailable` (`14`) | Catalog API is unreachable | Retry within the budgeted resilience policy |
## Related Documentation
- [[service|catalog-api]] — Service overview, persistence, and gRPC services.
- [[service|order-api]] — Primary caller hosting the administrative dashboard.
- [[query|ListCategoriesGrpc]] — Anonymous gRPC category listing.
## Raw Schema:schema.proto
edition = "2023";
package book.v1;
service BookGrpcService {
rpc GetDashboard (GetDashboardRequest) returns (GetDashboardResponse);
}
message GetDashboardRequest {}
message GetDashboardResponse {
int64 total_books = 1;
repeated DashboardCategory categories = 2;
}
message DashboardCategory {
string name = 1;
int64 value = 2;
}
---
id: GetOrder
name: Get order
version: 1.0.0
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
summary: Returns Order details, including the recorded item quantities and prices.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
operation:
method: GET
path: /api/v1/orders/{id}
statusCodes: ["200", "404"]
sidebar:
badge: "GET"
---
`GetOrder` queries [[service|order-api]] (`GET /ordering/api/v1/orders/{id}`) to retrieve a single order's header metadata, purchase-time unit prices, quantities, and book display names. Standard customers can retrieve only their own orders, while administrators (`admin` role) can retrieve any order; nonexistent and out-of-scope orders both return `404 Not Found`.
## Overview
| Property | Value |
| :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Ordering |
| **Owner Service** | [[service\|order-api]] |
| **Protocol / Format** | HTTP `GET`, `application/json` response |
| **Gateway Endpoint** | `GET /ordering/api/v1/orders/{id}` (service path `/api/v1/orders/{id}`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `customer` or `admin` role plus scopes `ordering_read`, `ordering_write` |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` limit, `20` per `10s`, queue `5`) |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Path Parameters
| Name | Type | Required | Constraints | Description |
| :--- | :---------------- | :------- | :---------- | :----------------------------------------- |
| `id` | `string` (`uuid`) | Yes | Valid UUID | Unique identifier of the order to retrieve |
### Success Response (`200 OK`)
| Name | Type | Required | Constraints | Description |
| :----------------- | :--------------------- | :------- | :------------------------------------ | :----------------------------------------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | Valid UUID | Unique identifier of the order |
| `date` | `string` (`date-time`) | Yes | ISO 8601 UTC timestamp | UTC timestamp when the order was placed |
| `total` | `number` | Yes | Decimal currency amount | Total order amount computed from recorded item prices and quantities |
| `status` | `string` | Yes | Enum: `New`, `Cancelled`, `Completed` | Current lifecycle status of the order |
| `items` | `object[]` | Yes | Array | Line items recorded at checkout |
| `items[].id` | `string` (`uuid`) | Yes | Valid UUID | Catalog book identifier |
| `items[].quantity` | `integer` | Yes | `> 0` | Purchased unit quantity |
| `items[].price` | `number` | Yes | Decimal currency amount | Unit price locked at checkout (does not change if Catalog prices update later) |
| `items[].name` | `string \| null` | No | Nullable | Book title enriched via [[query\|GetBooksGrpc]] (`null` if unavailable) |
## Behavior & Side Effects
- **Catalog enrichment:** Reads recorded order items from PostgreSQL and enriches `items[].name` via [[query|GetBooksGrpc]] when items exist.
- **No state mutation:** Pure read query with no database writes or integration events.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :---------------------- | :------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------- |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID bearer token | Re-authenticate and retry |
| `403 Forbidden` | Caller lacks Ordering API roles or scopes | Request a token with `customer` or `admin` role and Ordering scopes |
| `404 Not Found` | Order does not exist, is soft-deleted, or belongs to another buyer outside the caller's role scope | Display a not-found state; do not assume whether the ID belongs to another customer |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` duration before retrying |
## Related Documentation
- [[service|order-api]] — Service overview, persistence, and endpoints.
- [[entity|order]] — Order entity model.
- [[query|ListOrders]] — Paginated and filterable order summary listing.
- [[query|GetBooksGrpc]] — Catalog API gRPC query used to enrich line-item names.
- [[command|CancelOrder]] — Transition an order to `Cancelled`.
- [[command|CompleteOrder]] — Transition an order to `Completed`.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "OrderDetailDto",
"description": "Order detail response documented by the Ordering API OpenAPI contract.",
"type": "object",
"required": ["id", "date", "total", "status", "items"],
"properties": {
"id": {
"type": "string",
"format": "uuid"
},
"date": {
"type": "string",
"format": "date-time"
},
"total": {
"type": "number"
},
"status": {
"type": "string",
"enum": ["New", "Cancelled", "Completed"]
},
"items": {
"type": "array",
"items": {
"type": "object",
"required": ["id", "quantity", "price"],
"properties": {
"id": {
"type": "string",
"format": "uuid"
},
"quantity": {
"type": "integer"
},
"price": {
"type": "number"
},
"name": {
"type": ["string", "null"]
}
}
}
}
}
}
---
id: GetRecognizers
name: Get recognizers
version: 1.0.0
badges:
- content: Privacy
backgroundColor: red
textColor: red
summary: Returns the names of PII recognizers available for the requested language.
owners:
- platform-engineering-team
schemaPath: schema.json
operation:
method: GET
path: /recognizers
statusCodes: ["200"]
sidebar:
badge: "GET"
---
`GetRecognizers` queries the internal [[service|presidio-api]] Analyzer sidecar (`GET /recognizers`) to list the PII recognizers available for a language. This endpoint is an upstream capability discovery query; BookWorm's runtime PII middleware calls only `POST /analyze` (defaulting to `language: "en"`).
## Overview
| Property | Value |
| :--------------------------------- | :---------------------------------------------------------------- |
| **Bounded Context** | Data Privacy (External Integration) |
| **Owner Service** | [[service\|presidio-api]] (`presidio-analyzer`) |
| **Protocol / Format** | HTTP `GET /recognizers`, `application/json` response |
| **Gateway Endpoint** | Internal sidecar `GET /recognizers` (not exposed via API Gateway) |
| **Authentication & Authorization** | None (internal service-to-service network boundary) |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | None (sidecar) |
| **Contract Version** | `1.0.0` |
:::note
**Capability discovery only:** BookWorm's runtime privacy middleware does not call `GET /recognizers`; it calls [[command|AnalyzeText]] with `language: "en"`.
:::
## Request & Response Contract
### Query Parameters
| Name | Type | Required | Constraints | Description |
| :--------- | :------- | :------- | :---------------------------------------- | :---------------------------------------------------------------------- |
| `language` | `string` | No | Two-character ISO 639-1 code (e.g., `en`) | Filters returned recognizers to those loaded for the specified language |
### Success Response (`200 OK`)
| Name | Type | Required | Constraints | Description |
| :--------- | :--------- | :------- | :------------------------ | :--------------------------------------------------------- |
| Root value | `string[]` | Yes | Array of recognizer names | Names of PII recognizers loaded for the requested language |
## Behavior & Side Effects
- **Read-only discovery:** Returns loaded recognizer names from the sidecar without mutating state.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :----------------------------------------------------------------------------------------------------- | :------------------------------------------------------ |
| `500 Internal Server Error` | Unsupported `language` (`"No matching recognizers were found to serve the request."`) or sidecar error | Supply a supported ISO 639-1 language code (e.g., `en`) |
## Related Documentation
- [[service|presidio-api]] — Service overview and privacy middleware integration.
- [[command|AnalyzeText]] — Runtime `POST /analyze` command used by [[service|chat-api]] and [[service|rating-api]].
- [[query|GetSupportedEntities]] — List detectable PII entity types in Presidio Analyzer.
- [[query|GetAnonymizers]] — List built-in anonymization operators in Presidio Anonymizer.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "GetRecognizersResponse",
"description": "Recognizer names available for the requested language.",
"type": "array",
"items": { "type": "string" }
}
---
id: GetSupportedEntities
name: Get supported entities
version: 1.0.0
badges:
- content: Privacy
backgroundColor: red
textColor: red
summary: Returns the PII entity types Presidio Analyzer can detect for the requested language.
owners:
- platform-engineering-team
schemaPath: schema.json
operation:
method: GET
path: /supportedentities
statusCodes: ["200"]
sidebar:
badge: "GET"
---
`GetSupportedEntities` queries the internal [[service|presidio-api]] Analyzer sidecar (`GET /supportedentities`) to list the PII entity types the analyzer can detect for a language. This endpoint reports upstream Analyzer capability; BookWorm's runtime PII middleware calls only `POST /analyze`.
## Overview
| Property | Value |
| :--------------------------------- | :---------------------------------------------------------------------- |
| **Bounded Context** | Data Privacy (External Integration) |
| **Owner Service** | [[service\|presidio-api]] (`presidio-analyzer`) |
| **Protocol / Format** | HTTP `GET /supportedentities`, `application/json` response |
| **Gateway Endpoint** | Internal sidecar `GET /supportedentities` (not exposed via API Gateway) |
| **Authentication & Authorization** | None (internal service-to-service network boundary) |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | None (sidecar) |
| **Contract Version** | `1.0.0` |
:::note
**Capability discovery only:** The returned list describes Presidio Analyzer capability rather than a BookWorm allowlist. At runtime, BookWorm calls [[command|AnalyzeText]] (`language: "en"`) without an `entities` filter and replaces all detected spans via [[command|AnonymizeText]].
:::
## Request & Response Contract
### Query Parameters
| Name | Type | Required | Constraints | Description |
| :--------- | :------- | :------- | :---------------------------------------- | :------------------------------------------------------------------------------ |
| `language` | `string` | No | Two-character ISO 639-1 code (e.g., `en`) | Filters returned PII entity types to those supported for the specified language |
### Success Response (`200 OK`)
| Name | Type | Required | Constraints | Description |
| :--------- | :--------- | :------- | :----------------------------------------- | :---------------------------------------------------------------------------------------------- |
| Root value | `string[]` | Yes | Array of uppercase entity type identifiers | PII entity types Presidio Analyzer can detect (e.g., `EMAIL_ADDRESS`, `PERSON`, `PHONE_NUMBER`) |
## Behavior & Side Effects
- **Read-only discovery:** Returns supported entity type identifiers from the sidecar without mutating state.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :----------------------------------------------------------------------------------------------------- | :------------------------------------------------------ |
| `500 Internal Server Error` | Unsupported `language` (`"No matching recognizers were found to serve the request."`) or sidecar error | Supply a supported ISO 639-1 language code (e.g., `en`) |
## Related Documentation
- [[service|presidio-api]] — Service overview and privacy middleware integration.
- [[command|AnalyzeText]] — Runtime `POST /analyze` command used by [[service|chat-api]] and [[service|rating-api]].
- [[query|GetRecognizers]] — List available PII recognizers in Presidio Analyzer.
- [[query|GetAnonymizers]] — List built-in anonymization operators in Presidio Anonymizer.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "GetSupportedEntitiesResponse",
"description": "PII entity types supported by Presidio Analyzer for the requested language.",
"type": "array",
"items": { "type": "string" }
}
---
id: ListAuthors
name: List authors
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Returns all authors known to the Catalog.
owners:
- catalog-experience-team
schemaPath: schema.json
operation:
method: GET
path: /api/v1/authors
statusCodes: ["200"]
sidebar:
badge: "GET"
---
`ListAuthors` queries [[service|catalog-api]] (`GET /catalog/api/v1/authors`) to return all registered catalog authors as an unpaginated JSON array. The endpoint is publicly readable, returns `[]` with `200 OK` when no authors exist, and caches the directory.
## Overview
| Property | Value |
| :--------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | HTTP `GET`, `application/json` response |
| **Gateway Endpoint** | `GET /catalog/api/v1/authors` (service path `/api/v1/authors`) |
| **Authentication & Authorization** | None required (public read endpoint) |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` limit, `20` per `10s`, queue `5`); cached in L1 + Redis L2 |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Request Parameters
Accepts no path parameters, query parameters, or request body.
### Success Response (`200 OK`)
Returns a JSON array of author objects (`additionalProperties: false`).
| Name | Type | Required | Constraints | Description |
| :-------- | :---------------- | :------- | :---------- | :-------------------------------------- |
| `[].id` | `string` (`uuid`) | Yes | Valid UUID | Unique identifier of the author |
| `[].name` | `string \| null` | Yes | Nullable | Author display name (`null` when unset) |
## Behavior & Side Effects
- **Read-through caching:** Serves the author directory from L1/Redis L2 cache and invalidates when authors are created, updated, or deleted.
- **No state mutation:** Pure read query with no database writes or integration events.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :---------------------- | :-------------------------------------------------------- | :-------------------------------------------------- |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` duration before retrying |
## Related Documentation
- [[service|catalog-api]] — Service overview, persistence, and endpoints.
- [[entity|author]] — Author entity model.
- [[query|ListAuthorsGrpc]] — Internal gRPC contract used by MCP Tools.
- [[command|CreateAuthor]] — Create a new catalog author.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "ListAuthorsResponse",
"description": "Collection of authors returned by the Catalog API.",
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["id", "name"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "A UUID identifying the resource."
},
"name": {
"type": ["string", "null"],
"description": "Author display name."
}
}
}
}
---
id: ListAuthorsGrpc
name: List authors over gRPC
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Returns all Catalog authors through the book.v1 gRPC contract.
owners:
- catalog-experience-team
schemaPath: schema.proto
sidebar:
badge: "gRPC"
---
`ListAuthorsGrpc` invokes the internal `book.v1.BookGrpcService/ListAuthors` gRPC unary RPC on [[service|catalog-api]] to return all registered catalog authors without pagination. [[service|mcp-server]] calls this RPC to power its `list_authors` tool.
## Overview
| Property | Value |
| :--------------------------------- | :------------------------------------------------------------------------------------ |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | gRPC unary RPC (`book.v1.BookGrpcService/ListAuthors`), Protobuf `edition = "2023"` |
| **Gateway Endpoint** | Internal gRPC RPC `book.v1.BookGrpcService/ListAuthors` (not exposed via API Gateway) |
| **Authentication & Authorization** | Internal service-to-service anonymous read |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | Backed by PostgreSQL and cached in L1 + Redis L2 |
| **Contract Version** | `1.0.0` |
## Request & Response Contract
### Request Message (`ListAuthorsRequest`)
Empty Protobuf message with no fields.
### Success Response (`ListAuthorsResponse`)
| Name | Type | Required | Constraints | Description |
| :--------------- | :---------------- | :------- | :----------------------------- | :--------------------------------------------------- |
| `authors` | `AuthorItem[]` | Yes | Tag `1` (`repeated`) | All catalog authors (empty collection if none exist) |
| `authors[].id` | `string` (`uuid`) | Yes | Tag `1` | Author UUID |
| `authors[].name` | `string` | Yes | Tag `2` (empty string if null) | Author display name |
## Behavior & Side Effects
- **Read-through caching:** Serves the author directory from L1/Redis L2 cache, shared with [[query|ListAuthors]].
- **No state mutation:** Pure read RPC with no database writes or integration events.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :------------------- | :------------------------- | :------------------------------------------ |
| `Unavailable` (`14`) | Catalog API is unreachable | Retry within the budgeted resilience policy |
## Related Documentation
- [[service|catalog-api]] — Service overview, persistence, and gRPC services.
- [[service|mcp-server]] — Primary caller exposing the `list_authors` MCP tool.
- [[entity|author]] — Author entity model.
- [[query|ListAuthors]] — Public HTTP endpoint (`GET /catalog/api/v1/authors`).
## Raw Schema:schema.proto
edition = "2023";
package book.v1;
service BookGrpcService {
rpc ListAuthors (ListAuthorsRequest) returns (ListAuthorsResponse);
}
message ListAuthorsRequest {}
message ListAuthorsResponse {
repeated AuthorItem authors = 1;
}
message AuthorItem {
string id = 1;
string name = 2;
}
---
id: ListBooks
name: List books
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Returns a filterable collection of books with pricing, availability, relationships, and rating summaries.
owners:
- catalog-experience-team
schemaPath: schema.json
operation:
method: QUERY
path: /api/v1/books
statusCodes: ["200", "400"]
sidebar:
badge: "QUERY"
---
`ListBooks` queries [[service|catalog-api]] (`QUERY /catalog/api/v1/books`) with an optional JSON request body to search, filter, sort, and paginate catalog books. The endpoint is publicly readable, uses hybrid vector search when `search` is supplied, caches results, and emits total counts and navigation links in HTTP response headers.
## Overview
| Property | Value |
| :--------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | HTTP `QUERY`, `application/json` request and response |
| **Gateway Endpoint** | `QUERY /catalog/api/v1/books` (service path `/api/v1/books`) |
| **Authentication & Authorization** | None required (public read endpoint) |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` limit, `20` per `10s`, queue `5`); caches search IDs (`5 min`) and filtered pages (`60s`) |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Request Body (`application/json`, optional)
Omitting the request body applies all defaults below.
| Name | Type | Required | Constraints | Description |
| :------------- | :----------------- | :------- | :---------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------- |
| `pageIndex` | `integer` | No | Default `1`; must be `> 0` | 1-based page number to retrieve |
| `pageSize` | `integer` | No | Default `20`; must be `> 0` | Maximum number of books per page (also caps vector search candidate count) |
| `orderBy` | `string \| null` | No | Default `"Name"`; supports `Name`, `Price.OriginalPrice`, `Price.DiscountPrice`, `Status` | Field used to sort results (unknown values fall back to `Name`; ties ordered by ID) |
| `isDescending` | `boolean` | No | Default `false` | Sorts descending when `true` and ascending when `false` |
| `search` | `string \| null` | No | Trimmed, lowercased for cache key | Free-text query executed via hybrid vector search; returns empty page if zero vector hits match |
| `minPrice` | `number \| null` | No | Decimal | Inclusive minimum price filter |
| `maxPrice` | `number \| null` | No | Decimal | Inclusive maximum price filter |
| `categoryId` | `string[] \| null` | No | Array of UUIDs | Restricts results to books matching any supplied category ID |
| `publisherId` | `string[] \| null` | No | Array of UUIDs | Restricts results to books matching any supplied publisher ID |
| `authorIds` | `string[] \| null` | No | Array of UUIDs | Restricts results to books associated with any supplied author ID |
### Response Headers (`200 OK`)
| Name | Type | Required | Constraints | Description |
| :----------------- | :------- | :------- | :---------------------------------------- | :------------------------------------------------------------------------------------------ |
| `Pagination-Count` | `string` | Yes | Integer string (e.g., `84`) | Total number of books matching the active filters across all pages |
| `Link` | `string` | Yes | Comma-separated `;rel=` entries | Navigation URIs with `first`, `self`, `last`, and conditional `previous` / `next` relations |
### Success Response (`200 OK`)
Returns a JSON array of book objects (`[]` when no books match). Each item matches the response schema documented in [[query|GetBook]].
## Behavior & Side Effects
- **Hybrid vector search:** When `search` is non-empty, executes a hybrid vector search against Qdrant and filters matching book IDs from PostgreSQL.
- **Two-tier caching:** Caches vector search ID lists for 5 minutes and filtered page results for 60 seconds; invalidated on catalog mutations.
- **No state mutation:** Pure read query with no database writes or integration events.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :---------------------- | :------------------------------------------------------------------------------------------ | :-------------------------------------------------- |
| `400 Bad Request` | `pageIndex <= 0`, `pageSize <= 0`, malformed UUID in filter arrays, or invalid JSON payload | Fix request body values; do not retry unchanged |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` duration before retrying |
## Related Documentation
- [[service|catalog-api]] — Service overview, persistence, and endpoints.
- [[entity|book]] — Book entity model.
- [[query|GetBook]] — Retrieve a single book projection by ID.
- [[query|ListBooksGrpc]] — Internal gRPC book search endpoint used by MCP Tools.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "ListBooksResponse",
"description": "Book collection returned by the Catalog API.",
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"required": [
"id",
"name",
"description",
"imageUrl",
"price",
"priceSale",
"status",
"category",
"publisher",
"authors",
"averageRating",
"totalReviews"
],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "A UUID identifying the resource."
},
"name": {
"type": ["string", "null"]
},
"description": {
"type": ["string", "null"]
},
"imageUrl": {
"type": ["string", "null"],
"format": "uri"
},
"price": {
"type": "number"
},
"priceSale": {
"type": ["number", "null"]
},
"status": {
"type": "string",
"enum": ["InStock", "OutOfStock"]
},
"category": {
"type": ["object", "null"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "A UUID identifying the resource."
},
"name": {
"type": ["string", "null"]
}
},
"required": ["id", "name"]
},
"publisher": {
"type": ["object", "null"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "A UUID identifying the resource."
},
"name": {
"type": ["string", "null"]
}
},
"required": ["id", "name"]
},
"authors": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "A UUID identifying the resource."
},
"name": {
"type": ["string", "null"]
}
},
"required": ["id", "name"]
}
},
"averageRating": {
"type": "number",
"minimum": 0
},
"totalReviews": {
"type": "integer",
"minimum": 0
}
}
}
}
---
id: ListBooksGrpc
name: List books over gRPC
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Searches and lists Catalog books with full metadata through the book.v1 gRPC contract.
owners:
- catalog-experience-team
schemaPath: schema.proto
sidebar:
badge: "gRPC"
---
`ListBooksGrpc` invokes the internal `book.v1.BookGrpcService/ListBooks` gRPC unary RPC on [[service|catalog-api]] to search and list books with full metadata (descriptions, images, pricing, stock status, relationships, and rating summaries). [[service|mcp-server]] calls this RPC to power its `search_catalog` tool.
## Overview
| Property | Value |
| :--------------------------------- | :------------------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | gRPC unary RPC (`book.v1.BookGrpcService/ListBooks`), Protobuf `edition = "2023"` |
| **Gateway Endpoint** | Internal gRPC RPC `book.v1.BookGrpcService/ListBooks` (not exposed via API Gateway) |
| **Authentication & Authorization** | Internal service-to-service anonymous read |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | Hybrid vector search (cached `5 min`) when `search` is non-empty; filtered page cached `60s` |
| **Contract Version** | `1.0.0` |
:::note
This RPC uses fixed defaults (`pageIndex = 1`, `pageSize = 20`, `orderBy = "Name"`, `isDescending = false`) and does not expose paging parameters. Callers requiring multi-page traversal or price/relationship filters must use HTTP [[query|ListBooks]].
:::
## Request & Response Contract
### Request Message (`ListBooksRequest`)
| Name | Type | Required | Constraints | Description |
| :------- | :------- | :------- | :------------------------------------------ | :------------------------------------------------------ |
| `search` | `string` | No | Tag `1`; blank/whitespace treated as `null` | Free-text search term executed via hybrid vector search |
### Success Response (`ListBooksResponse`)
| Name | Type | Required | Constraints | Description |
| :------ | :----------- | :------- | :----------------------------------- | :----------------------------------------------------------------------------------------------------------------------------- |
| `books` | `BookItem[]` | Yes | Tag `1` (`repeated`); max `20` items | Matching books with full metadata (empty collection if zero matches). See [[query\|GetBookDetailsGrpc]] for `BookItem` fields. |
## Behavior & Side Effects
- **Hybrid search & caching:** When `search` is non-empty, executes hybrid vector search against Qdrant and filters matching books from PostgreSQL.
- **No state mutation:** Pure read RPC with no database writes or integration events.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :------------------- | :--------------------------------------------------------------------------------------------- | :------------------------------------------ |
| `Unavailable` (`14`) | Catalog API (or backing Qdrant/PostgreSQL dependency during an uncached search) is unreachable | Retry within the budgeted resilience policy |
## Related Documentation
- [[service|catalog-api]] — Service overview, persistence, and gRPC services.
- [[service|mcp-server]] — Primary caller exposing the `search_catalog` MCP tool.
- [[entity|book]] — Book entity model.
- [[query|ListBooks]] — Public HTTP `QUERY /catalog/api/v1/books` supporting pagination and rich filters.
- [[query|GetBookDetailsGrpc]] — Full `BookItem` field schema and single-book lookup.
## Raw Schema:schema.proto
edition = "2023";
package book.v1;
service BookGrpcService {
rpc ListBooks (ListBooksRequest) returns (ListBooksResponse);
}
message ListBooksRequest {
string search = 1;
}
message ListBooksResponse {
repeated BookItem books = 1;
}
message BookItem {
string id = 1;
string name = 2;
string description = 3;
string image_url = 4;
DecimalValue price = 5;
DecimalValue price_sale = 6;
BookStatus status = 7;
CategoryItem category = 8;
PublisherItem publisher = 9;
repeated AuthorItem authors = 10;
double average_rating = 11;
int32 total_reviews = 12;
}
enum BookStatus {
BOOK_STATUS_UNSPECIFIED = 0;
BOOK_STATUS_IN_STOCK = 1;
BOOK_STATUS_OUT_OF_STOCK = 2;
}
message DecimalValue {
int64 units = 1;
sfixed32 nanos = 2;
}
message CategoryItem {
string id = 1;
string name = 2;
}
message PublisherItem {
string id = 1;
string name = 2;
}
message AuthorItem {
string id = 1;
string name = 2;
}
---
id: ListBuyers
name: List buyers
version: 1.0.0
badges:
- content: Customer Management
backgroundColor: orange
textColor: orange
summary: Returns Buyer profiles with pagination.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
operation:
method: GET
path: /api/v1/buyers
statusCodes: ["200"]
sidebar:
badge: "GET"
---
`ListBuyers` queries [[service|order-api]] (`GET /ordering/api/v1/buyers`) to return a paginated slice of registered buyer profiles for store administrators. The endpoint requires the Microsoft Entra ID `admin` policy and emits total item counts and navigation URIs in HTTP response headers.
## Overview
| Property | Value |
| :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Ordering |
| **Owner Service** | [[service\|order-api]] |
| **Protocol / Format** | HTTP `GET`, `application/json` response |
| **Gateway Endpoint** | `GET /ordering/api/v1/buyers` (service path `/api/v1/buyers`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `admin` policy (role `admin` plus scopes `ordering_read`, `ordering_write`) |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` limit, `20` per `10s`, queue `5`) |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Query Parameters
| Name | Type | Required | Constraints | Description |
| :---------- | :-------- | :------- | :-------------------------- | :---------------------------------------- |
| `PageIndex` | `integer` | No | Default `1`; must be `> 0` | 1-based page number to retrieve |
| `PageSize` | `integer` | No | Default `20`; must be `> 0` | Maximum number of buyer profiles per page |
### Response Headers (`200 OK`)
| Name | Type | Required | Constraints | Description |
| :----------------- | :------- | :------- | :---------------------------------------- | :------------------------------------------------------------------------------------------ |
| `Pagination-Count` | `string` | Yes | Integer string (e.g., `128`) | Total number of buyer profiles across all pages |
| `Link` | `string` | Yes | Comma-separated `;rel=` entries | Navigation URIs with `first`, `self`, `last`, and conditional `previous` / `next` relations |
### Success Response (`200 OK`)
Returns a JSON array of buyer summary objects.
| Name | Type | Required | Constraints | Description |
| :----------- | :---------------- | :------- | :---------- | :--------------------------------------------- |
| `[].id` | `string` (`uuid`) | Yes | Valid UUID | Unique identifier of the buyer profile |
| `[].name` | `string \| null` | Yes | Nullable | Buyer display name (`null` when unset) |
| `[].address` | `string \| null` | Yes | Nullable | Formatted shipping address (`null` when unset) |
## Behavior & Side Effects
- **Admin-scoped listing:** Returns paginated buyer profiles from PostgreSQL with `Pagination-Count` and `Link` headers.
- **No state mutation:** Pure read query with no database writes or integration events.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :---------------------- | :------------------------------------------------------------- | :----------------------------------------------------------------- |
| `400 Bad Request` | `PageIndex <= 0`, `PageSize <= 0`, or non-integer paging value | Fix paging parameters to positive integers; do not retry unchanged |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID bearer token | Re-authenticate and retry |
| `403 Forbidden` | Caller does not satisfy the `admin` authorization policy | Authenticate with an administrator account |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` duration before retrying |
## Related Documentation
- [[service|order-api]] — Service overview, persistence, and endpoints.
- [[entity|buyer]] — Buyer entity model.
- [[query|GetBuyer]] — Retrieve a single buyer profile.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "BuyerDtoArray",
"description": "Buyer list response documented by the Ordering API OpenAPI contract.",
"type": "array",
"items": {
"type": "object",
"required": ["id", "name", "address"],
"properties": {
"id": {
"type": "string",
"format": "uuid"
},
"name": {
"type": ["string", "null"]
},
"address": {
"type": ["string", "null"]
}
}
}
}
---
id: ListCategories
name: List categories
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Returns all categories known to the Catalog.
owners:
- catalog-experience-team
schemaPath: schema.json
operation:
method: GET
path: /api/v1/categories
statusCodes: ["200"]
sidebar:
badge: "GET"
---
`ListCategories` queries [[service|catalog-api]] (`GET /catalog/api/v1/categories`) to return all registered book categories as an unpaginated JSON array. The endpoint is publicly readable, returns `[]` with `200 OK` when no categories exist, and caches the taxonomy.
## Overview
| Property | Value |
| :--------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | HTTP `GET`, `application/json` response |
| **Gateway Endpoint** | `GET /catalog/api/v1/categories` (service path `/api/v1/categories`) |
| **Authentication & Authorization** | None required (public read endpoint) |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` limit, `20` per `10s`, queue `5`); cached in L1 + Redis L2 |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Request Parameters
Accepts no path parameters, query parameters, or request body.
### Success Response (`200 OK`)
Returns a JSON array of category objects (`additionalProperties: false`).
| Name | Type | Required | Constraints | Description |
| :-------- | :---------------- | :------- | :---------- | :---------------------------------------- |
| `[].id` | `string` (`uuid`) | Yes | Valid UUID | Unique identifier of the category |
| `[].name` | `string \| null` | Yes | Nullable | Category display name (`null` when unset) |
## Behavior & Side Effects
- **Read-through caching:** Serves the category taxonomy from L1/Redis L2 cache and invalidates when categories are created, updated, or deleted.
- **No state mutation:** Pure read query with no database writes or integration events.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :---------------------- | :-------------------------------------------------------- | :-------------------------------------------------- |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` duration before retrying |
## Related Documentation
- [[service|catalog-api]] — Service overview, persistence, and endpoints.
- [[entity|category]] — Category entity model.
- [[query|ListCategoriesGrpc]] — Internal gRPC contract used by MCP Tools.
- [[command|CreateCategory]] — Create a new catalog category.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "ListCategoriesResponse",
"description": "Collection of categories returned by the Catalog API.",
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["id", "name"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "A UUID identifying the resource."
},
"name": {
"type": ["string", "null"],
"description": "Categorie display name."
}
}
}
}
---
id: ListCategoriesGrpc
name: List categories over gRPC
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Returns all Catalog categories through the book.v1 gRPC contract.
owners:
- catalog-experience-team
schemaPath: schema.proto
sidebar:
badge: "gRPC"
---
`ListCategoriesGrpc` invokes the internal `book.v1.BookGrpcService/ListCategories` gRPC unary RPC on [[service|catalog-api]] to return all registered book categories without pagination. [[service|mcp-server]] calls this RPC to power its `list_categories` tool.
## Overview
| Property | Value |
| :--------------------------------- | :--------------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | gRPC unary RPC (`book.v1.BookGrpcService/ListCategories`), Protobuf `edition = "2023"` |
| **Gateway Endpoint** | Internal gRPC RPC `book.v1.BookGrpcService/ListCategories` (not exposed via API Gateway) |
| **Authentication & Authorization** | Internal service-to-service anonymous read |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | Backed by PostgreSQL and cached in L1 + Redis L2 |
| **Contract Version** | `1.0.0` |
## Request & Response Contract
### Request Message (`ListCategoriesRequest`)
Empty Protobuf message with no fields.
### Success Response (`ListCategoriesResponse`)
| Name | Type | Required | Constraints | Description |
| :------------------ | :---------------- | :------- | :----------------------------- | :------------------------------------------------------ |
| `categories` | `CategoryItem[]` | Yes | Tag `1` (`repeated`) | All catalog categories (empty collection if none exist) |
| `categories[].id` | `string` (`uuid`) | Yes | Tag `1` | Category UUID |
| `categories[].name` | `string` | Yes | Tag `2` (empty string if null) | Category display name |
## Behavior & Side Effects
- **Read-through caching:** Serves the category taxonomy from L1/Redis L2 cache, shared with [[query|ListCategories]].
- **No state mutation:** Pure read RPC with no database writes or integration events.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :------------------- | :------------------------- | :------------------------------------------ |
| `Unavailable` (`14`) | Catalog API is unreachable | Retry within the budgeted resilience policy |
## Related Documentation
- [[service|catalog-api]] — Service overview, persistence, and gRPC services.
- [[service|mcp-server]] — Primary caller exposing the `list_categories` MCP tool.
- [[entity|category]] — Category entity model.
- [[query|ListCategories]] — Public HTTP endpoint (`GET /catalog/api/v1/categories`).
## Raw Schema:schema.proto
edition = "2023";
package book.v1;
service BookGrpcService {
rpc ListCategories (ListCategoriesRequest) returns (ListCategoriesResponse);
}
message ListCategoriesRequest {}
message ListCategoriesResponse {
repeated CategoryItem categories = 1;
}
message CategoryItem {
string id = 1;
string name = 2;
}
---
id: ListFeedbacks
name: List feedbacks
version: 1.0.0
badges:
- content: Reviews
backgroundColor: purple
textColor: purple
summary: Returns feedback for a book with pagination, sorting, and validation responses.
owners:
- catalog-experience-team
schemaPath: schema.json
operation:
method: GET
path: /api/v1/feedbacks
statusCodes: ["200", "400"]
sidebar:
badge: "GET"
---
`ListFeedbacks` queries [[service|rating-api]] (`GET /rating/api/v1/feedbacks`) for a paginated, sorted page of customer feedback records belonging to a single Catalog book. The endpoint is publicly readable, caches pages for 10 minutes, and emits total counts and navigation links in HTTP response headers.
## Overview
| Property | Value |
| :--------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Reviews |
| **Owner Service** | [[service\|rating-api]] |
| **Protocol / Format** | HTTP `GET`, `application/json` response |
| **Gateway Endpoint** | `GET /rating/api/v1/feedbacks` (service path `/api/v1/feedbacks`) |
| **Authentication & Authorization** | None required (public read endpoint) |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` limit, `20` per `10s`, queue `5`); cached in L1 + Redis L2 for `10 minutes` tagged by `BookId` |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Query Parameters
| Name | Type | Required | Constraints | Description |
| :------------- | :---------------- | :------- | :----------------------------------------------------------------------------------- | :----------------------------------------------------------------- |
| `BookId` | `string` (`uuid`) | Yes | Valid UUID | Identifier of the Catalog book whose feedback records are returned |
| `PageIndex` | `integer` | No | Default `1`; must be `> 0` | 1-based page number to retrieve |
| `PageSize` | `integer` | No | Default `20`; must be `> 0` | Maximum number of feedback records per page |
| `OrderBy` | `string` | No | Default `"Rating"`; supports `Rating` and `CreatedAt` (others fall back to `Rating`) | Field used to sort feedback records |
| `IsDescending` | `boolean` | No | Default `false` | Sorts descending when `true` and ascending when `false` |
### Response Headers (`200 OK`)
| Name | Type | Required | Constraints | Description |
| :----------------- | :------- | :------- | :---------------------------------------- | :------------------------------------------------------------------------------------------------------------------- |
| `Pagination-Count` | `string` | Yes | Integer string (e.g., `42`) | Total number of feedback records matching `BookId` across all pages |
| `Link` | `string` | Yes | Comma-separated `;rel=` entries | Navigation URIs with `first`, `self`, `last`, and conditional `previous` / `next` relations preserving query filters |
### Success Response (`200 OK`)
Returns a JSON array of feedback objects (`additionalProperties: false`).
| Name | Type | Required | Constraints | Description |
| :------------- | :------------------ | :------- | :---------- | :-------------------------------------------- |
| `[].id` | `string` (`uuid`) | Yes | Valid UUID | Unique identifier of the feedback record |
| `[].firstName` | `string \| null` | Yes | Nullable | First name of the reviewer |
| `[].lastName` | `string \| null` | Yes | Nullable | Last name of the reviewer |
| `[].comment` | `string \| null` | Yes | Nullable | Written review text left by the reviewer |
| `[].rating` | `integer \| string` | Yes | `0`-`5` | Numeric star rating submitted by the reviewer |
| `[].bookId` | `string` (`uuid`) | Yes | Valid UUID | Identifier of the reviewed Catalog book |
## Behavior & Side Effects
- **Read-through caching:** Queries Azure Cosmos DB (`ratingdb`/`feedbacks`, partition key `/bookId`) and caches paginated results for 10 minutes; invalidated on feedback creation or deletion.
- **No state mutation:** Pure read query with no database writes or integration events.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :---------------------- | :-------------------------------------------------------------------- | :------------------------------------------------------- |
| `400 Bad Request` | Missing/malformed `BookId` or invalid `PageIndex`/`PageSize` (`<= 0`) | Correct invalid query parameters; do not retry unchanged |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` duration before retrying |
## Related Documentation
- [[service|rating-api]] — Service overview, Azure Cosmos DB storage, and endpoints.
- [[entity|feedback]] — Feedback document model.
- [[query|SummarizeFeedback]] — Generate an AI summary and classification for a book's feedback.
- [[command|CreateFeedback]] — Submit a new customer feedback record.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "ListFeedbacksResponse",
"description": "Feedback records returned for a Catalog book.",
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["id", "firstName", "lastName", "comment", "rating", "bookId"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "Unique identifier of the feedback record."
},
"firstName": {
"type": ["string", "null"],
"description": "First name of the reviewer."
},
"lastName": {
"type": ["string", "null"],
"description": "Last name of the reviewer."
},
"comment": {
"type": ["string", "null"],
"description": "Written feedback left by the reviewer."
},
"rating": {
"type": ["integer", "string"],
"format": "int32",
"description": "Rating value from 0 through 5."
},
"bookId": {
"type": "string",
"format": "uuid",
"description": "Identifier of the reviewed Catalog book."
}
}
}
}
---
id: ListOrders
name: List orders
version: 1.0.0
badges:
- content: Order Lifecycle
backgroundColor: blue
textColor: blue
summary: Returns Orders with pagination and optional status and Buyer filters.
owners:
- commerce-fulfillment-team
schemaPath: schema.json
operation:
method: GET
path: /api/v1/orders
statusCodes: ["200", "400"]
sidebar:
badge: "GET"
---
`ListOrders` queries [[service|order-api]] (`GET /ordering/api/v1/orders`) to return a paginated list of order summaries with optional status and buyer filters. Non-administrator callers are automatically scoped to their own authenticated Microsoft Entra ID buyer ID, while administrators (`admin` role) can filter across buyers.
## Overview
| Property | Value |
| :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Ordering |
| **Owner Service** | [[service\|order-api]] |
| **Protocol / Format** | HTTP `GET`, `application/json` response |
| **Gateway Endpoint** | `GET /ordering/api/v1/orders` (service path `/api/v1/orders`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `customer` or `admin` role plus scopes `ordering_read`, `ordering_write` |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` limit, `20` per `10s`, queue `5`) |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Query Parameters
| Name | Type | Required | Constraints | Description |
| :---------- | :---------------- | :------- | :------------------------------------ | :-------------------------------------------------------------------------------------------------------------- |
| `PageIndex` | `integer` | No | Default `1`; must be `> 0` | 1-based page number to retrieve |
| `PageSize` | `integer` | No | Default `20`; must be `> 0` | Maximum number of order summaries per page |
| `Status` | `string` | No | Enum: `New`, `Cancelled`, `Completed` | Filters orders by lifecycle status |
| `BuyerId` | `string` (`uuid`) | No | Valid UUID | Filters orders by buyer ID for `admin` callers; overridden with the caller's own buyer ID for non-admin callers |
### Response Headers (`200 OK`)
| Name | Type | Required | Constraints | Description |
| :----------------- | :------- | :------- | :---------------------------------------- | :------------------------------------------------------------------------------------------------------------------- |
| `Pagination-Count` | `string` | Yes | Integer string (e.g., `57`) | Total number of orders matching the active status and buyer filters across all pages |
| `Link` | `string` | Yes | Comma-separated `;rel=` entries | Navigation URIs with `first`, `self`, `last`, and conditional `previous` / `next` relations preserving query filters |
### Success Response (`200 OK`)
Returns a JSON array of order summary objects. To retrieve line items for an order, call [[query|GetOrder]].
| Name | Type | Required | Constraints | Description |
| :---------- | :--------------------- | :------- | :------------------------------------ | :-------------------------------------- |
| `[].id` | `string` (`uuid`) | Yes | Valid UUID | Unique identifier of the order |
| `[].date` | `string` (`date-time`) | Yes | ISO 8601 UTC timestamp | UTC timestamp when the order was placed |
| `[].total` | `number` | Yes | Decimal currency amount | Total recorded amount for the order |
| `[].status` | `string` | Yes | Enum: `New`, `Cancelled`, `Completed` | Current lifecycle status of the order |
## Behavior & Side Effects
- **Role-scoped filtering:** Standard customers only see their own orders (any `BuyerId` parameter is overridden); administrators can filter across all buyers.
- **No state mutation:** Pure read query with no database writes or integration events.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :---------------------- | :----------------------------------------------------------------------------------------------- | :------------------------------------------------------------------ |
| `400 Bad Request` | `PageIndex <= 0`, `PageSize <= 0`, unrecognized `Status` enum value, or malformed `BuyerId` UUID | Correct invalid query parameters; do not retry unchanged |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID bearer token | Re-authenticate and retry |
| `403 Forbidden` | Caller lacks Ordering API roles or scopes | Request a token with `customer` or `admin` role and Ordering scopes |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` duration before retrying |
## Related Documentation
- [[service|order-api]] — Service overview, persistence, and endpoints.
- [[entity|order]] — Order entity model.
- [[query|GetOrder]] — Retrieve full order details including line items.
- [[command|CreateOrder]] — Place a new order from the active basket.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "OrderDtoArray",
"description": "Order list response documented by the Ordering API OpenAPI contract.",
"type": "array",
"items": {
"type": "object",
"required": ["id", "date", "total", "status"],
"properties": {
"id": {
"type": "string",
"format": "uuid"
},
"date": {
"type": "string",
"format": "date-time"
},
"total": {
"type": "number"
},
"status": {
"type": "string",
"enum": ["New", "Cancelled", "Completed"]
}
}
}
}
---
id: ListPublishers
name: List publishers
version: 1.0.0
badges:
- content: Catalog Management
backgroundColor: green
textColor: green
summary: Returns all publishers known to the Catalog.
owners:
- catalog-experience-team
schemaPath: schema.json
operation:
method: GET
path: /api/v1/publishers
statusCodes: ["200"]
sidebar:
badge: "GET"
---
`ListPublishers` queries [[service|catalog-api]] (`GET /catalog/api/v1/publishers`) to return all registered book publishers as an unpaginated JSON array. The endpoint is publicly readable, returns `[]` with `200 OK` when no publishers exist, and caches the directory.
## Overview
| Property | Value |
| :--------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Catalog |
| **Owner Service** | [[service\|catalog-api]] |
| **Protocol / Format** | HTTP `GET`, `application/json` response |
| **Gateway Endpoint** | `GET /catalog/api/v1/publishers` (service path `/api/v1/publishers`) |
| **Authentication & Authorization** | None required (public read endpoint) |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` limit, `20` per `10s`, queue `5`); cached in L1 + Redis L2 |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
## Request & Response Contract
### Request Parameters
Accepts no path parameters, query parameters, or request body.
### Success Response (`200 OK`)
Returns a JSON array of publisher objects (`additionalProperties: false`).
| Name | Type | Required | Constraints | Description |
| :-------- | :---------------- | :------- | :---------- | :----------------------------------------- |
| `[].id` | `string` (`uuid`) | Yes | Valid UUID | Unique identifier of the publisher |
| `[].name` | `string \| null` | Yes | Nullable | Publisher display name (`null` when unset) |
## Behavior & Side Effects
- **Read-through caching:** Serves the publisher directory from L1/Redis L2 cache and invalidates when publishers are created, updated, or deleted.
- **No state mutation:** Pure read query with no database writes or integration events.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :---------------------- | :-------------------------------------------------------- | :-------------------------------------------------- |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` duration before retrying |
## Related Documentation
- [[service|catalog-api]] — Service overview, persistence, and endpoints.
- [[entity|publisher]] — Publisher entity model.
- [[command|CreatePublisher]] — Create a new catalog publisher.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "ListPublishersResponse",
"description": "Collection of publishers returned by the Catalog API.",
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["id", "name"],
"properties": {
"id": {
"type": "string",
"format": "uuid",
"description": "A UUID identifying the resource."
},
"name": {
"type": ["string", "null"],
"description": "Publisher display name."
}
}
}
}
---
id: SummarizeFeedback
name: Summarize feedback
version: 1.0.0
badges:
- content: Reviews
backgroundColor: purple
textColor: purple
summary: Returns a generated feedback summary, classification, rating metrics, evidence, and confidence for a book.
owners:
- catalog-experience-team
diagrams:
- id: rating-summarizer-workflow
version: 1.0.0
schemaPath: schema.json
operation:
method: GET
path: /api/v1/feedbacks/{id}/summarize
statusCodes: ["200", "404"]
sidebar:
badge: "GET"
---
`SummarizeFeedback` queries [[service|rating-api]] (`GET /rating/api/v1/feedbacks/{id}/summarize`) to return a synthesized summary, application-computed rating metrics, classification, supporting evidence, and confidence for a book's customer feedback. The operation is read-only, requires Microsoft Entra ID authentication, and caches results.
## Overview
| Property | Value |
| :--------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context** | Reviews |
| **Owner Service** | [[service\|rating-api]] |
| **Protocol / Format** | HTTP `GET`, `application/json` response |
| **Gateway Endpoint** | `GET /rating/api/v1/feedbacks/{id}/summarize` (service path `/api/v1/feedbacks/{id}/summarize`) |
| **Authentication & Authorization** | Microsoft Entra ID JWT required |
| **Idempotency / Concurrency** | Read-only and naturally idempotent |
| **Rate Limit / Caching** | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` limit, `20` per `10s`, queue `5`); cached `6 hours` when `reviewCount > 0`, `1 minute` when `reviewCount == 0` |
| **Contract Version** | `1.0.0` (`ApiVersions.V1`) |
:::note
A book with zero feedback records returns `200 OK` with `"classification": "NoData"` and does **not** invoke the AI model workflow. Do not treat `404 Not Found` or `5xx` errors as equivalent to `NoData`.
:::
## Request & Response Contract
### Path Parameters
| Name | Type | Required | Constraints | Description |
| :--- | :---------------- | :------- | :---------- | :------------------------------------------------- |
| `id` | `string` (`uuid`) | Yes | Valid UUID | Unique identifier of the Catalog book to summarize |
### Success Response (`200 OK`)
Only `summary` is strictly required in the schema; clients should handle remaining fields defensively.
| Name | Type | Required | Constraints | Description |
| :--------------- | :--------------- | :------- | :---------------------------------------- | :------------------------------------------------------------------------------------------------------------------ |
| `summary` | `string` | Yes | Non-null | Generated narrative summary of customer feedback, or `"No feedback found for this book."` when `reviewCount` is `0` |
| `classification` | `string` | No | Enum: `NoData`, `Bad`, `Good`, `TopRated` | Application-derived classification computed by deterministic business rules |
| `averageRating` | `number \| null` | No | `double` or `null` | Arithmetic mean rating across included feedback records (`null` when `reviewCount` is `0`) |
| `reviewCount` | `integer` | No | `int32` | Number of feedback records included in the summary (`0` when unreviewed) |
| `evidence` | `string` | No | — | Supporting evidence produced by the quality assessment step (empty string when `reviewCount` is `0`) |
| `confidence` | `string` | No | Free-form string | Confidence reported by the quality assessment step (empty string when `reviewCount` is `0`) |
## Behavior & Side Effects
- **AI summarization & PII redaction:** When feedback exists, invokes the map-reduce-assess AI workflow with [[service|presidio-api]] PII redaction before generating the summary.
- **Deterministic classification:** Returns `NoData` when fewer than 3 reviews exist (or average is invalid), `Bad` when average `< 3.5` or a dominant negative pattern is found, `TopRated` at average `>= 4.5` with `50+` reviews or `>= 4.0` with `200+` reviews, and `Good` otherwise.
- **Tiered caching:** Caches non-empty summaries for 6 hours and empty (`NoData`) results for 1 minute; invalidated on feedback mutations.
## Error Responses
| Status / Code | Condition | Client Recovery Action |
| :-------------------------- | :------------------------------------------------------------- | :--------------------------------------------------------------- |
| `401 Unauthorized` | Missing, expired, or invalid Entra ID bearer token | Re-authenticate and retry |
| `403 Forbidden` | Authenticated principal lacks Rating API authorization | Request a token with the required Rating API scopes |
| `404 Not Found` | Target resource or summary could not be found | Surface an unavailable/not-found state; do not treat as `NoData` |
| `429 Too Many Requests` | Rate limit quota exceeded (`Retry-After` header included) | Wait for the `Retry-After` duration before retrying |
| `500 Internal Server Error` | Downstream AI, [[service\|presidio-api]], or Cosmos DB failure | Retry with exponential backoff; do not fall back to `NoData` |
## Related Documentation
- [[service|rating-api]] — Service overview, Azure Cosmos DB storage, and AI governance.
- [[service|presidio-api]] — PII detection and anonymization service.
- [[entity|feedback]] — Feedback document model.
- [[query|ListFeedbacks]] — Retrieve paginated individual customer reviews for a book.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "SummarizeResult",
"description": "Generated summary of feedback for a book.",
"type": "object",
"required": ["summary"],
"properties": {
"summary": {
"type": "string",
"description": "Generated summary of the book's feedback."
},
"classification": {
"type": "string",
"enum": ["NoData", "Bad", "Good", "TopRated"],
"description": "Application-derived feedback classification."
},
"averageRating": {
"type": ["number", "null"],
"format": "double",
"description": "Arithmetic mean rating; null when no feedback exists."
},
"reviewCount": {
"type": "integer",
"format": "int32",
"description": "Number of feedback records included in the summary."
},
"evidence": {
"type": "string",
"description": "Supporting evidence from the feedback assessment."
},
"confidence": {
"type": "string",
"description": "Assessment confidence; empty when no feedback exists."
}
}
}
---
id: book-agent
name: Book Agent
version: 1.0.0
summary: Primary conversational book discovery and recommendation specialist that grounds catalog answers in read-only MCP lookups and delegated research while never mutating orders, baskets, or reviews.
owners:
- ai-capabilities-team
repository:
language: C#
url: https://github.com/foxminchan/BookWorm
sends:
- id: AnalyzeText
version: 1.0.0
- id: AnonymizeText
version: 1.0.0
flows:
- id: agent-orchestration
version: 1.0.0
tools:
- name: search_catalog
type: mcp
icon: /icons/languages/dotnet.svg
description: Searches the book catalog by keyword or semantic description.
- name: get_book
type: mcp
icon: /icons/languages/dotnet.svg
description: Retrieves full catalog details for a known book identifier.
- name: list_categories
type: mcp
icon: /icons/languages/dotnet.svg
description: Lists all available book categories in the catalog.
- name: list_authors
type: mcp
icon: /icons/languages/dotnet.svg
description: Lists authors available in the catalog.
- name: Book Catalog Researcher
type: subagent
icon: /icons/languages/dotnet.svg
description: Delegates multi-part factual catalog lookups to the Book Catalog Researcher subagent.
- name: Book Recommendation Researcher
type: subagent
icon: /icons/languages/dotnet.svg
description: Delegates preference-based shortlist discovery to the Book Recommendation Researcher subagent.
- name: handoff_to_rating
type: handoff
icon: /icons/languages/dotnet.svg
description: Transfers review summary and rating quality requests to the Rating Agent over A2A gRPC after resolving an exact book ID.
- name: handoff_to_qa
type: handoff
icon: /icons/languages/dotnet.svg
description: Transfers store policy, shipping, returns, account, order, or billing inquiries to the QA Agent.
badges:
- content: AI Agent
backgroundColor: purple
textColor: purple
model:
provider: Microsoft
name: model-router
version: "2025-11-18"
---
## Role & Autonomy Boundary
Book Agent is the primary conversational book discovery and recommendation specialist hosted in [[service|chat-api]]. It is triggered when the intent router inside [[flow|agent-orchestration]] classifies an authenticated customer chat turn as a book discovery, catalog lookup, or recommendation request, or when [[agent|qa-agent]] hands off a book-specific follow-up.
Book Agent operates strictly within a **read-only discovery boundary**: it must never place orders, mutate baskets, publish or edit reviews, bypass caller authorization, or invent unverified catalog facts such as prices, availability, or ratings.
## Agent Profile & Model Governance
| Property | Value |
| :--------------------------- | :------------------------------------------------------------------------------------------------------------------------------------ |
| **Bounded Context / Domain** | Conversational ([[domain\|bookworm]]) |
| **Owner Team** | [[team\|ai-capabilities-team]] |
| **Hosting Service** | [[service\|chat-api]] |
| **LLM Provider & Model** | Microsoft Foundry `model-router` (`2025-11-18`; `temperature: 0.7`, `maxOutputTokens: 2000`, `reasoningEffort: high`) |
| **Interaction Protocol** | Streaming AG-UI over HTTP (inbound); MCP Streamable HTTP (outbound to [[service\|mcp-server]]); A2A gRPC (handoff to reviews) |
| **Memory / Context Scope** | Durable AG-UI session state in [[container\|chat-session-blob]], user-scoped reading preference memory, and local planning/file state |
| **Fallback Behavior** | Falls back to Markdown responses if storefront UI tools are absent; fails closed on PII screening or policy denial |
## Tools & Capabilities
| Capability / Tool | Access Level | Target Resource | Guardrail / Constraint |
| :------------------------------------------------------------------ | :----------- | :--------------------------------------------- | :------------------------------------------------------------------------------------------- |
| `search_catalog`, `get_book`, `list_categories`, `list_authors` | Read | [[service\|mcp-server]] | Governed by default-deny policy; executes with On-Behalf-Of (OBO) caller identity |
| `Book Catalog Researcher` | Delegate | [[agent\|book-catalog-researcher]] | Invoked only for multi-part factual lookups; inherits parent PII and guardrail middleware |
| `Book Recommendation Researcher` | Delegate | [[agent\|book-recommendation-researcher]] | Invoked in parallel for preference-based shortlists; inherits parent middleware |
| `handoff_to_rating` | Delegate | [[agent\|rating-agent]] | Permitted only after resolving a single exact book identifier and title |
| `handoff_to_qa` | Delegate | [[agent\|qa-agent]] | Transfers store policy, shipping, returns, account, order, or billing questions |
| Planning & skill harness (`load_skill`, `todos_*`, `mode_*`) | Read / Write | Scoped session planning & `book-catalog` skill | Multi-step plans pause in Plan Mode for user approval before switching to Execute Mode |
| Storefront UI tools (`showBookCard`, `showBookList`, `addToBasket`) | Delegate | Storefront AG-UI client | Emitted only when advertised by the client; cart actions execute client-side under user auth |
## Data, Messaging & Handoff Boundaries
- **Data Stores:** Book Agent does not read or write relational or document domain databases directly. Durable conversation transcripts are managed by [[service|chat-api]] in [[container|chat-session-blob]], while user reading preferences and scratchpad planning files remain isolated from business domain stores.
- **Messages:** Every input prompt and buffered streaming output is screened via [[service|presidio-api]] using [[command|AnalyzeText]] and [[command|AnonymizeText]].
- **Delegation & Handoffs:** Complex multi-constraint queries fan out in parallel to [[agent|book-catalog-researcher]] and [[agent|book-recommendation-researcher]]. Review quality questions hand off over A2A gRPC to [[agent|rating-agent]], and operational support questions hand off in-process to [[agent|qa-agent]].
The orchestrator validates the prompt, injects live storefront context, and filters candidate tools using the decision model before invoking Book Agent.
For multi-part queries, Book Agent delegates factual verification to [[agent|book-catalog-researcher]] and preference matching to [[agent|book-recommendation-researcher]] concurrently.
Book Agent merges verified catalog identifiers into structured storefront UI cards or Markdown, or hands off to [[agent|rating-agent]] or [[agent|qa-agent]] when the intent crosses specialist boundaries.
## Safety, Privacy & AI Governance
- **Fail-Closed PII Redaction:** Input and buffered streaming output pass through [[service|presidio-api]] (`AnalyzeText` followed by `AnonymizeText`, replacing detected entities with ``). Any screening failure aborts the turn.
- **Default-Deny Tool Governance:** Only explicitly allow-listed tools for Book Agent's workload identity can execute; unapproved tools and cross-domain mutations are blocked by policy.
- **Conversation Guardian & Loop Protection:** Enforces a maximum of `30` conversation turns, caps retry cycles at `3`, and screens for multi-turn prompt injection and escalating or offensive rhetoric.
- **Context Compaction & Observability:** Applies full conversation compaction before model context limits are reached and emits OpenTelemetry traces correlated to the caller's session.
Book Agent must never claim a book is in stock, quote unverified prices, or fabricate ratings. All
product claims must originate from live [[service|mcp-server]] responses, and review quality
analysis must be handed off to [[agent|rating-agent]] only after resolving a single exact book ID.
- **Absent UI Tools:** When storefront interactive card tools are not advertised in the client context, Book Agent falls back to structured Markdown links and summaries.
- **Ambiguous Intent:** Low-confidence routing pauses for human-in-the-loop disambiguation before Book Agent is invoked.
- **Evaluation:** Verified against deterministic tool allow/deny tests, adversarial multi-turn prompt-injection suites, and Presidio fail-closed fault injection.
## Architecture Visualizations
**Agent Orchestration and Tool Boundary**
## Related Documentation
- [[service|chat-api]] — Hosting AG-UI server, workflow orchestration, and Entra ID authorization.
- [[flow|agent-orchestration]] — End-to-end conversational routing, disambiguation, and handoff flow.
- [[agent|book-catalog-researcher]] — Delegated subagent for factual catalog lookups.
- [[agent|book-recommendation-researcher]] — Delegated subagent for preference-based shortlists.
- [[agent|qa-agent]] — Peer specialist handling store policy and support handoffs.
- [[agent|rating-agent]] — Remote A2A specialist handling review and rating handoffs.
- [[container|chat-session-blob]] — Durable AG-UI session storage managed by [[service|chat-api]].
- [[doc|arc42/08-crosscutting-concepts/005-ai-governance]] — Cross-cutting AI governance rules and standards.
- [[adr|adr-bw-014-composable-ai-governance]] — Shared governance composition across AI paths.
- [[adr|adr-002-fail-closed-pii-middleware]] — Fail-closed PII screening decision.
- [[adr|adr-005-govern-agent-tools-per-agent]] — Per-agent default-deny tool governance.
---
id: book-catalog-researcher
name: Book Catalog Researcher
version: 1.0.0
summary: Internal delegated subagent that performs low-temperature factual catalog lookups for the Book Agent and never communicates directly with customers or mutates state.
owners:
- ai-capabilities-team
repository:
language: C#
url: https://github.com/foxminchan/BookWorm
sends:
- id: AnalyzeText
version: 1.0.0
- id: AnonymizeText
version: 1.0.0
flows:
- id: agent-orchestration
version: 1.0.0
tools:
- name: search_catalog
type: mcp
icon: /icons/languages/dotnet.svg
description: Searches the book catalog by keyword or description.
- name: get_book
type: mcp
icon: /icons/languages/dotnet.svg
description: Retrieves full catalog details for a known book identifier.
- name: list_categories
type: mcp
icon: /icons/languages/dotnet.svg
description: Lists available book categories in the catalog.
- name: list_authors
type: mcp
icon: /icons/languages/dotnet.svg
description: Lists authors available in the catalog.
badges:
- content: Delegated Subagent
backgroundColor: teal
textColor: teal
model:
provider: Microsoft
name: model-router
version: "2025-11-18"
---
## Role & Autonomy Boundary
Book Catalog Researcher is an internal delegated subagent hosted inside [[service|chat-api]] and invoked exclusively by [[agent|book-agent]]. It is triggered when a multi-part customer inquiry requires dedicated factual catalog verification in parallel with preference-based recommendation research.
It has **no external user-facing surface**: it cannot be routed to directly by the workflow orchestrator, cannot initiate handoffs to peer agents, cannot access planning or file memory, and must never fabricate titles, prices, availability, or ratings.
## Agent Profile & Model Governance
| Property | Value |
| :--------------------------- | :----------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context / Domain** | Conversational ([[domain\|bookworm]]) |
| **Owner Team** | [[team\|ai-capabilities-team]] |
| **Hosting Service** | [[service\|chat-api]] (internal subagent of [[agent\|book-agent]]) |
| **LLM Provider & Model** | Microsoft Foundry `model-router` (`2025-11-18`; `temperature: 0.2`, `maxOutputTokens: 1200`, `reasoningEffort: medium`) |
| **Interaction Protocol** | In-process subagent delegation (inbound from [[agent\|book-agent]]); MCP Streamable HTTP (outbound to [[service\|mcp-server]]) |
| **Memory / Context Scope** | Ephemeral per-delegation turn; inherits active run context from [[agent\|book-agent]] with no independent storage |
| **Fallback Behavior** | Returns explicit unverified/not-found status to [[agent\|book-agent]]; fails closed on PII or policy errors |
## Tools & Capabilities
| Capability / Tool | Access Level | Target Resource | Guardrail / Constraint |
| :-------------------------------------------------------------- | :----------- | :---------------------- | :------------------------------------------------------------------------------------------- |
| `search_catalog`, `get_book`, `list_categories`, `list_authors` | Read | [[service\|mcp-server]] | Default-deny policy permits only these four read-only catalog tools; no mutation tools exist |
## Data, Messaging & Handoff Boundaries
- **Data Stores:** Book Catalog Researcher has no direct database, cache, or blob storage access. All catalog facts are retrieved exclusively through [[service|mcp-server]].
- **Messages:** Inherits [[agent|book-agent]]'s privacy pipeline, screening all inputs and outputs via [[service|presidio-api]] using [[command|AnalyzeText]] and [[command|AnonymizeText]].
- **Delegation & Handoffs:** Receives subagent tasks solely from [[agent|book-agent]] and returns concise findings with verified book identifiers. It has no handoff tools and never delegates further.
## Safety, Privacy & AI Governance
- **Inherited Fail-Closed PII Redaction:** Every model invocation runs through [[service|presidio-api]] (`AnalyzeText` and `AnonymizeText`, masking detected PII with ``); any failure aborts execution.
- **Strict Least-Privilege Policy:** Default-deny governance permits only agent execution and the four read-only catalog tools—no handoff, planning, file-memory, or storefront UI tools are granted.
- **Deterministic Grounding:** Configured with low temperature (`0.2`) and `1200` max output tokens to favor exact, concise catalog reporting over creative elaboration.
- **Prompt & Output Guardrails:** Inherits decision-based tool filtering, prompt/output safety guardrails, and full context compaction from [[agent|book-agent]].
Book Catalog Researcher must treat catalog tool outputs as its sole factual source. It must never
extrapolate stock levels, prices, or bibliographic details beyond what [[service|mcp-server]]
returns.
- **Empty or Partial Matches:** When catalog queries return no matching books, the subagent reports the exact gap to [[agent|book-agent]] rather than substituting unverified titles.
- **Evaluation:** Tested for strict tool-scope isolation (denying non-catalog tools), deterministic fact extraction, and inherited Presidio PII redaction.
## Architecture Visualizations
**Subagent Delegation and Catalog Lookup Boundary**
## Related Documentation
- [[agent|book-agent]] — Parent coordinating agent and full governance specification.
- [[agent|book-recommendation-researcher]] — Sibling delegated subagent for preference-based shortlists.
- [[service|mcp-server]] — Read-only Catalog MCP server exposing the four catalog tools.
- [[service|chat-api]] — Hosting service and workflow orchestration.
- [[flow|agent-orchestration]] — End-to-end conversational routing and delegation flow.
- [[doc|arc42/08-crosscutting-concepts/005-ai-governance]] — Cross-cutting AI governance rules and standards.
- [[adr|adr-005-govern-agent-tools-per-agent]] — Per-agent default-deny tool governance.
---
id: book-recommendation-researcher
name: Book Recommendation Researcher
version: 1.0.0
summary: Internal delegated subagent that curates catalog-verified book shortlists matching customer preferences for the Book Agent without inferring demographics or inventing facts.
owners:
- ai-capabilities-team
repository:
language: C#
url: https://github.com/foxminchan/BookWorm
sends:
- id: AnalyzeText
version: 1.0.0
- id: AnonymizeText
version: 1.0.0
flows:
- id: agent-orchestration
version: 1.0.0
tools:
- name: search_catalog
type: mcp
icon: /icons/languages/dotnet.svg
description: Searches the book catalog by theme, keyword, or description.
- name: get_book
type: mcp
icon: /icons/languages/dotnet.svg
description: Retrieves full catalog details for a candidate book identifier.
- name: list_categories
type: mcp
icon: /icons/languages/dotnet.svg
description: Lists available book categories in the catalog.
- name: list_authors
type: mcp
icon: /icons/languages/dotnet.svg
description: Lists authors available in the catalog.
badges:
- content: Delegated Subagent
backgroundColor: teal
textColor: teal
model:
provider: Microsoft
name: model-router
version: "2025-11-18"
---
## Role & Autonomy Boundary
Book Recommendation Researcher is an internal delegated subagent hosted inside [[service|chat-api]] and invoked exclusively by [[agent|book-agent]]. It is triggered when an open-ended customer request benefits from curating a preference-matched shortlist in parallel with factual catalog lookups.
It has **no external user-facing surface**: it cannot be routed to directly by the workflow orchestrator, cannot initiate handoffs to peer agents, cannot access planning or file memory, and must never infer customer demographics or fabricate availability, popularity, ratings, or prices.
## Agent Profile & Model Governance
| Property | Value |
| :--------------------------- | :----------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context / Domain** | Conversational ([[domain\|bookworm]]) |
| **Owner Team** | [[team\|ai-capabilities-team]] |
| **Hosting Service** | [[service\|chat-api]] (internal subagent of [[agent\|book-agent]]) |
| **LLM Provider & Model** | Microsoft Foundry `model-router` (`2025-11-18`; `temperature: 0.4`, `maxOutputTokens: 1200`, `reasoningEffort: medium`) |
| **Interaction Protocol** | In-process subagent delegation (inbound from [[agent\|book-agent]]); MCP Streamable HTTP (outbound to [[service\|mcp-server]]) |
| **Memory / Context Scope** | Ephemeral per-delegation turn; inherits active run context from [[agent\|book-agent]] with no independent storage |
| **Fallback Behavior** | Returns a smaller verified shortlist or explicit no-match report; fails closed on PII or policy errors |
## Tools & Capabilities
| Capability / Tool | Access Level | Target Resource | Guardrail / Constraint |
| :-------------------------------------------------------------- | :----------- | :---------------------- | :------------------------------------------------------------------------------------------- |
| `search_catalog`, `get_book`, `list_categories`, `list_authors` | Read | [[service\|mcp-server]] | Default-deny policy permits only these four read-only catalog tools; no mutation tools exist |
## Data, Messaging & Handoff Boundaries
- **Data Stores:** Book Recommendation Researcher has no direct database, cache, or blob storage access. Every candidate book in a shortlist must be verified through [[service|mcp-server]].
- **Messages:** Inherits [[agent|book-agent]]'s privacy pipeline, screening all inputs and outputs via [[service|presidio-api]] using [[command|AnalyzeText]] and [[command|AnonymizeText]].
- **Delegation & Handoffs:** Receives subagent tasks solely from [[agent|book-agent]] and returns an evidence-backed shortlist with verified book identifiers. It has no handoff tools and never delegates further.
## Safety, Privacy & AI Governance
- **Inherited Fail-Closed PII Redaction:** Every model invocation runs through [[service|presidio-api]] (`AnalyzeText` and `AnonymizeText`, masking detected PII with ``); any failure aborts execution.
- **Fairness & Grounding Invariants:** Prohibits demographic inference or stereotyping; every recommendation must cite explicit catalog attributes returned by [[service|mcp-server]].
- **Strict Least-Privilege Policy:** Default-deny governance permits only agent execution and the four read-only catalog tools—no handoff, planning, file-memory, or storefront UI tools are granted.
- **Prompt & Output Guardrails:** Inherits decision-based tool filtering, prompt/output safety guardrails, and full context compaction from [[agent|book-agent]].
Book Recommendation Researcher must never recommend titles that were not retrieved and verified
through [[service|mcp-server]] during the current run, and must never infer protected or
demographic attributes about the customer.
- **Insufficient Matches:** If few or no catalog titles match all stated constraints, the subagent returns only verified partial matches with explicit caveats to [[agent|book-agent]].
- **Evaluation:** Verified for catalog-grounding fidelity (zero hallucinated ISBNs/IDs), fairness constraints, tool-scope isolation, and Presidio PII redaction.
## Architecture Visualizations
**Subagent Delegation and Preference Matching Boundary**
## Related Documentation
- [[agent|book-agent]] — Parent coordinating agent and full governance specification.
- [[agent|book-catalog-researcher]] — Sibling delegated subagent for factual catalog lookups.
- [[service|mcp-server]] — Read-only Catalog MCP server exposing the four catalog tools.
- [[service|chat-api]] — Hosting service and workflow orchestration.
- [[flow|agent-orchestration]] — End-to-end conversational routing and delegation flow.
- [[doc|arc42/08-crosscutting-concepts/005-ai-governance]] — Cross-cutting AI governance rules and standards.
- [[adr|adr-005-govern-agent-tools-per-agent]] — Per-agent default-deny tool governance.
---
id: qa-agent
name: QA Agent
version: 1.0.0
summary: Read-only customer support and store-policy specialist that answers operational, shipping, returns, account, and billing questions without accessing live order data or mutating records.
owners:
- ai-capabilities-team
repository:
language: C#
url: https://github.com/foxminchan/BookWorm
sends:
- id: AnalyzeText
version: 1.0.0
- id: AnonymizeText
version: 1.0.0
flows:
- id: agent-orchestration
version: 1.0.0
tools:
- name: load_skill
type: function
icon: /icons/languages/dotnet.svg
description: Loads curated store-policy guidance from the store-policies skill context.
- name: read_skill_resource
type: function
icon: /icons/languages/dotnet.svg
description: Reads specific policy reference sections within the store-policies skill.
- name: handoff_to_book
type: handoff
icon: /icons/languages/dotnet.svg
description: Transfers book discovery, catalog, or recommendation follow-ups to the Book Agent.
badges:
- content: AI Agent
backgroundColor: purple
textColor: purple
model:
provider: Microsoft
name: model-router
version: "2025-11-18"
---
## Role & Autonomy Boundary
QA Agent is the read-only customer support and store-policy specialist hosted in [[service|chat-api]]. It is triggered either when the intent router inside [[flow|agent-orchestration]] classifies a customer prompt as an operational, policy, shipping, returns, account, or billing inquiry, or when [[agent|book-agent]] hands off a non-book support question.
QA Agent has **no database access, no MCP catalog client, and no account or order mutation capabilities**: it provides policy guidance only, cannot look up or modify live orders, and must never invent policy terms or prices.
## Agent Profile & Model Governance
| Property | Value |
| :--------------------------- | :------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context / Domain** | Conversational ([[domain\|bookworm]]) |
| **Owner Team** | [[team\|ai-capabilities-team]] |
| **Hosting Service** | [[service\|chat-api]] |
| **LLM Provider & Model** | Microsoft Foundry `model-router` (`2025-11-18`; `temperature: 0.5`, `maxOutputTokens: 1000`, `reasoningEffort: medium`) |
| **Interaction Protocol** | Streaming AG-UI over HTTP (inbound); in-process handoff (outbound to [[agent\|book-agent]]) |
| **Memory / Context Scope** | Durable AG-UI session state in [[container\|chat-session-blob]] with lightweight history compaction and `store-policies` skill context |
| **Fallback Behavior** | States explicitly when a policy detail is unavailable and directs the customer to support; fails closed on PII errors |
## Tools & Capabilities
| Capability / Tool | Access Level | Target Resource | Guardrail / Constraint |
| :------------------------------------- | :----------- | :---------------------- | :----------------------------------------------------------------------------------------- |
| `load_skill`, `read_skill_resource` | Read | `store-policies` skill | Scoped exclusively to curated store-policy guidance; cannot read arbitrary files or stores |
| `handoff_to_book` | Delegate | [[agent\|book-agent]] | Transfers book discovery or recommendation follow-ups back to Book Agent |
| Catalog tools (`search_catalog`, etc.) | Denied | [[service\|mcp-server]] | Explicitly denied at priority `70` as defense-in-depth |
## Data, Messaging & Handoff Boundaries
- **Data Stores:** QA Agent reads no business databases, caches, or external APIs. Conversation sessions are persisted by [[service|chat-api]] in [[container|chat-session-blob]].
- **Messages:** Every input prompt and buffered streaming output is screened via [[service|presidio-api]] using [[command|AnalyzeText]] and [[command|AnonymizeText]].
- **Delegation & Handoffs:** Receives routed support turns or handoffs from [[agent|book-agent]], and hands book-specific follow-ups back to [[agent|book-agent]] via `handoff_to_book`. It never calls [[agent|rating-agent]] directly.
## Safety, Privacy & AI Governance
- **Fail-Closed PII Redaction:** Input and buffered streaming output pass through [[service|presidio-api]] (`AnalyzeText` followed by `AnonymizeText`, replacing detected entities with ``). Any failure aborts the turn.
- **Defense-in-Depth Tool Denial:** Default-deny governance permits only skill loading and `handoff_to_book`, while an explicit high-priority deny rule blocks all catalog MCP tools.
- **Topic & Fairness Guardrails:** Covers shipping, delivery, returns, refunds, account/order guidance, store policies, and services (gift cards, loyalty, wishlists, pre-orders). Never tailors policy answers based on inferred personal characteristics.
- **Conversation Guardian:** Monitors for escalating rhetoric, offensive patterns, handoff loops (`max_conversation_turns: 30`), and multi-turn prompt injection.
QA Agent must never fabricate store policies, refund timelines, or account statuses, and cannot
inspect or modify live customer orders. When a policy detail is missing from its skill context, it
must state the gap clearly and direct the customer to the official support channel.
- **Missing Policy Detail:** Explicitly informs the customer that the requested detail is unavailable rather than guessing.
- **Out-of-Scope Book Query:** Hands off to [[agent|book-agent]] instead of attempting to answer catalog questions from memory.
- **Evaluation:** Verified against explicit catalog-tool denial tests, missing-policy refusal accuracy, handoff-loop bounds, and Presidio fail-closed fault injection.
## Architecture Visualizations
**Support Routing, Policy Skill, and Handoff Boundary**
## Related Documentation
- [[service|chat-api]] — Hosting AG-UI server, workflow orchestration, and intent routing.
- [[flow|agent-orchestration]] — End-to-end conversational routing, disambiguation, and handoff flow.
- [[agent|book-agent]] — Peer specialist for book discovery handoffs.
- [[service|presidio-api]] — PII analysis and anonymization sidecars invoked by middleware.
- [[doc|arc42/08-crosscutting-concepts/005-ai-governance]] — Cross-cutting AI governance rules and standards.
- [[adr|adr-bw-014-composable-ai-governance]] — Shared governance composition across AI paths.
- [[adr|adr-002-fail-closed-pii-middleware]] — Fail-closed PII screening decision.
- [[adr|adr-005-govern-agent-tools-per-agent]] — Per-agent default-deny tool governance.
---
id: rating-agent
name: Rating Agent
version: 1.0.0
summary: Read-only review intelligence specialist that summarizes customer feedback over A2A gRPC and map-reduce workflows while leaving final quality tier classification to deterministic service logic.
owners:
- catalog-experience-team
repository:
language: C#
url: https://github.com/foxminchan/BookWorm
tools:
- name: GetCustomerReviews
type: function
icon: /icons/languages/dotnet.svg
description: Read-only in-process lookup returning raw customer reviews (review ID, rating, comment) for a book; rate-limited to 30 calls per minute.
- name: get_book
type: mcp
icon: /icons/languages/dotnet.svg
description: Retrieves catalog book metadata (title, authors, category, price, average rating, total reviews) from the MCP Server before fetching reviews.
sends:
- id: AnalyzeText
version: 1.0.0
- id: AnonymizeText
version: 1.0.0
readsFrom:
- id: rating-database
version: 1.0.0
flows:
- id: agent-orchestration
version: 1.0.0
badges:
- content: AI Agent
backgroundColor: purple
textColor: purple
model:
provider: Microsoft
name: model-router
version: "2025-11-18"
---
## Role & Autonomy Boundary
Rating Agent is the read-only review analysis and quality-signal specialist hosted inside [[service|rating-api]] in the Reviews bounded context. It is triggered through two runtime paths: remote Agent-to-Agent (A2A) gRPC handoffs from [[service|chat-api]] (routed or handed off from [[agent|book-agent]]), and [[service|rating-api]]'s in-process map-reduce summarization pipeline backing [[query|SummarizeFeedback]].
Rating Agent **never writes to [[container|rating-database]] or [[container|catalog-database]]**, never executes destructive queries, and never assigns final quality tiers—classifications (`No Data`, `Bad`, `Good`, `Top Rated`) are computed deterministically by service code rather than the language model.
## Agent Profile & Model Governance
| Property | Value |
| :--------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context / Domain** | Reviews ([[domain\|bookworm]]) |
| **Owner Team** | [[team\|catalog-experience-team]], [[team\|catalog-experience-team]] |
| **Hosting Service** | [[service\|rating-api]] |
| **LLM Provider & Model** | Microsoft Foundry `model-router` (`2025-11-18`; `temperature: 0.4`, `maxOutputTokens: 1500`, `reasoningEffort: medium`) |
| **Interaction Protocol** | Remote A2A gRPC server (`rating_read` policy, Entra Agent Identity); in-process workflow invocation; MCP Streamable HTTP (outbound to [[service\|mcp-server]]) |
| **Memory / Context Scope** | Stateless per-request with four-stage context compaction; summarized results cached by [[service\|rating-api]] in [[container\|rating-cache]] |
| **Fallback Behavior** | Re-runs reduction up to configured iteration limits when confidence is low; fails closed on PII or write-policy violations |
## Tools & Capabilities
| Capability / Tool | Access Level | Target Resource | Guardrail / Constraint |
| :------------------- | :----------- | :----------------------------- | :--------------------------------------------------------------------------------------- |
| `GetCustomerReviews` | Read | [[container\|rating-database]] | Read-only partition query; rate-limited to `30/minute` by governance policy |
| `get_book` | Read | [[service\|mcp-server]] | Always invoked before `GetCustomerReviews` to refresh catalog metadata and review counts |
## Data, Messaging & Handoff Boundaries
- **Data Stores:** Read-only consumer of [[container|rating-database]] via `GetCustomerReviews`. Generated summaries and quality signals are never persisted back to [[container|rating-database]] by the agent; [[service|rating-api]] caches [[query|SummarizeFeedback]] outputs in [[container|rating-cache]].
- **Messages:** Screens all inputs and outputs via [[service|presidio-api]] using [[command|AnalyzeText]] and [[command|AnonymizeText]]. Stored customer reviews in [[container|rating-database]] remain unmodified.
- **Delegation & Handoffs:** Receives remote A2A gRPC requests from [[service|chat-api]] (typically handed off by [[agent|book-agent]] after resolving a single book identifier). It never calls [[service|chat-api]] or peer conversational agents.
For [[query|SummarizeFeedback]], the summarization workflow partitions customer reviews into bounded batches and fans out parallel structured summarization calls to Rating Agent.
A reduce stage merges batch outputs into unified sentiment, recurring themes, strengths, weaknesses, and confidence-scored quality signals, repeating reduction if confidence falls below threshold.
Deterministic service logic evaluates review count, average rating, and dominant negative pattern flags to assign `No Data`, `Bad`, `Good`, or `Top Rated`—never delegated to the LLM.
## Safety, Privacy & AI Governance
- **Fail-Closed PII Redaction:** [[service|presidio-api]] (`AnalyzeText` and `AnonymizeText`) screens model inputs and outputs alongside regex PII patterns (`email`, `phone`, `credit_card`), ensuring reviewer personal details are masked before reaching the model or caller.
- **Default-Deny & Write Protection:** High-priority governance rules (`block-write-operations`, `block-destructive-sql`) block all mutations and non-`SELECT` SQL patterns, while capping `GetCustomerReviews` at `30/minute`.
- **Dual Output Guardrails:** Combines shared prompt/response guardrails with Rating-specific output checks across both buffered and streaming responses.
- **Four-Stage Context Compaction:** Applies tool-result compaction (`> 20` messages), LLM summarization (`> 3,000` tokens), sliding window (`> 12` turns), and hard truncation (`> 24,000` tokens) to prevent context overflow on large review sets.
Rating Agent is explicitly instructed never to emit a final quality classification or equate
review counts with sales volume. All write operations are denied by policy, and final quality
tiers are always computed deterministically outside the model.
| Classification | Condition |
| :------------- | :----------------------------------------------------------------------------------------------------- |
| **No Data** | Fewer than `3` reviews, or non-finite / out-of-range average rating |
| **Bad** | Average rating `< 3.5`, or a dominant negative pattern is detected |
| **Top Rated** | (`averageRating >= 4.5` and `reviewCount >= 50`) or (`averageRating >= 4.0` and `reviewCount >= 200`) |
| **Good** | Remaining books with `reviewCount >= 3` and `averageRating >= 3.5` without a dominant negative pattern |
- **Low-Confidence Refinement:** If parsed assessment confidence is below threshold, the workflow loops reduction up to its configured maximum iterations before deterministic classification.
## Architecture Visualizations
**Review Intelligence Invocation and Data Boundary**
## Related Documentation
- [[service|rating-api]] — Hosting service, [[query|SummarizeFeedback]] endpoint, and A2A gRPC server.
- [[container|rating-database]] — Authoritative Azure Cosmos DB feedback store.
- [[container|rating-cache]] — Caching layer for [[query|SummarizeFeedback]] results.
- [[agent|book-agent]] — Conversational specialist that resolves a book ID before A2A handoff.
- [[flow|agent-orchestration]] — Conversational workflow routing and A2A handoff flow.
- [[doc|arc42/08-crosscutting-concepts/005-ai-governance]] — Cross-cutting AI governance rules and standards.
- [[adr|adr-bw-014-composable-ai-governance]] — Shared governance composition across AI paths.
- [[adr|adr-004-read-only-governed-feedback-summarization]] — Read-only governed feedback summarization decision.
---
id: basket-api
name: Basket API
version: 1.0.0
summary: |
Internal HTTP and gRPC service for managing customer-scoped shopping baskets,
Catalog price enrichment, and post-checkout cleanup.
readsFrom:
- id: basket-database
version: 1.0.0
writesTo:
- id: basket-database
version: 1.0.0
entities:
- id: basket
version: 1.0.0
- id: basket-item
version: 1.0.0
owners:
- commerce-fulfillment-team
badges:
- content: Internal
backgroundColor: gray
textColor: gray
- content: HTTP + gRPC
backgroundColor: teal
textColor: teal
diagrams:
- id: checkout-interaction
version: 1.0.0
receives:
- id: CreateBasket
version: 1.0.0
group: Basket Commands
- id: UpdateBasket
version: 1.0.0
group: Basket Commands
- id: DeleteBasket
version: 1.0.0
group: Basket Commands
- id: GetBasket
version: 1.0.0
group: Basket Queries
- id: GetBasketGrpc
version: 1.0.0
group: Basket Queries
- id: PlaceOrderCommand
version: 1.0.0
from:
- id: bookworm.{env}.finance.place-order
version: 1.0.0
sends:
- id: GetBookGrpc
version: 1.0.0
group: Catalog Queries
- id: GetBooksGrpc
version: 1.0.0
group: Catalog Queries
- id: BasketDeletedCompleteIntegrationEvent
version: 1.0.0
group: Basket Cleanup Outcomes
to:
- id: bookworm.{env}.basket.delete-complete
- id: BasketDeletedFailedIntegrationEvent
version: 1.0.0
group: Basket Cleanup Outcomes
to:
- id: bookworm.{env}.basket.delete-failed
styles:
icon: /icons/languages/dotnet.svg
specifications:
- type: openapi
path: openapi-v1.yml
name: OpenAPI V1
- type: asyncapi
path: asyncapi-v1.yml
name: AsyncAPI V1
repository:
language: C#
url: "https://github.com/foxminchan/BookWorm"
---
## Service Responsibility & Boundary
Basket API owns transient, customer-scoped shopping [[entity|basket]] and [[entity|basket-item]] state within the [[domain|shopping]] domain. It exposes authenticated HTTP endpoints for the storefront, serves internal gRPC basket snapshots to [[service|order-api]] during checkout, enriches basket reads with live titles and prices from [[service|catalog-api]] over gRPC, and performs asynchronous post-checkout cleanup with [[service|order-orchestration]] over Kafka.
## Service Profile
| Property | Value |
| :---------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Bounded Context / Domain** | [[domain\|shopping]] |
| **Owner Team** | [[team\|commerce-fulfillment-team]] |
| **Runtime Style** | REST API, gRPC Server/Client, and Async Kafka Consumer/Producer |
| **Public / Gateway Exposure** | Yes via API Gateway (HTTP) and Internal Only (gRPC) |
| **Authentication & Authorization Policy** | Microsoft Entra ID JWT via [[system\|identity-provider]]; `customer` role with basket read/write scopes; basket owner derived strictly from token |
| **Owned Data Store(s)** | [[container\|basket-database]] (Redis key-value store, no SQL database) |
| **Key Resilience / Idempotency Pattern** | 24-hour message-ID idempotency guard, per-user rate limiting, and dead-letter routing on [[channel\|bookworm.{env}.basket.dead-letter-queue]] |
## Contracts & Data Ownership
Basket API stores only customer ID, book IDs, and positive quantities in [[container|basket-database]]. Basket updates replace the entire item collection rather than merging partial changes, and basket records are never used to reconstruct accepted orders.
:::note
On read, Basket API batches distinct book IDs into a single gRPC lookup against [[service|catalog-api]] to attach current titles, regular prices, and sale prices. If Catalog returns no match for a book ID, the item remains in the response without inventing metadata.
:::
:::warning
Both Basket API and [[service|notification-api]] consume [[command|PlaceOrderCommand]] on the same Kafka topic. When [[service|order-orchestration]] retries on timeout, both consumers receive the retry.
:::
## Architecture Visualizations & Specifications
### Basket API Context
### Service Interactions
### Owned Entities
## Attached Resources & Related Docs
- [[doc|platform/006-api-and-contracts]] — Consolidated HTTP, gRPC, and Kafka contract reference.
- [[container|basket-database]] — Redis key structure and durability characteristics.
- [[diagram|checkout-interaction]] — Interaction between Shopping, Ordering, and Finance.
- [[doc|domains/bookworm/subdomains/shopping/engineering/basket-api-contracts]] — Basket API contracts and boundaries.
- [[doc|domains/bookworm/subdomains/shopping/guides/checkout-lifecycle]] — Pre-order to checkout handoff guide.
## Raw Schema:openapi-v1.yml
openapi: 3.2.0
info:
title: Basket Service API
description: "Manages the lifecycle of customer shopping baskets, including adding and removing items, calculating totals, and handling checkout processes"
contact:
name: BookWorm Engineering
url: https://github.com/foxminchan
email: engineering@bookworm.com
license:
name: MIT
url: https://opensource.org/licenses/MIT
version: "1.0"
summary: A service responsible for managing customer shopping baskets
paths:
/api/v1/baskets:
put:
tags:
- Basket
summary: Update Basket
description: Update a basket by its unique identifier
operationId: UpdateBasketEndpoint
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/UpdateBasketCommand"
required: true
responses:
"204":
description: No Content
"400":
description: Bad Request
content:
application/problem+json:
schema:
$ref: "#/components/schemas/HttpValidationProblemDetails"
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
get:
tags:
- Basket
summary: Get Basket
description: Get a basket by user
operationId: GetBasketEndpoint
responses:
"200":
description: OK
content:
application/json:
schema:
$ref: "#/components/schemas/CustomerBasketDto"
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
delete:
tags:
- Basket
summary: Delete Basket
description: Delete a basket by its unique identifier
operationId: DeleteBasketEndpoint
responses:
"204":
description: No Content
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
post:
tags:
- Basket
summary: Create Basket
description: Create a new basket for a user
operationId: CreateBasketEndpoint
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/CreateBasketCommand"
required: true
responses:
"201":
description: Created
content:
application/json:
schema:
$ref: "#/components/schemas/CustomerId"
"400":
description: Bad Request
content:
application/problem+json:
schema:
$ref: "#/components/schemas/HttpValidationProblemDetails"
components:
schemas:
BasketItemDto:
required:
- id
- quantity
type: object
properties:
id:
type:
- "null"
- string
quantity:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int32
name:
type:
- "null"
- string
price:
pattern: "^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?$"
type:
- number
- string
format: double
default: 0
priceSale:
pattern: "^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?$"
type:
- "null"
- number
- string
format: double
BasketItemRequest:
required:
- id
- quantity
type: object
properties:
id:
type: string
quantity:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int32
CreateBasketCommand:
required:
- items
type: object
properties:
items:
type: array
items:
$ref: "#/components/schemas/BasketItemRequest"
CustomerBasketDto:
required:
- id
- items
type: object
properties:
id:
oneOf:
- type: "null"
- $ref: "#/components/schemas/CustomerId"
items:
type: array
items:
$ref: "#/components/schemas/BasketItemDto"
CustomerId:
type:
- "null"
- string
items:
type: string
HttpValidationProblemDetails:
type: object
properties:
type:
type:
- "null"
- string
title:
type:
- "null"
- string
status:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- "null"
- integer
- string
format: int32
detail:
type:
- "null"
- string
instance:
type:
- "null"
- string
errors:
type: object
additionalProperties:
type: array
items:
type: string
ProblemDetails:
type: object
properties:
type:
type:
- "null"
- string
title:
type:
- "null"
- string
status:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- "null"
- integer
- string
format: int32
detail:
type:
- "null"
- string
instance:
type:
- "null"
- string
UpdateBasketCommand:
required:
- items
type: object
properties:
items:
type: array
items:
$ref: "#/components/schemas/BasketItemRequest"
tags:
- name: Basket
## Raw Schema:asyncapi-v1.yml
asyncapi: 3.1.0
info:
title: Basket API integration events
version: 1.0.0
description: |
AsyncAPI contract for the Basket service's checkout cleanup events.
Basket publishes a success or failure outcome after attempting to delete
the submitted basket.
defaultContentType: application/cloudevents+json
channels:
basketDeleteComplete:
address: bookworm.{env}.basket.delete-complete
description: Basket publishes this event when checkout cleanup deletes the basket successfully.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
basketDeleteComplete:
$ref: "#/components/messages/BasketDeletedCompleteIntegrationEvent"
basketDeleteFailed:
address: bookworm.{env}.basket.delete-failed
description: Basket publishes this event when checkout cleanup cannot delete the basket.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
basketDeleteFailed:
$ref: "#/components/messages/BasketDeletedFailedIntegrationEvent"
operations:
sendBasketDeleteComplete:
action: send
channel:
$ref: "#/channels/basketDeleteComplete"
summary: Publish successful basket deletion
messages:
- $ref: "#/channels/basketDeleteComplete/messages/basketDeleteComplete"
sendBasketDeleteFailed:
action: send
channel:
$ref: "#/channels/basketDeleteFailed"
summary: Publish failed basket deletion
messages:
- $ref: "#/channels/basketDeleteFailed/messages/basketDeleteFailed"
components:
parameters:
env:
description: BookWorm deployment environment.
enum:
- development
- staging
- production
default: development
messages:
BasketDeletedCompleteIntegrationEvent:
name: BasketDeletedCompleteIntegrationEvent
title: Basket deletion completed
summary: The submitted basket was deleted successfully after checkout.
contentType: application/json
payload:
$ref: "#/components/schemas/BasketDeletedCompletePayload"
BasketDeletedFailedIntegrationEvent:
name: BasketDeletedFailedIntegrationEvent
title: Basket deletion failed
summary: The submitted basket could not be deleted after checkout.
contentType: application/json
payload:
$ref: "#/components/schemas/BasketDeletedFailedPayload"
schemas:
BasketDeletedCompletePayload:
type: object
additionalProperties: false
required:
- id
- creationDate
- orderId
- basketId
- totalMoney
properties:
id:
type: string
format: uuid
description: Unique identifier assigned by the integration-event building block.
creationDate:
type: string
format: date-time
description: UTC timestamp when the integration event was created.
orderId:
type: string
format: uuid
description: Identifier of the order whose submitted basket was deleted.
basketId:
type: string
format: uuid
description: Identifier of the basket deleted during checkout cleanup.
totalMoney:
type: number
format: double
description: Total purchase amount associated with the order.
BasketDeletedFailedPayload:
type: object
additionalProperties: false
required:
- id
- creationDate
- orderId
- basketId
- totalMoney
properties:
id:
type: string
format: uuid
description: Unique identifier assigned by the integration-event building block.
creationDate:
type: string
format: date-time
description: UTC timestamp when the integration event was created.
orderId:
type: string
format: uuid
description: Identifier of the order whose submitted basket could not be deleted.
basketId:
type: string
format: uuid
description: Identifier of the basket that could not be deleted.
email:
type:
- string
- "null"
format: email
description: Customer email used by downstream recovery or notification workflows.
totalMoney:
type: number
format: double
description: Total purchase amount associated with the order.
---
id: catalog-api
name: Catalog API
version: 1.0.0
summary: |
Internal HTTP and gRPC service for Catalog product management, hybrid
discovery, and authoritative book metadata.
writesTo:
- id: catalog-database
- id: catalog-cache
- id: catalog-blob
readsFrom:
- id: catalog-database
- id: catalog-cache
- id: catalog-blob
- id: catalog-vector
entities:
- id: book
version: 1.0.0
- id: author
version: 1.0.0
- id: category
version: 1.0.0
- id: publisher
version: 1.0.0
owners:
- catalog-experience-team
badges:
- content: Internal
backgroundColor: gray
textColor: gray
- content: HTTP + gRPC
backgroundColor: teal
textColor: teal
receives:
- id: CreatePublisher
version: 1.0.0
group: Publisher Management
- id: UpdatePublisher
version: 1.0.0
group: Publisher Management
- id: DeletePublisher
version: 1.0.0
group: Publisher Management
- id: CreateCategory
version: 1.0.0
group: Category Management
- id: UpdateCategory
version: 1.0.0
group: Category Management
- id: DeleteCategory
version: 1.0.0
group: Category Management
- id: CreateAuthor
version: 1.0.0
group: Author Management
- id: UpdateAuthor
version: 1.0.0
group: Author Management
- id: DeleteAuthor
version: 1.0.0
group: Author Management
- id: CreateBook
version: 1.0.0
group: Book Management
- id: UpdateBook
version: 1.0.0
group: Book Management
- id: DeleteBook
version: 1.0.0
group: Book Management
- id: ListPublishers
version: 1.0.0
group: Catalog Queries
- id: ListCategories
version: 1.0.0
group: Catalog Queries
- id: ListAuthors
version: 1.0.0
group: Catalog Queries
- id: GetBook
version: 1.0.0
group: Catalog Queries
- id: GetBookGrpc
version: 1.0.0
group: Catalog Queries
- id: GetBooksGrpc
version: 1.0.0
group: Catalog Queries
- id: GetDashboardGrpc
version: 1.0.0
group: Catalog Queries
- id: ListBooks
version: 1.0.0
group: Catalog Queries
- id: ListBooksGrpc
version: 1.0.0
group: Catalog Queries
- id: GetBookDetailsGrpc
version: 1.0.0
group: Catalog Queries
- id: ListCategoriesGrpc
version: 1.0.0
group: Catalog Queries
- id: ListAuthorsGrpc
version: 1.0.0
group: Catalog Queries
- id: FeedbackCreatedIntegrationEvent
version: 1.0.0
group: Feedback Projection
from:
- id: "bookworm.{env}.rating.feedback-create"
parameters:
env: development
- id: FeedbackDeletedIntegrationEvent
version: 1.0.0
group: Feedback Projection
from:
- id: "bookworm.{env}.rating.feedback-delete"
parameters:
env: development
sends:
- id: BookUpdatedRatingFailedIntegrationEvent
version: 1.0.0
to:
- id: "bookworm.{env}.catalog.book-update-rating-failed"
parameters:
env: development
styles:
icon: /icons/languages/dotnet.svg
specifications:
- type: openapi
path: openapi-v1.yml
name: OpenAPI V1
- type: asyncapi
path: asyncapi-v1.yml
name: AsyncAPI V1
repository:
language: C#
url: "https://github.com/foxminchan/BookWorm"
---
## Service Responsibility & Boundary
Catalog API is the system of record within the [[domain|catalog]] domain for [[entity|book]], [[entity|author]], [[entity|category]], and [[entity|publisher]] records, pricing, cover image references, and derived rating summaries. It serves versioned HTTP endpoints for storefront and backoffice workflows, exposes internal gRPC read contracts to peer services, and executes hybrid keyword-and-semantic search. Asynchronous vector index synchronization is delegated to [[service|catalog-ingestion]], while individual customer reviews remain owned by [[service|rating-api]].
## Service Profile
| Property | Value |
| :---------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context / Domain** | [[domain\|catalog]] |
| **Owner Team** | [[team\|catalog-experience-team]] |
| **Runtime Style** | REST API, gRPC Server, and Async Kafka Consumer/Producer |
| **Public / Gateway Exposure** | Yes via API Gateway (HTTP) and Internal Only (gRPC) |
| **Authentication & Authorization Policy** | Microsoft Entra ID JWT via [[system\|identity-provider]]; public catalog reads, `business_user` policy for catalog writes, and `admin` policy for dashboard gRPC |
| **Owned Data Store(s)** | [[container\|catalog-database]] (authoritative), [[container\|catalog-blob]] (cover media), [[container\|catalog-cache]] (read cache), [[container\|catalog-vector]] (read-only search index) |
| **Key Resilience / Idempotency Pattern** | Transactional outbox/inbox, soft-delete filtering, rate limiting, and dead-letter routing on [[channel\|bookworm.{env}.catalog.dead-letter-queue]] |
## Contracts & Data Ownership
Catalog API owns [[entity|book]], [[entity|author]], [[entity|category]], and [[entity|publisher]] in [[container|catalog-database]], stores cover image bytes in [[container|catalog-blob]], caches selected reads in [[container|catalog-cache]], and queries candidate book IDs from [[container|catalog-vector]] during semantic search.
:::note
Catalog writes trigger database-queued vector updates for [[service|catalog-ingestion]] rather than writing embeddings synchronously. Semantic search always resolves final book details and filters from [[container|catalog-database]] so stale index entries never expose outdated prices or deleted books.
:::
:::warning
When [[service|catalog-api]] consumes [[event|FeedbackCreatedIntegrationEvent]] for a missing book, it publishes [[event|BookUpdatedRatingFailedIntegrationEvent]] so [[service|rating-api]] can execute a compensating delete on the orphaned review.
:::
- **Internal gRPC consumers:** [[service|basket-api]], [[service|order-api]], and
[[service|mcp-server]] query book pricing, details, categories, authors, and dashboard counts over
gRPC. - **Kafka feedback projections:** Consumes [[event|FeedbackCreatedIntegrationEvent]] and
[[event|FeedbackDeletedIntegrationEvent]] from [[service|rating-api]] to maintain derived average
rating and review count projections.
## Architecture Visualizations & Specifications
### Catalog API Context
### Service Interactions
### Owned Entities
## Attached Resources & Related Docs
- [[doc|platform/006-api-and-contracts]] — Consolidated service, HTTP, gRPC, and Kafka directory.
- [[service|catalog-ingestion]] — Asynchronous vector-indexing worker.
- [[container|catalog-database]] — PostgreSQL schema, outbox, and vector queue triggers.
- [[container|catalog-cache]] — Redis read-caching strategy.
- [[container|catalog-vector]] — Vector search collection details.
- [[container|catalog-blob]] — Blob storage for book cover images.
## Raw Schema:openapi-v1.yml
openapi: 3.2.0
info:
title: Catalog Service API
description: "Manages the catalog of products for the BookWorm platform, including books, authors, and categories"
contact:
name: BookWorm Engineering
url: https://github.com/foxminchan
email: engineering@bookworm.com
license:
name: MIT
url: https://opensource.org/licenses/MIT
version: "1.0"
summary: A service responsible for managing the catalog of products for the BookWorm platform
paths:
/api/v1/publishers:
put:
tags:
- Publisher
summary: Update Publisher
description: Updates publisher if it exists
operationId: UpdatePublisherEndpoint
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/UpdatePublisherCommand"
required: true
responses:
"204":
description: No Content
"400":
description: Bad Request
content:
application/problem+json:
schema:
$ref: "#/components/schemas/HttpValidationProblemDetails"
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
get:
tags:
- Publisher
summary: List Publishers
description: Lists all publishers
operationId: ListPublishersEndpoint
responses:
"200":
description: OK
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/PublisherDto"
post:
tags:
- Publisher
summary: Create Publisher
description: Creates a new publisher
operationId: CreatePublisherEndpoint
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/CreatePublisherCommand"
required: true
responses:
"200":
description: OK
content:
application/json:
schema:
$ref: "#/components/schemas/PublisherId"
"400":
description: Bad Request
content:
application/problem+json:
schema:
$ref: "#/components/schemas/HttpValidationProblemDetails"
"/api/v1/publishers/{id}":
delete:
tags:
- Publisher
summary: Delete Publisher
description: Delete a publisher from the catalog system
operationId: DeletePublisherEndpoint
parameters:
- name: id
in: path
description: The unique identifier of the publisher to be deleted
required: true
schema: {}
responses:
"204":
description: No Content
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
/api/v1/categories:
put:
tags:
- Category
summary: Update Category
description: Update a category if it exists
operationId: UpdateCategoryEndpoint
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/UpdateCategoryCommand"
required: true
responses:
"204":
description: No Content
"400":
description: Bad Request
content:
application/problem+json:
schema:
$ref: "#/components/schemas/HttpValidationProblemDetails"
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
get:
tags:
- Category
summary: List Categories
description: List all categories
operationId: ListCategoriesEndpoint
responses:
"200":
description: OK
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/CategoryDto"
post:
tags:
- Category
summary: Create Category
description: Create a new category in the catalog system
operationId: CreateCategoryEndpoint
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/CreateCategoryCommand"
required: true
responses:
"200":
description: OK
content:
application/json:
schema:
$ref: "#/components/schemas/CategoryId"
"400":
description: Bad Request
content:
application/problem+json:
schema:
$ref: "#/components/schemas/HttpValidationProblemDetails"
"/api/v1/categories/{id}":
delete:
tags:
- Category
summary: Delete Category
description: Delete a category from the catalog system
operationId: DeleteCategoryEndpoint
parameters:
- name: id
in: path
description: The unique identifier of the category to be deleted
required: true
schema: {}
responses:
"204":
description: No Content
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
/api/v1/books:
put:
tags:
- Book
summary: Update Book
description: Update a book if it exists
operationId: UpdateBookEndpoint
parameters:
- name: If-Match
in: header
description: Expected entity tag for optimistic concurrency control; returns 412 Precondition Failed when stale
schema:
type: string
requestBody:
content:
multipart/form-data:
schema:
$ref: "#/components/schemas/UpdateBookCommand"
required: true
responses:
"204":
description: No Content
"400":
description: Bad Request
content:
application/problem+json:
schema:
$ref: "#/components/schemas/HttpValidationProblemDetails"
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
"412":
description: Precondition Failed
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
query:
tags:
- Book
summary: List Books
description: List all books with advanced filtering and pagination
operationId: ListBooksEndpoint
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/ListBooksQuery"
responses:
"200":
description: OK
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/BookDto"
"400":
description: Bad Request
content:
application/problem+json:
schema:
$ref: "#/components/schemas/HttpValidationProblemDetails"
post:
tags:
- Book
summary: Create Book
description: Create a book
operationId: CreateBookEndpoint
requestBody:
content:
multipart/form-data:
schema:
$ref: "#/components/schemas/CreateBookCommand"
required: true
responses:
"201":
description: Created
content:
application/json:
schema:
$ref: "#/components/schemas/BookId"
"400":
description: Bad Request
content:
application/problem+json:
schema:
$ref: "#/components/schemas/HttpValidationProblemDetails"
"/api/v1/books/{id}":
get:
tags:
- Book
summary: Get Book
description: Get a book by identifier
operationId: GetBookEndpoint
parameters:
- name: id
in: path
description: The unique identifier of the book to be retrieved
required: true
schema: {}
- name: If-None-Match
in: header
description: Entity tag for conditional requests; returns 304 Not Modified when the resource has not changed
schema:
type: string
responses:
"200":
description: OK
headers:
ETag:
description: Entity tag representing the current resource version
schema:
type: string
content:
application/json:
schema:
$ref: "#/components/schemas/BookDto"
"304":
description: Not Modified
headers:
ETag:
description: Entity tag representing the current resource version
schema:
type: string
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
delete:
tags:
- Book
summary: Delete Book
description: Delete a book if it exists
operationId: DeleteBookEndpoint
parameters:
- name: id
in: path
description: The unique identifier of the book to be deleted
required: true
schema: {}
responses:
"204":
description: No Content
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
/api/v1/authors:
put:
tags:
- Author
summary: Update Author
description: Update an author if it exists
operationId: UpdateAuthorEndpoint
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/UpdateAuthorCommand"
required: true
responses:
"204":
description: No Content
"400":
description: Bad Request
content:
application/problem+json:
schema:
$ref: "#/components/schemas/HttpValidationProblemDetails"
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
get:
tags:
- Author
summary: List Authors
description: List all authors
operationId: ListAuthorsEndpoint
responses:
"200":
description: OK
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/AuthorDto"
post:
tags:
- Author
summary: Create Author
description: Create a new author in the catalog system
operationId: CreateAuthorEndpoint
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/CreateAuthorCommand"
required: true
responses:
"200":
description: OK
content:
application/json:
schema:
$ref: "#/components/schemas/AuthorId"
"400":
description: Bad Request
content:
application/problem+json:
schema:
$ref: "#/components/schemas/HttpValidationProblemDetails"
"/api/v1/authors/{id}":
delete:
tags:
- Author
summary: Delete Author
description: Delete an author from the catalog system
operationId: DeleteAuthorEndpoint
parameters:
- name: id
in: path
description: The unique identifier of the author to be deleted
required: true
schema: {}
responses:
"204":
description: No Content
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
components:
schemas:
AuthorDto:
required:
- id
- name
type: object
properties:
id:
$ref: "#/components/schemas/AuthorId"
name: {}
AuthorId:
type: string
format: uuid
BookDto:
required:
- id
- name
- description
- imageUrl
- price
- priceSale
- status
- category
- publisher
- authors
- averageRating
- totalReviews
type: object
properties:
id:
$ref: "#/components/schemas/BookId"
name: {}
description: {}
imageUrl: {}
price:
format: double
priceSale:
format: double
status:
$ref: "#/components/schemas/Status"
category:
oneOf:
- type: "null"
- $ref: "#/components/schemas/CategoryDto"
publisher:
oneOf:
- type: "null"
- $ref: "#/components/schemas/PublisherDto"
authors:
type: array
items:
$ref: "#/components/schemas/AuthorDto"
averageRating:
pattern: "^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$"
type:
- number
- string
format: double
totalReviews:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int32
version:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int64
default: 0
BookId:
type: string
format: uuid
CategoryDto:
required:
- id
- name
type: object
properties:
id:
$ref: "#/components/schemas/CategoryId"
name: {}
CategoryId:
type: string
format: uuid
CreateAuthorCommand:
required:
- name
type: object
properties:
name: {}
CreateBookCommand:
type: object
properties:
name: {}
description: {}
image:
oneOf:
- type: "null"
- $ref: "#/components/schemas/IFormFile"
price:
format: double
priceSale:
format: double
categoryId:
type: string
format: uuid
publisherId:
type: string
format: uuid
authorIds:
type: array
items:
type: string
format: uuid
CreateCategoryCommand:
required:
- name
type: object
properties:
name: {}
CreatePublisherCommand:
required:
- name
type: object
properties:
name: {}
HttpValidationProblemDetails:
type: object
properties:
type: {}
title: {}
status:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- "null"
- integer
- string
format: int32
detail: {}
instance: {}
errors:
type: object
additionalProperties:
type: array
IFormFile:
type:
- "null"
- string
format: binary
ProblemDetails:
type: object
properties:
type: {}
title: {}
status:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- "null"
- integer
- string
format: int32
detail: {}
instance: {}
PublisherDto:
required:
- id
- name
type: object
properties:
id:
$ref: "#/components/schemas/PublisherId"
name: {}
PublisherId:
type: string
format: uuid
Status:
enum:
- InStock
- OutOfStock
UpdateAuthorCommand:
required:
- id
- name
type: object
properties:
id:
$ref: "#/components/schemas/AuthorId"
name: {}
UpdateBookCommand:
type: object
properties:
id:
type: string
format: uuid
name: {}
description: {}
image:
oneOf:
- type: "null"
- $ref: "#/components/schemas/IFormFile"
price:
format: double
priceSale:
format: double
categoryId:
type: string
format: uuid
publisherId:
type: string
format: uuid
authorIds:
type: array
items:
type: string
format: uuid
isRemoveImage:
type: boolean
UpdateCategoryCommand:
required:
- id
- name
type: object
properties:
id:
$ref: "#/components/schemas/CategoryId"
name: {}
UpdatePublisherCommand:
required:
- id
- name
type: object
properties:
id:
$ref: "#/components/schemas/PublisherId"
name: {}
ListBooksQuery:
type: object
properties:
pageIndex:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
description: Number of items to return in a single page of results
format: int32
default: 1
pageSize:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
description: Number of items to return in a single page of results
format: int32
default: 20
orderBy:
type:
- string
- "null"
description: Property to order results by
default: Name
isDescending:
type: boolean
description: Whether to order results in descending order
default: false
search:
type:
- string
- "null"
description: Search term to filter results by
minPrice:
type:
- number
- string
- "null"
description: Minimum price to filter results by
format: double
maxPrice:
type:
- number
- string
- "null"
description: Maximum price to filter results by
format: double
categoryId:
type:
- array
- "null"
items:
type: string
format: uuid
description: Category IDs to filter results by
publisherId:
type:
- array
- "null"
items:
type: string
format: uuid
description: Publisher IDs to filter results by
authorIds:
type:
- array
- "null"
items:
type: string
format: uuid
description: Author IDs to filter results by
tags:
- name: Author
- name: Book
- name: Category
- name: Publisher
## Raw Schema:asyncapi-v1.yml
---
asyncapi: 3.1.0
info:
title: Catalog API integration events
version: 1.0.0
description: |
AsyncAPI contract for the Catalog service's Kafka integration events.
Catalog consumes rating changes from the Rating service and publishes a
failure event when a feedback-created message references an unknown book.
defaultContentType: application/cloudevents+json
channels:
feedbackCreated:
address: bookworm.{env}.rating.feedback-create
description: Rating service publishes this event when feedback is created.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
feedbackCreated:
$ref: "#/components/messages/FeedbackCreatedIntegrationEvent"
feedbackDeleted:
address: bookworm.{env}.rating.feedback-delete
description: Rating service publishes this event when feedback is deleted.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
feedbackDeleted:
$ref: "#/components/messages/FeedbackDeletedIntegrationEvent"
bookUpdatedRatingFailed:
address: bookworm.{env}.catalog.book-update-rating-failed
description: Catalog publishes this event when a feedback-created event cannot update a book.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
bookUpdatedRatingFailed:
$ref: "#/components/messages/BookUpdatedRatingFailedIntegrationEvent"
operations:
receiveFeedbackCreated:
action: receive
channel:
$ref: "#/channels/feedbackCreated"
summary: Consume feedback-created events
messages:
- $ref: "#/channels/feedbackCreated/messages/feedbackCreated"
receiveFeedbackDeleted:
action: receive
channel:
$ref: "#/channels/feedbackDeleted"
summary: Consume feedback-deleted events
messages:
- $ref: "#/channels/feedbackDeleted/messages/feedbackDeleted"
sendBookUpdatedRatingFailed:
action: send
channel:
$ref: "#/channels/bookUpdatedRatingFailed"
summary: Publish rating update failures
messages:
- $ref: "#/channels/bookUpdatedRatingFailed/messages/bookUpdatedRatingFailed"
components:
parameters:
env:
description: BookWorm deployment environment.
enum:
- development
- staging
- production
default: development
messages:
FeedbackCreatedIntegrationEvent:
name: FeedbackCreatedIntegrationEvent
title: Feedback created
summary: A new rating was created for a book.
contentType: application/json
payload:
$ref: "#/components/schemas/FeedbackRatingPayload"
FeedbackDeletedIntegrationEvent:
name: FeedbackDeletedIntegrationEvent
title: Feedback deleted
summary: An existing rating was deleted from a book.
contentType: application/json
payload:
$ref: "#/components/schemas/FeedbackRatingPayload"
BookUpdatedRatingFailedIntegrationEvent:
name: BookUpdatedRatingFailedIntegrationEvent
title: Book rating update failed
summary: Catalog could not update a book rating for the feedback event.
contentType: application/json
payload:
$ref: "#/components/schemas/BookUpdatedRatingFailedPayload"
schemas:
FeedbackRatingPayload:
type: object
additionalProperties: false
required:
- bookId
- rating
- feedbackId
properties:
bookId:
type: string
format: uuid
description: Identifier of the book whose rating summary changes.
rating:
type: integer
description: Rating value added to or removed from the book.
feedbackId:
type: string
format: uuid
description: Identifier of the feedback record.
BookUpdatedRatingFailedPayload:
type: object
additionalProperties: false
required:
- feedbackId
properties:
feedbackId:
type: string
format: uuid
description: Identifier of the feedback that could not be applied.
---
id: catalog-ingestion
name: Catalog Ingestion
version: 1.0.0
summary: |
Internal background worker that reads pending Catalog book updates and
synchronizes semantic search vectors in Qdrant.
styles:
icon: /icons/compute/function.svg
writesTo:
- id: catalog-database
- id: catalog-vector
readsFrom:
- id: catalog-database
owners:
- catalog-experience-team
badges:
- content: Internal
backgroundColor: gray
textColor: gray
- content: Background worker
backgroundColor: blue
textColor: blue
receives:
- id: ProcessVectorBatchIntegrationEvent
version: 1.0.0
from:
- id: scheduler.process-vector-batch
version: 1.0.0
repository:
language: C#
url: "https://github.com/foxminchan/BookWorm"
---
## Service Responsibility & Boundary
Catalog Ingestion is an internal background worker within the [[domain|catalog]] domain that reads coalesced book mutations from [[container|catalog-database]], generates semantic embeddings, and upserts or removes records in [[container|catalog-vector]]. Authoring APIs and synchronous search queries remain owned by [[service|catalog-api]], while recurring schedule management is delegated to [[service|scheduler-service]].
## Service Profile
| Property | Value |
| :---------------------------------------- | :------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context / Domain** | [[domain\|catalog]] |
| **Owner Team** | [[team\|catalog-experience-team]] |
| **Runtime Style** | Async Worker (Kafka-triggered serverless function) |
| **Public / Gateway Exposure** | Internal Only (no HTTP or gRPC surface) |
| **Authentication & Authorization Policy** | Internal worker; Azure Managed Identity RBAC for AI embedding generation |
| **Owned Data Store(s)** | Reads/acknowledges pending queue in [[container\|catalog-database]]; writes derived index in [[container\|catalog-vector]] |
| **Key Resilience / Idempotency Pattern** | Distributed advisory lock for single-writer exclusivity and revision-checked queue acknowledgment |
## Contracts & Data Ownership
Catalog Ingestion owns no authoritative business entities. It processes bounded batches of up to 200 pending updates from [[container|catalog-database]] on each scheduled trigger and updates [[container|catalog-vector]] accordingly.
:::note
If a book is modified concurrently while a batch is in flight, its pending queue revision changes and the worker leaves the row queued for the next cycle—preventing stale embeddings from overwriting newer edits.
:::
- **Single-writer exclusivity:** Acquires an exclusive advisory lock on
[[container|catalog-database]]; overlapping triggers exit immediately without duplicate work. -
**Retry on downstream failure:** If embedding generation or vector store writes fail,
unacknowledged rows remain queued and are retried automatically on the next 5-minute trigger.
## Architecture Visualizations & Specifications
### Vector Indexing Flow
### Service Interactions
## Attached Resources & Related Docs
- [[doc|platform/006-api-and-contracts]] — Consolidated service and messaging directory.
- [[service|catalog-api]] — Authoritative Catalog service that enqueues vector updates.
- [[service|scheduler-service]] — Scheduler dispatching periodic batch triggers.
- [[container|catalog-database]] — Authoritative catalog store and pending update queue.
- [[container|catalog-vector]] — Derived vector search collection.
---
id: chat-api
name: Chat API
version: 1.0.0
summary: |
Internal HTTP host for BookWorm's interactive multi-agent chat workflow,
agent discovery, and session persistence.
owners:
- ai-capabilities-team
readsFrom:
- id: chat-session-blob
version: 1.0.0
writesTo:
- id: chat-session-blob
version: 1.0.0
styles:
icon: /icons/languages/dotnet.svg
repository:
language: C#
url: "https://github.com/foxminchan/BookWorm"
badges:
- content: Internal
backgroundColor: gray
textColor: gray
- content: HTTP API
backgroundColor: teal
textColor: teal
---
## Service Responsibility & Boundary
Chat API is the interactive conversational host within the [[domain|conversational]] domain, orchestrating BookWorm's multi-agent chat workflow, prompt safety validation, and session persistence in [[container|chat-session-blob]]. It delegates catalog lookups to [[service|mcp-server]], review summarization to [[agent|rating-agent]] in [[service|rating-api]] over Agent-to-Agent (A2A) gRPC, and PII redaction to [[service|presidio-api]]. Chat API never places orders, modifies baskets, writes reviews, or publishes Kafka integration events.
## Service Profile
| Property | Value |
| :---------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context / Domain** | [[domain\|conversational]] |
| **Owner Team** | [[team\|ai-capabilities-team]] |
| **Runtime Style** | REST / Streaming API (AG-UI & Agent Discovery) |
| **Public / Gateway Exposure** | Yes via API Gateway |
| **Authentication & Authorization Policy** | Microsoft Entra ID JWT (`customer` or `admin` role + chat scopes) and Entra Agent Identities with On-Behalf-Of (OBO) token exchange |
| **Owned Data Store(s)** | [[container\|chat-session-blob]] (conversation transcripts and agent memory) |
| **Key Resilience / Idempotency Pattern** | Fail-closed PII screening, per-user rate limiting, and prompt-injection/scope gating |
## Contracts & Data Ownership
Chat API persists conversation session state and model memory in [[container|chat-session-blob]] and exposes the interactive streaming chat endpoint alongside agent discovery metadata.
:::warning
Chat API operates exclusively as an A2A **client** communicating with [[service|rating-api]]. All specialist agent inputs and outputs pass through fail-closed PII screening via [[service|presidio-api]]; streaming responses are buffered until privacy filtering succeeds, and any screening failure aborts the turn.
:::
- **Validation & scope routing:** Empty or suspected prompt-injection inputs are rejected
immediately, oversized inputs are truncated safely, and non-English or out-of-scope requests
short-circuit before reaching specialist agents. - **Scoped specialists:** [[agent|qa-agent]]
answers store-policy questions without catalog tools; [[agent|book-agent]] coordinates
[[agent|book-catalog-researcher]] and [[agent|book-recommendation-researcher]] using read-only
catalog tools on [[service|mcp-server]]; review insights delegate to [[agent|rating-agent]].
## Architecture Visualizations & Specifications
### Conversational Workflow Context
### Service Interactions
## Attached Resources & Related Docs
- [[doc|platform/006-api-and-contracts]] — Consolidated service and protocol index.
- [[agent|book-agent]] — Primary catalog and recommendation specialist.
- [[agent|qa-agent]] — Store-policy specialist.
- [[container|chat-session-blob]] — Conversation session storage.
- [[service|presidio-api]] — PII detection and anonymization sidecars.
- [[service|mcp-server]] — Read-only Catalog MCP server.
---
id: mcp-server
name: MCP Server
version: 1.0.0
summary: |
Internal stateless Streamable HTTP MCP service that exposes read-only
Catalog lookup tools and reusable AI prompts.
owners:
- ai-capabilities-team
sends:
- id: ListBooksGrpc
version: 1.0.0
group: Catalog Queries
- id: GetBookDetailsGrpc
version: 1.0.0
group: Catalog Queries
- id: ListCategoriesGrpc
version: 1.0.0
group: Catalog Queries
- id: ListAuthorsGrpc
version: 1.0.0
group: Catalog Queries
repository:
language: C#
url: "https://github.com/foxminchan/BookWorm"
styles:
icon: /icons/languages/dotnet.svg
badges:
- content: Internal
backgroundColor: gray
textColor: gray
- content: HTTP API
backgroundColor: teal
textColor: teal
---
## Service Responsibility & Boundary
MCP Server is a stateless Model Context Protocol (MCP) adapter within the [[domain|conversational]] domain that exposes read-only catalog lookup tools and reusable AI prompt templates over Streamable HTTP to [[service|chat-api]] and [[service|rating-api]]. It delegates all product queries to [[service|catalog-api]] over gRPC and owns no databases, caches, or messaging channels.
## Service Profile
| Property | Value |
| :---------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context / Domain** | [[domain\|conversational]] |
| **Owner Team** | [[team\|ai-capabilities-team]] |
| **Runtime Style** | Stateless Streamable HTTP MCP Server |
| **Public / Gateway Exposure** | Internal Only (not routed via public API Gateway) |
| **Authentication & Authorization Policy** | Microsoft Entra ID JWT requiring `mcptools_read` scope with server-side authorization filters and default-deny governance policies |
| **Owned Data Store(s)** | None (Stateless) |
| **Key Resilience / Idempotency Pattern** | Global rate limiting, RFC 9457 error handling, and explicit error propagation on upstream gRPC failures |
## Contracts & Data Ownership
MCP Server owns no persistent entities or data stores. It translates four read-only catalog tools (`search_catalog`, `get_book`, `list_categories`, `list_authors`) into gRPC queries against [[service|catalog-api]] and serves reusable prompt templates for book recommendations and review summarization.
:::note
MCP Server has no upstream dependency on [[service|rating-api]] and exposes no review-fetching tool. [[service|rating-api]] retrieves raw customer feedback in-process while using MCP Server only for book details and review-analysis prompts.
:::
## Architecture Visualizations & Specifications
### MCP Integration Context
### Service Interactions
## Attached Resources & Related Docs
- [[doc|platform/006-api-and-contracts]] — Consolidated service, HTTP, gRPC, and Kafka index.
- [[service|catalog-api]] — Upstream gRPC catalog provider.
- [[service|chat-api]] — Conversational consumer of Catalog MCP tools.
- [[service|rating-api]] — Consumer of book detail lookups and rating analysis prompts.
---
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.{env}.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.
:::
- **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.{env}.notification.dead-letter-queue]].
## Architecture Visualizations & Specifications
### Notification Delivery Context
### Service Interactions
## 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.
---
id: oauth-api
name: OAuth API
version: 1.0.0
summary: |
External OAuth 2.0 and OIDC identity provider API used by BookWorm clients
and services to authenticate users, issue tokens, and delegate agent access.
externalSystem: true
owners:
- platform-engineering-team
badges:
- content: External
backgroundColor: purple
textColor: purple
- content: HTTP API
backgroundColor: teal
textColor: teal
styles:
icon: /icons/third-party/entra-id.svg
---
## Integration Purpose & Boundary
OAuth API (backed by Microsoft Entra ID) is BookWorm's external OAuth 2.0 and OpenID Connect (OIDC) authentication boundary. Storefront and Backoffice clients authenticate users against it, while [[service|catalog-api]], [[service|basket-api]], [[service|order-api]], [[service|rating-api]], [[service|chat-api]], [[service|mcp-server]], and [[service|scheduler-service]] validate issued JWTs and use Entra Agent Identities for delegated On-Behalf-Of (OBO) calls.
:::warning
Authentication is not authorization: OAuth API verifies caller identity and issues role/scope claims (`customer`, `business_user`, `admin`), while each BookWorm service enforces its own resource-ownership and policy checks. Protected services must **fail closed** (`401 Unauthorized`) whenever token validation or provider metadata fails.
:::
## Integration Profile
| Property | Value |
| :------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Provider / Sidecar** | Microsoft Entra ID (OAuth 2.0 / OIDC & Entra Agent Identities) |
| **BookWorm Consumers** | [[service\|catalog-api]], [[service\|basket-api]], [[service\|order-api]], [[service\|rating-api]], [[service\|chat-api]], [[service\|mcp-server]], [[service\|scheduler-service]], Storefront, and Backoffice |
| **Runtime Transport & Protocol** | HTTPS OAuth 2.0 / OIDC (proxied via API Gateway for browser flows; JWT & OBO token exchange for APIs) |
| **Auth / Credential Boundary** | Federated Managed Identity in publish environments; client secrets and signing tokens kept strictly out of source control and logs |
| **Data / PII Sensitivity** | High — carries user identity claims, access tokens, and session cookies; never log bearer tokens or refresh credentials |
| **Failure / Fallback Behavior** | Fail-closed — protected APIs reject unauthenticated or unverifiable requests with `401 Unauthorized` without anonymous fallback |
## Visualizations & Specifications
### Authentication & Delegation Context
### Service Interactions
- **App roles:** `customer` (storefront shopping, orders, chat, and reviews), `business_user`
(catalog writes), and `admin` (backoffice dashboards, moderation, and scheduler operations). -
**Service scopes:** Each API enforces its own read/write scopes (`catalog_read`/`catalog_write`,
`basket_read`/`basket_write`, `ordering_read`/`ordering_write`, `rating_read`/`rating_write`,
`chatting_read`/`chatting_write`, `mcptools_read`).
## Related Documentation
- [[doc|platform/006-api-and-contracts]] — Consolidated service authentication and route index.
- [[doc|platform/004-identity-and-rbac-matrix]] — Platform-wide Azure RBAC and Entra ID permissions.
- [[service|chat-api]] — Consumer of agent identity and OBO token exchange.
- [[service|rating-api]] — Consumer of agent identity and A2A read scope policy.
- [[system|identity-provider]] — External Identity Provider system boundary.
---
id: order-api
name: Order API
version: 1.0.0
summary: |
Authenticated Ordering service for Buyer profiles and the Order lifecycle,
creating Orders from baskets, snapshotting prices, and coordinating status events.
owners:
- commerce-fulfillment-team
badges:
- content: Internal
backgroundColor: gray
textColor: gray
- content: HTTP API
backgroundColor: teal
textColor: teal
diagrams:
- id: order-lifecycle
version: 1.0.0
- id: checkout-interaction
version: 1.0.0
readsFrom:
- id: order-database
version: 1.0.0
- id: order-cache
version: 1.0.0
writesTo:
- id: order-database
version: 1.0.0
- id: order-cache
version: 1.0.0
receives:
- id: CreateOrder
version: 1.0.0
group: Order Commands
- id: CompleteOrder
version: 1.0.0
group: Order Commands
- id: CancelOrder
version: 1.0.0
group: Order Commands
- id: DeleteOrder
version: 1.0.0
group: Order Commands
- id: CreateBuyer
version: 1.0.0
group: Buyer Commands
- id: UpdateAddress
version: 1.0.0
group: Buyer Commands
- id: DeleteBuyer
version: 1.0.0
group: Buyer Commands
- id: GetOrder
version: 1.0.0
group: Order Queries
- id: ListOrders
version: 1.0.0
group: Order Queries
- id: GetBuyer
version: 1.0.0
group: Buyer Queries
- id: ListBuyers
version: 1.0.0
group: Buyer Queries
- id: DeleteBasketCompleteCommand
version: 1.0.0
group: Basket Cleanup Outcomes
from:
- id: bookworm.{env}.finance.delete-basket-complete
version: 1.0.0
- id: DeleteBasketFailedCommand
version: 1.0.0
group: Basket Cleanup Outcomes
from:
- id: bookworm.{env}.finance.delete-basket-failed
version: 1.0.0
sends:
- id: GetBasketGrpc
version: 1.0.0
group: Checkout Enrichment Queries
- id: GetBookGrpc
version: 1.0.0
group: Checkout Enrichment Queries
- id: GetBooksGrpc
version: 1.0.0
group: Checkout Enrichment Queries
- id: GetDashboardGrpc
version: 1.0.0
- id: UserCheckedOutIntegrationEvent
version: 1.0.0
to:
- id: bookworm.{env}.ordering.user-checked-out
version: 1.0.0
- id: OrderStatusChangedToCompleteIntegrationEvent
version: 1.0.0
group: Order Status Changes
to:
- id: bookworm.{env}.ordering.order-status-change-to-complete
version: 1.0.0
- id: OrderStatusChangedToCancelIntegrationEvent
version: 1.0.0
group: Order Status Changes
to:
- id: bookworm.{env}.ordering.order-status-change-to-cancel
version: 1.0.0
entities:
- id: buyer
version: 1.0.0
- id: order
version: 1.0.0
- id: order-item
version: 1.0.0
styles:
icon: /icons/languages/dotnet.svg
specifications:
- type: openapi
path: openapi-v1.yaml
name: OpenAPI v1
- type: asyncapi
path: asyncapi-v1.yml
name: AsyncAPI v1
- type: generic
path: sla.yaml
name: Carrier Service Levels
repository:
language: C#
url: "https://github.com/foxminchan/BookWorm"
---
## Service Responsibility & Boundary
Order API is the system of record within the [[domain|ordering]] domain for [[entity|buyer]] profiles, accepted [[entity|order]] aggregates, purchase-time [[entity|order-item]] price snapshots, and Order lifecycle statuses (`New`, `Completed`, `Cancelled`). It serves versioned HTTP endpoints and Server-Sent Events (SSE) backoffice dashboards, queries [[service|basket-api]] and [[service|catalog-api]] over gRPC during checkout, and delegates post-checkout basket cleanup and email coordination to [[service|order-orchestration]] over Kafka.
## Service Profile
| Property | Value |
| :---------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context / Domain** | [[domain\|ordering]] |
| **Owner Team** | [[team\|commerce-fulfillment-team]] |
| **Runtime Style** | REST API, SSE Dashboard Stream, gRPC Client, and Async Kafka Producer/Consumer |
| **Public / Gateway Exposure** | Yes via API Gateway |
| **Authentication & Authorization Policy** | Microsoft Entra ID JWT via [[system\|identity-provider]]; `customer` or `admin` roles with ordering scopes; backoffice dashboard also requires `admin` and catalog read scope |
| **Owned Data Store(s)** | [[container\|order-database]] (relational, event-sourced history, and transactional outbox), [[container\|order-cache]] (distributed locks, idempotency markers, and dashboard cache) |
| **Key Resilience / Idempotency Pattern** | 1-hour `x-request-id` idempotency markers, buyer-scoped distributed write locks, per-user rate limiting, and dead-letter routing on [[channel\|bookworm.{env}.ordering.dead-letter-queue]] |
## Contracts & Data Ownership
Order API owns [[entity|buyer]], [[entity|order]], and [[entity|order-item]] in [[container|order-database]] and uses [[container|order-cache]] for checkout concurrency locks, idempotency markers, and short-lived dashboard caching.
:::note
Every new Order starts in `New` status with line totals locked to active Catalog prices (sale price when set, otherwise regular price). Later Catalog price edits never rewrite accepted Orders, and soft-deletion on failed basket cleanup preserves audit records without altering business status.
:::
:::warning
State-changing Order operations require an `x-request-id` idempotency header. Duplicate keys within the 1-hour idempotency window return `409 Conflict`—callers should inspect existing Order status before generating a new idempotency key.
:::
- **Order event stream:** Domain events append to an event stream in [[container|order-database]]
to support chronological order history and time-travel summary views. - **Lifecycle separation:**
Completing or cancelling an Order is permitted only from `New` status; receiving
[[command|DeleteBasketCompleteCommand]] never auto-completes an Order, and
[[command|DeleteBasketFailedCommand]] soft-deletes the Order without changing its business status.
## Architecture Visualizations & Specifications
### Order API Context
### Service Interactions
### Owned Entities
## Attached Resources & Related Docs
- [[doc|platform/006-api-and-contracts]] — Consolidated service, HTTP, gRPC, and Kafka directory.
- [[service|order-orchestration]] — Downstream Finance durable workflow.
- [[container|order-database]] — PostgreSQL relational, event-store, and outbox storage.
- [[container|order-cache]] — Redis locks, idempotency, and dashboard cache.
- [[diagram|order-lifecycle]] — Order status transitions and saga separation.
- [[doc|domains/bookworm/subdomains/ordering/engineering/01-order-consistency-and-data-ownership]] — Ordering consistency and ownership boundaries.
## Raw Schema:openapi-v1.yaml
openapi: 3.2.0
info:
title: Ordering Service API
description: "Orchestrates the entire order lifecycle, from creation to completion or cancellation, for the BookWorm platform"
contact:
name: BookWorm Engineering
url: https://github.com/foxminchan
email: engineering@bookworm.com
license:
name: MIT
url: https://opensource.org/licenses/MIT
version: "1.0"
summary: A service responsible for managing the order lifecycle for the BookWorm platform
paths:
/api/v1/orders:
get:
tags:
- Order
summary: List Orders
description: List orders with pagination and filtering
operationId: ListOrdersEndpoint
parameters:
- name: PageIndex
in: query
description: Number of items to return in a single page of results
schema:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int32
default: 1
- name: PageSize
in: query
description: Number of items to return in a single page of results
schema:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int32
default: 20
- name: Status
in: query
description: Status to filter results by
schema:
$ref: "#/components/schemas/Status"
- name: BuyerId
in: query
description: Buyer ID to filter results by
schema:
type: string
format: uuid
responses:
"200":
description: OK
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/OrderDto"
"400":
description: Bad Request
content:
application/problem+json:
schema:
$ref: "#/components/schemas/HttpValidationProblemDetails"
post:
tags:
- Order
summary: Create Order
description: Create a new order
operationId: CreateOrderEndpoint
parameters:
- name: x-request-id
in: header
description: The idempotency key of the order to be created
required: true
schema:
type: string
responses:
"201":
description: Created
content:
application/json:
schema:
$ref: "#/components/schemas/OrderId"
"/api/v1/orders/{id}":
get:
tags:
- Order
summary: Get Order
description: Get an order if it exists
operationId: GetOrderEndpoint
parameters:
- name: id
in: path
description: The unique identifier of the order to be retrieved
required: true
schema:
type: string
responses:
"200":
description: OK
content:
application/json:
schema:
$ref: "#/components/schemas/OrderDetailDto"
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
delete:
tags:
- Order
summary: Delete Order
description: Delete an order if it exists
operationId: DeleteOrderEndpoint
parameters:
- name: id
in: path
description: The unique identifier of the order to be deleted
required: true
schema:
type: string
responses:
"204":
description: No Content
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
"/api/v1/orders/{id}/summary":
get:
tags:
- Order
summary: Get Order Event-Sourced Summary
description: Reconstructs the order summary from its event stream (optionally at a specific version) and returns its stream version as an ETag
operationId: GetOrderSummaryEndpoint
parameters:
- name: id
in: path
description: The unique identifier of the order
required: true
schema:
type: string
- name: version
in: query
description: Optional stream version for point-in-time replay
schema:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int64
- name: at
in: query
description: Optional UTC timestamp for point-in-time replay
schema:
type: string
format: date-time
- name: If-None-Match
in: header
description: Entity tag for conditional requests; returns 304 Not Modified when the resource has not changed
schema:
type: string
responses:
"200":
description: OK
headers:
ETag:
description: Entity tag representing the current resource version
schema:
type: string
content:
application/json:
schema:
$ref: "#/components/schemas/OrderSummaryDto"
"304":
description: Not Modified
headers:
ETag:
description: Entity tag representing the current resource version
schema:
type: string
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
"/api/v1/orders/{id}/history":
get:
tags:
- Order
summary: Get Order Event History
description: Get the chronological event stream history for an order
operationId: GetOrderHistoryEndpoint
parameters:
- name: id
in: path
description: The unique identifier of the order
required: true
schema:
type: string
responses:
"200":
description: OK
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/OrderEventHistoryDto"
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
"/api/v1/orders/{orderId}/complete":
patch:
tags:
- Order
summary: Complete Order
description: Complete an order
operationId: CompleteOrderEndpoint
parameters:
- name: x-request-id
in: header
description: The idempotency key of the order to be completed
required: true
schema:
type: string
- name: orderId
in: path
description: The unique identifier of the order to be completed
required: true
schema:
type: string
responses:
"200":
description: OK
content:
application/json:
schema:
$ref: "#/components/schemas/OrderDetailDto"
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
"/api/v1/orders/{orderId}/cancel":
patch:
tags:
- Order
summary: Cancel Order
description: Cancel an order
operationId: CancelOrderEndpoint
parameters:
- name: x-request-id
in: header
description: The idempotency key of the order to be cancelled
required: true
schema:
type: string
- name: orderId
in: path
description: The unique identifier of the order to be cancelled
required: true
schema:
type: string
responses:
"200":
description: OK
content:
application/json:
schema:
$ref: "#/components/schemas/OrderDetailDto"
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
/api/v1/dashboard:
get:
tags:
- Dashboard
summary: Get backoffice dashboard
description: "Get store-wide totals, seven UTC daily buckets, categories, and the five newest orders"
operationId: GetDashboardEndpoint
responses:
"200":
description: OK
content:
application/json:
schema:
$ref: "#/components/schemas/DashboardDto"
"400":
description: Bad Request
content:
application/problem+json:
schema:
$ref: "#/components/schemas/HttpValidationProblemDetails"
/api/v1/dashboard/stream:
get:
tags:
- Dashboard
summary: Stream backoffice dashboard
description: Send cached dashboard snapshots every 15 seconds; reconnect to resynchronize
operationId: StreamDashboardEndpoint
responses:
"200":
description: OK
content:
text/event-stream:
itemSchema:
required:
- data
type: object
properties:
data:
$ref: "#/components/schemas/DashboardDto"
event:
type: string
id:
type: string
/api/v1/buyers/address:
patch:
tags:
- Buyer
summary: Update Buyer Address
description: "Update the current buyer's address"
operationId: UpdateAddressEndpoint
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/UpdateAddressCommand"
required: true
responses:
"200":
description: OK
content:
application/json:
schema:
$ref: "#/components/schemas/BuyerDto"
"400":
description: Bad Request
content:
application/problem+json:
schema:
$ref: "#/components/schemas/HttpValidationProblemDetails"
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
/api/v1/buyers:
get:
tags:
- Buyer
summary: List Buyers
description: List all buyers with pagination options
operationId: ListBuyersEndpoint
parameters:
- name: PageIndex
in: query
description: Number of items to return in a single page of results
schema:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int32
default: 1
- name: PageSize
in: query
description: Number of items to return in a single page of results
schema:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int32
default: 20
responses:
"200":
description: OK
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/BuyerDto"
post:
tags:
- Buyer
summary: Create Buyer
description: Create a new buyer in the system
operationId: CreateBuyerEndpoint
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/CreateBuyerCommand"
required: true
responses:
"201":
description: Created
content:
application/json:
schema:
$ref: "#/components/schemas/BuyerId"
"400":
description: Bad Request
content:
application/problem+json:
schema:
$ref: "#/components/schemas/HttpValidationProblemDetails"
/api/v1/buyers/me:
get:
tags:
- Buyer
summary: Get Buyer
description: "Get the current buyer's information"
operationId: GetBuyerEndpoint
parameters:
- name: Id
in: query
description: "Only 'ADMIN' role can retrieve other users' data"
required: true
schema:
type: string
format: uuid
responses:
"200":
description: OK
content:
application/json:
schema:
$ref: "#/components/schemas/BuyerDto"
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
"/api/v1/buyers/{id}":
delete:
tags:
- Buyer
summary: Delete Buyer
description: Delete a buyer by ID if it exists
operationId: DeleteBuyerEndpoint
parameters:
- name: id
in: path
description: The unique identifier of the buyer to be deleted
required: true
schema:
type: string
responses:
"204":
description: No Content
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
components:
schemas:
BuyerDto:
required:
- id
- name
- address
type: object
properties:
id:
$ref: "#/components/schemas/BuyerId"
name:
type:
- "null"
- string
address:
type:
- "null"
- string
BuyerId:
type: string
format: uuid
CategoryCountDto:
required:
- name
- value
type: object
properties:
name:
type: string
value:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int64
CreateBuyerCommand:
required:
- street
- city
- province
type: object
properties:
street:
type: string
city:
type: string
province:
type: string
DailyOrdersDto:
required:
- date
- orders
- revenue
type: object
properties:
date:
type: string
format: date
orders:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int64
revenue:
format: double
DashboardDto:
required:
- totalOrders
- totalRevenue
- totalCustomers
- totalBooks
- dailyOrders
- categories
- recentOrders
- updatedAt
type: object
properties:
totalOrders:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int64
totalRevenue:
format: double
totalCustomers:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int64
totalBooks:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int64
dailyOrders:
type: array
items:
$ref: "#/components/schemas/DailyOrdersDto"
categories:
type: array
items:
$ref: "#/components/schemas/CategoryCountDto"
recentOrders:
type: array
items:
$ref: "#/components/schemas/RecentOrderDto"
updatedAt:
type: string
format: date-time
HttpValidationProblemDetails:
type: object
properties:
type:
type:
- "null"
- string
title:
type:
- "null"
- string
status:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- "null"
- integer
- string
format: int32
detail:
type:
- "null"
- string
instance:
type:
- "null"
- string
errors:
type: object
additionalProperties:
type: array
items:
type: string
OrderDetailDto:
required:
- id
- date
- total
- status
- items
type: object
properties:
id:
$ref: "#/components/schemas/OrderId"
date:
type: string
format: date-time
total:
format: double
status:
$ref: "#/components/schemas/Status"
items:
type: array
items:
$ref: "#/components/schemas/OrderItemDto"
OrderDto:
required:
- id
- date
- total
- status
type: object
properties:
id:
$ref: "#/components/schemas/OrderId"
date:
type: string
format: date-time
total:
format: double
status:
$ref: "#/components/schemas/Status"
OrderEventHistoryDto:
required:
- sequence
- version
- eventType
- timestamp
- status
- totalPrice
type: object
properties:
sequence:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int64
version:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int64
eventType:
type: string
timestamp:
type: string
format: date-time
status:
oneOf:
- type: "null"
- $ref: "#/components/schemas/Status"
totalPrice:
format: double
OrderId:
type: string
format: uuid
OrderItemDto:
required:
- id
- quantity
- price
type: object
properties:
id:
type: string
format: uuid
quantity:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int32
price:
format: double
name:
type:
- "null"
- string
OrderSummaryDto:
required:
- id
- status
- totalPrice
- version
type: object
properties:
id:
type: string
format: uuid
status:
$ref: "#/components/schemas/Status"
totalPrice:
format: double
version:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int64
ProblemDetails:
type: object
properties:
type:
type:
- "null"
- string
title:
type:
- "null"
- string
status:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- "null"
- integer
- string
format: int32
detail:
type:
- "null"
- string
instance:
type:
- "null"
- string
RecentOrderDto:
required:
- id
- date
- total
- status
type: object
properties:
id:
type: string
format: uuid
date:
type: string
format: date-time
total:
format: double
status:
type: string
Status:
enum:
- New
- Cancelled
- Completed
UpdateAddressCommand:
required:
- street
- city
- province
type: object
properties:
street:
type: string
city:
type: string
province:
type: string
tags:
- name: Buyer
- name: Dashboard
- name: Order
## Raw Schema:asyncapi-v1.yml
asyncapi: 3.1.0
info:
title: Order API integration messages
version: 1.0.0
description: |
AsyncAPI contract for Order API's Finance integration. Order API publishes
checkout and Order status events, and consumes basket-cleanup outcomes.
defaultContentType: application/cloudevents+json
channels:
userCheckedOut:
address: bookworm.{env}.ordering.user-checked-out
description: Order API publishes this event after placing an Order.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
userCheckedOut:
$ref: "#/components/messages/UserCheckedOutIntegrationEvent"
orderStatusChangedToComplete:
address: bookworm.{env}.ordering.order-status-change-to-complete
description: Order API publishes this event after completing an Order.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
orderStatusChangedToComplete:
$ref: "#/components/messages/OrderStatusChangedToCompleteIntegrationEvent"
orderStatusChangedToCancel:
address: bookworm.{env}.ordering.order-status-change-to-cancel
description: Order API publishes this event after cancelling an Order.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
orderStatusChangedToCancel:
$ref: "#/components/messages/OrderStatusChangedToCancelIntegrationEvent"
deleteBasketComplete:
address: bookworm.{env}.finance.delete-basket-complete
description: Finance publishes this command after successful basket cleanup.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
deleteBasketComplete:
$ref: "#/components/messages/DeleteBasketCompleteCommand"
deleteBasketFailed:
address: bookworm.{env}.finance.delete-basket-failed
description: Finance publishes this command when basket cleanup fails.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
deleteBasketFailed:
$ref: "#/components/messages/DeleteBasketFailedCommand"
operations:
sendUserCheckedOut:
action: send
channel:
$ref: "#/channels/userCheckedOut"
summary: Publish checkout details
messages:
- $ref: "#/channels/userCheckedOut/messages/userCheckedOut"
sendOrderStatusChangedToComplete:
action: send
channel:
$ref: "#/channels/orderStatusChangedToComplete"
summary: Publish completed Order details
messages:
- $ref: "#/channels/orderStatusChangedToComplete/messages/orderStatusChangedToComplete"
sendOrderStatusChangedToCancel:
action: send
channel:
$ref: "#/channels/orderStatusChangedToCancel"
summary: Publish cancelled Order details
messages:
- $ref: "#/channels/orderStatusChangedToCancel/messages/orderStatusChangedToCancel"
receiveDeleteBasketComplete:
action: receive
channel:
$ref: "#/channels/deleteBasketComplete"
summary: Receive successful basket-cleanup outcomes
messages:
- $ref: "#/channels/deleteBasketComplete/messages/deleteBasketComplete"
receiveDeleteBasketFailed:
action: receive
channel:
$ref: "#/channels/deleteBasketFailed"
summary: Receive failed basket-cleanup outcomes
messages:
- $ref: "#/channels/deleteBasketFailed/messages/deleteBasketFailed"
components:
parameters:
env:
description: BookWorm deployment environment.
enum:
- development
- staging
- production
default: development
messages:
UserCheckedOutIntegrationEvent:
name: UserCheckedOutIntegrationEvent
title: User checked out
summary: An Order was placed and checkout details are ready for Finance.
contentType: application/json
payload:
$ref: "#/components/schemas/OrderIntegrationEventPayload"
OrderStatusChangedToCompleteIntegrationEvent:
name: OrderStatusChangedToCompleteIntegrationEvent
title: Order completed
summary: An Order transitioned from New to Completed.
contentType: application/json
payload:
$ref: "#/components/schemas/OrderIntegrationEventPayload"
OrderStatusChangedToCancelIntegrationEvent:
name: OrderStatusChangedToCancelIntegrationEvent
title: Order cancelled
summary: An Order transitioned from New to Cancelled.
contentType: application/json
payload:
$ref: "#/components/schemas/OrderIntegrationEventPayload"
DeleteBasketCompleteCommand:
name: DeleteBasketCompleteCommand
title: Basket deletion completed
summary: Finance reports that basket cleanup completed successfully.
contentType: application/json
payload:
$ref: "#/components/schemas/DeleteBasketCompletePayload"
DeleteBasketFailedCommand:
name: DeleteBasketFailedCommand
title: Basket deletion failed
summary: Finance reports that basket cleanup failed.
contentType: application/json
payload:
$ref: "#/components/schemas/DeleteBasketFailedPayload"
schemas:
OrderIntegrationEventPayload:
type: object
additionalProperties: false
required:
- id
- creationDate
- orderId
- basketId
- fullName
- email
- totalMoney
properties:
id:
type: string
format: uuid
description: Unique identifier assigned to the integration event.
creationDate:
type: string
format: date-time
description: UTC timestamp when the integration event was created.
orderId:
type: string
format: uuid
description: Identifier of the Order.
basketId:
type: string
format: uuid
description: |
UUID serialized as basketId. The current EventMapper supplies the
Order's BuyerId for this field.
fullName:
type:
- string
- "null"
description: Customer name, when available.
email:
type:
- string
- "null"
format: email
description: Customer email, when available.
totalMoney:
type: number
format: double
description: Total purchase amount associated with the Order.
DeleteBasketCompletePayload:
type: object
additionalProperties: false
required:
- id
- creationDate
- orderId
- totalMoney
properties:
id:
type: string
format: uuid
description: Unique identifier assigned to the integration message.
creationDate:
type: string
format: date-time
description: UTC timestamp when the integration message was created.
orderId:
type: string
format: uuid
description: Identifier of the Order whose basket cleanup completed.
totalMoney:
type: number
format: double
description: Total purchase amount associated with the Order.
DeleteBasketFailedPayload:
type: object
additionalProperties: false
required:
- id
- creationDate
- basketId
- email
- orderId
- totalMoney
properties:
id:
type: string
format: uuid
description: Unique identifier assigned to the integration message.
creationDate:
type: string
format: date-time
description: UTC timestamp when the integration message was created.
basketId:
type: string
format: uuid
description: Identifier of the basket whose cleanup failed.
email:
type:
- string
- "null"
format: email
description: Customer email, when available.
orderId:
type: string
format: uuid
description: Identifier of the affected Order.
totalMoney:
type: number
format: double
description: Total purchase amount associated with the Order.
## Raw Schema:sla.yaml
kind: CarrierServiceLevelAgreement
version: 2026.1
status: draft
domain: ordering
purpose: >-
Provide delivery estimates for order planning. The carrier owns shipment
execution; delivery does not itself change the BookWorm Order status.
effectiveDate: Upon signature by both parties
carriers:
- id: bookworm-primary-carrier
name: BookWorm Primary Parcel Carrier
regions:
- BookWorm-supported domestic delivery destinations
serviceLevels:
- code: STANDARD
deliveryDays: "3-5"
deliveryDayType: business-days
deliveryPeriodStarts: carrier-acceptance
cutOffTime: "16:00"
cutOffTimeZone: destination-local-time
maxParcelWeightKg: 30
targetStatus: proposed
- code: EXPRESS
deliveryDays: "1-2"
deliveryDayType: business-days
deliveryPeriodStarts: carrier-acceptance
cutOffTime: "14:00"
cutOffTimeZone: destination-local-time
maxParcelWeightKg: 20
targetStatus: proposed
- code: NEXT_DAY
deliveryDays: "1"
deliveryDayType: business-days
deliveryPeriodStarts: carrier-acceptance
cutOffTime: "12:00"
cutOffTimeZone: destination-local-time
maxParcelWeightKg: 10
targetStatus: proposed
collection:
window: "17:00-19:00"
timeZone: BookWorm warehouse local time
days: [MON, TUE, WED, THU, FRI]
targetStatus: proposed
penalties:
lateDeliveryCreditPercent: 15
lostParcelReimbursement: full-value
status: proposed
terms: >-
Define the credit basis, claim window, evidence requirements, exclusions,
and reimbursement cap in the signed carrier contract.
support:
escalationEmail: engineering@bookworm.com
responseTimeHours: 4
responseTimeBasis: business-hours
targetStatus: proposed
assumptions:
- Delivery estimates are measured from carrier acceptance, not Order creation.
- The carrier name is a BookWorm placeholder, not a confirmed provider.
- The existing BookWorm engineering contact is used as a provisional escalation email; confirm the operational owner before signing.
- The delivery area means the domestic destinations enabled at checkout; confirm the actual country and coverage with the carrier.
- Confirm local business-day calendars, warehouse time zone, parcel dimensions, and holiday handling with the carrier.
- The escalation contact, service targets, and remedies are proposed terms and are not binding until agreed in the signed contract.
---
id: order-orchestration
name: Order Orchestration
version: 1.0.0
summary: |
Message-driven Finance workflow service that coordinates post-checkout basket
cleanup and order notifications using Durable Task Scheduler and Kafka.
owners:
- commerce-fulfillment-team
badges:
- content: Internal
backgroundColor: gray
textColor: gray
- content: Event-driven
backgroundColor: orange
textColor: orange
diagrams:
- id: order-lifecycle
version: 1.0.0
- id: checkout-interaction
version: 1.0.0
receives:
- id: UserCheckedOutIntegrationEvent
version: 1.0.0
from:
- id: bookworm.{env}.ordering.user-checked-out
version: 1.0.0
- id: OrderStatusChangedToCompleteIntegrationEvent
version: 1.0.0
group: Order Status Changes
from:
- id: bookworm.{env}.ordering.order-status-change-to-complete
version: 1.0.0
- id: OrderStatusChangedToCancelIntegrationEvent
version: 1.0.0
group: Order Status Changes
from:
- id: bookworm.{env}.ordering.order-status-change-to-cancel
version: 1.0.0
- id: BasketDeletedCompleteIntegrationEvent
version: 1.0.0
group: Basket Cleanup Outcomes
from:
- id: bookworm.{env}.basket.delete-complete
version: 1.0.0
- id: BasketDeletedFailedIntegrationEvent
version: 1.0.0
group: Basket Cleanup Outcomes
from:
- id: bookworm.{env}.basket.delete-failed
version: 1.0.0
sends:
- id: PlaceOrderCommand
version: 1.0.0
group: Basket Coordination
to:
- id: bookworm.{env}.finance.place-order
version: 1.0.0
- id: DeleteBasketCompleteCommand
version: 1.0.0
group: Basket Coordination
to:
- id: bookworm.{env}.finance.delete-basket-complete
version: 1.0.0
- id: DeleteBasketFailedCommand
version: 1.0.0
group: Basket Coordination
to:
- id: bookworm.{env}.finance.delete-basket-failed
version: 1.0.0
- id: CompleteOrderCommand
version: 1.0.0
group: Order Notifications
to:
- id: bookworm.{env}.finance.complete-order
version: 1.0.0
- id: CancelOrderCommand
version: 1.0.0
group: Order Notifications
to:
- id: bookworm.{env}.finance.cancel-order
version: 1.0.0
styles:
icon: /icons/compute/function.svg
specifications:
- type: asyncapi
path: asyncapi-v1.yml
name: AsyncAPI V1
repository:
language: C#
url: "https://github.com/foxminchan/BookWorm"
---
## Service Responsibility & Boundary
Order Orchestration is an internal durable workflow worker within the [[domain|ordering]] domain that coordinates post-checkout basket cleanup retries and order lifecycle email commands over Kafka. It tracks one orchestration instance per Order ID in Azure Durable Task Scheduler, delegating authoritative Order state to [[service|order-api]], basket deletion to [[service|basket-api]], and email delivery to [[service|notification-api]]. It does not process payments or expose HTTP or gRPC endpoints.
## Service Profile
| Property | Value |
| :---------------------------------------- | :----------------------------------------------------------------------------------------------------- |
| **Bounded Context / Domain** | [[domain\|ordering]] |
| **Owner Team** | [[team\|commerce-fulfillment-team]] |
| **Runtime Style** | Durable Orchestrator & Async Kafka Worker |
| **Public / Gateway Exposure** | Internal Only (no HTTP or gRPC API) |
| **Authentication & Authorization Policy** | Internal worker; Azure Managed Identity RBAC for Durable Task Scheduler |
| **Owned Data Store(s)** | Azure Durable Task Scheduler (orchestration state and timers, keyed by Order ID) |
| **Key Resilience / Idempotency Pattern** | Order-ID correlation deduplicating checkout events and bounded 30-minute retry timers (max 3 attempts) |
## Contracts & Data Ownership
Order Orchestration owns only per-order coordination saga state (`Placed`, `BasketDeletionFailed`, `Completed`, `Cancelled`).
:::note
Despite the Finance system name, this service does **not** authorize or settle payments. [[service|order-api]] remains the sole authority for Order aggregates and business status; timeout exhaustion in Order Orchestration marks only the coordination workflow cancelled without cancelling the Order itself.
:::
:::warning
Both [[service|basket-api]] and [[service|notification-api]] consume [[command|PlaceOrderCommand]] on the same topic. When a durable timeout reissues [[command|PlaceOrderCommand]], both consumers receive the retry, which can generate an additional placement email.
:::
## Architecture Visualizations & Specifications
### Saga Coordination Context
### Service Interactions
## Attached Resources & Related Docs
- [[doc|platform/006-api-and-contracts]] — Consolidated service, HTTP, gRPC, and Kafka directory.
- [[service|order-api]] — Authoritative Order lifecycle service.
- [[service|basket-api]] — Consumer of [[command|PlaceOrderCommand]] for basket cleanup.
- [[service|notification-api]] — Consumer of order email commands.
- [[diagram|order-lifecycle]] — Order status transitions and saga separation.
- [[doc|domains/bookworm/subdomains/ordering/guides/02-understand-order-and-finance-status]] — Lifecycle separation between Order status and Finance orchestration.
## Raw Schema:asyncapi-v1.yml
asyncapi: 3.1.0
info:
title: Order Orchestration integration messages
version: 1.0.0
description: |
AsyncAPI contract for Finance's Order Orchestration service. The service
consumes checkout, Order lifecycle, and basket-cleanup messages, then
publishes basket-cleanup outcomes and order-notification commands.
Payload schemas describe camelCase JSON data inside BookWorm's
CloudEvents-compatible envelope, not the complete transport envelope.
Message identities are the BookWorm.Contracts types represented below.
All topics use the deployment environment parameter.
The place-order command is shared with both Basket and Notification:
Basket consumes it to delete the submitted basket, while Notification
consumes it to submit a new-order email. Re-publishing on timeout can
repeat both consumers' work; this contract does not promise exactly-once
processing or email delivery.
defaultContentType: application/cloudevents+json
channels:
userCheckedOut:
address: bookworm.{env}.ordering.user-checked-out
description: Ordering publishes checkout details to start Finance coordination.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
userCheckedOut:
$ref: "#/components/messages/UserCheckedOutIntegrationEvent"
orderStatusChangedToComplete:
address: bookworm.{env}.ordering.order-status-change-to-complete
description: Ordering publishes this event after an Order transitions to Completed.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
orderStatusChangedToComplete:
$ref: "#/components/messages/OrderStatusChangedToCompleteIntegrationEvent"
orderStatusChangedToCancel:
address: bookworm.{env}.ordering.order-status-change-to-cancel
description: Ordering publishes this event after an Order transitions to Cancelled.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
orderStatusChangedToCancel:
$ref: "#/components/messages/OrderStatusChangedToCancelIntegrationEvent"
basketDeleteComplete:
address: bookworm.{env}.basket.delete-complete
description: Basket publishes this event after successfully deleting the submitted basket.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
basketDeleteComplete:
$ref: "#/components/messages/BasketDeletedCompleteIntegrationEvent"
basketDeleteFailed:
address: bookworm.{env}.basket.delete-failed
description: Basket publishes this event when it cannot delete the submitted basket.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
basketDeleteFailed:
$ref: "#/components/messages/BasketDeletedFailedIntegrationEvent"
placeOrder:
address: bookworm.{env}.finance.place-order
description: Finance asks Basket to delete the checkout basket; Notification also consumes this command for a new-order email.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
placeOrder:
$ref: "#/components/messages/PlaceOrderCommand"
deleteBasketComplete:
address: bookworm.{env}.finance.delete-basket-complete
description: Finance reports successful basket cleanup to Ordering.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
deleteBasketComplete:
$ref: "#/components/messages/DeleteBasketCompleteCommand"
deleteBasketFailed:
address: bookworm.{env}.finance.delete-basket-failed
description: Finance reports failed basket cleanup to Ordering for recovery.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
deleteBasketFailed:
$ref: "#/components/messages/DeleteBasketFailedCommand"
completeOrder:
address: bookworm.{env}.finance.complete-order
description: Finance asks Notification to send an Order-completed email.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
completeOrder:
$ref: "#/components/messages/CompleteOrderCommand"
cancelOrder:
address: bookworm.{env}.finance.cancel-order
description: Finance asks Notification to send an Order-cancelled email.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
cancelOrder:
$ref: "#/components/messages/CancelOrderCommand"
operations:
receiveUserCheckedOut:
action: receive
channel:
$ref: "#/channels/userCheckedOut"
summary: Start checkout coordination
description: |
Creates a persisted saga correlated by Order ID, publishes PlaceOrderCommand,
and schedules the first basket-cleanup timeout.
messages:
- $ref: "#/channels/userCheckedOut/messages/userCheckedOut"
receiveOrderStatusChangedToComplete:
action: receive
channel:
$ref: "#/channels/orderStatusChangedToComplete"
summary: Handle an Order completion
description: |
Marks the saga Completed and publishes CompleteOrderCommand when both
recipient name and email are present.
messages:
- $ref: "#/channels/orderStatusChangedToComplete/messages/orderStatusChangedToComplete"
receiveOrderStatusChangedToCancel:
action: receive
channel:
$ref: "#/channels/orderStatusChangedToCancel"
summary: Handle an explicit Order cancellation
description: |
Marks the saga Cancelled and publishes CancelOrderCommand when both
recipient name and email are present.
messages:
- $ref: "#/channels/orderStatusChangedToCancel/messages/orderStatusChangedToCancel"
receiveBasketDeleteComplete:
action: receive
channel:
$ref: "#/channels/basketDeleteComplete"
summary: Handle successful basket cleanup
description: |
Publishes DeleteBasketCompleteCommand to Ordering. Successful cleanup
does not complete the Order or finish the saga.
messages:
- $ref: "#/channels/basketDeleteComplete/messages/basketDeleteComplete"
receiveBasketDeleteFailed:
action: receive
channel:
$ref: "#/channels/basketDeleteFailed"
summary: Handle failed basket cleanup
description: |
Marks the saga BasketDeletionFailed, completes it, and publishes
DeleteBasketFailedCommand to Ordering. Ordering may soft-delete the
Order; its business status is not changed by this outcome.
messages:
- $ref: "#/channels/basketDeleteFailed/messages/basketDeleteFailed"
sendPlaceOrder:
action: send
channel:
$ref: "#/channels/placeOrder"
summary: Request basket cleanup and order-placement notification
description: |
Published when checkout coordination starts and re-published when a
timeout triggers a retry. Basket deletes the basket and Notification
processes the same command as an email request.
messages:
- $ref: "#/channels/placeOrder/messages/placeOrder"
sendDeleteBasketComplete:
action: send
channel:
$ref: "#/channels/deleteBasketComplete"
summary: Report successful basket cleanup to Ordering
messages:
- $ref: "#/channels/deleteBasketComplete/messages/deleteBasketComplete"
sendDeleteBasketFailed:
action: send
channel:
$ref: "#/channels/deleteBasketFailed"
summary: Report failed basket cleanup to Ordering
messages:
- $ref: "#/channels/deleteBasketFailed/messages/deleteBasketFailed"
sendCompleteOrder:
action: send
channel:
$ref: "#/channels/completeOrder"
summary: Request an Order-completed email
description: |
Published after Ordering reports the Order's explicit Completed status,
when recipient name and email are present.
messages:
- $ref: "#/channels/completeOrder/messages/completeOrder"
sendCancelOrder:
action: send
channel:
$ref: "#/channels/cancelOrder"
summary: Request an Order-cancelled email
description: |
Published after Ordering reports the Order's explicit Cancelled status,
or after the Finance saga exhausts basket-cleanup retries. Timeout
exhaustion cancels only the Finance saga; it does not cancel the Order
in Ordering.
messages:
- $ref: "#/channels/cancelOrder/messages/cancelOrder"
components:
parameters:
env:
description: BookWorm deployment environment transformed to kebab case by the Kafka topic router.
enum:
- development
- staging
- production
default: development
messages:
UserCheckedOutIntegrationEvent:
name: UserCheckedOutIntegrationEvent
title: User checked out
summary: An Order was placed and checkout details are ready for Finance coordination.
description: "Wolverine message identity: BookWorm.Contracts.UserCheckedOutIntegrationEvent."
contentType: application/json
payload:
$ref: "#/components/schemas/OrderLifecyclePayload"
examples:
- name: checkedOut
payload:
id: "019a1c00-0000-7000-8000-000000000001"
creationDate: "2026-11-01T14:00:00Z"
orderId: "019a1c00-0000-7000-8000-000000000020"
basketId: "019a1c00-0000-7000-8000-000000000010"
fullName: Example Customer
email: customer@example.com
totalMoney: 49.95
OrderStatusChangedToCompleteIntegrationEvent:
name: OrderStatusChangedToCompleteIntegrationEvent
title: Order completed
summary: An Order transitioned from New to Completed.
description: "Wolverine message identity: BookWorm.Contracts.OrderStatusChangedToCompleteIntegrationEvent."
contentType: application/json
payload:
$ref: "#/components/schemas/OrderLifecyclePayload"
OrderStatusChangedToCancelIntegrationEvent:
name: OrderStatusChangedToCancelIntegrationEvent
title: Order cancelled
summary: An Order transitioned from New to Cancelled.
description: "Wolverine message identity: BookWorm.Contracts.OrderStatusChangedToCancelIntegrationEvent."
contentType: application/json
payload:
$ref: "#/components/schemas/OrderLifecyclePayload"
BasketDeletedCompleteIntegrationEvent:
name: BasketDeletedCompleteIntegrationEvent
title: Basket deletion completed
summary: Basket successfully deleted the submitted basket after checkout.
description: "Wolverine message identity: BookWorm.Contracts.BasketDeletedCompleteIntegrationEvent."
contentType: application/json
payload:
$ref: "#/components/schemas/BasketDeletedCompletePayload"
BasketDeletedFailedIntegrationEvent:
name: BasketDeletedFailedIntegrationEvent
title: Basket deletion failed
summary: Basket could not delete the submitted basket after checkout.
description: "Wolverine message identity: BookWorm.Contracts.BasketDeletedFailedIntegrationEvent."
contentType: application/json
payload:
$ref: "#/components/schemas/BasketDeletedFailedPayload"
PlaceOrderCommand:
name: PlaceOrderCommand
title: Place order
summary: Shared Finance command consumed by Basket for cleanup and Notification for a new-order email.
description: "Wolverine message identity: BookWorm.Contracts.PlaceOrderCommand."
contentType: application/json
payload:
$ref: "#/components/schemas/PlaceOrderPayload"
examples:
- name: placeOrder
payload:
id: "019a1c00-0000-7000-8000-000000000002"
creationDate: "2026-11-01T14:00:01Z"
basketId: "019a1c00-0000-7000-8000-000000000010"
orderId: "019a1c00-0000-7000-8000-000000000020"
fullName: Example Customer
email: customer@example.com
totalMoney: 49.95
DeleteBasketCompleteCommand:
name: DeleteBasketCompleteCommand
title: Basket deletion completed
summary: Finance reports successful basket cleanup to Ordering.
description: "Wolverine message identity: BookWorm.Contracts.DeleteBasketCompleteCommand."
contentType: application/json
payload:
$ref: "#/components/schemas/DeleteBasketCompletePayload"
DeleteBasketFailedCommand:
name: DeleteBasketFailedCommand
title: Basket deletion failed
summary: Finance reports failed basket cleanup to Ordering for recovery.
description: "Wolverine message identity: BookWorm.Contracts.DeleteBasketFailedCommand."
contentType: application/json
payload:
$ref: "#/components/schemas/DeleteBasketFailedPayload"
CompleteOrderCommand:
name: CompleteOrderCommand
title: Complete order
summary: Shared Finance command consumed by Notification to request a completed-order email.
description: "Wolverine message identity: BookWorm.Contracts.CompleteOrderCommand."
contentType: application/json
payload:
$ref: "#/components/schemas/OrderNotificationPayload"
CancelOrderCommand:
name: CancelOrderCommand
title: Cancel order
summary: Shared Finance command consumed by Notification to request a canceled-order email.
description: "Wolverine message identity: BookWorm.Contracts.CancelOrderCommand."
contentType: application/json
payload:
$ref: "#/components/schemas/OrderNotificationPayload"
schemas:
OrderLifecyclePayload:
type: object
additionalProperties: false
required:
- id
- creationDate
- orderId
- basketId
- fullName
- email
- totalMoney
properties:
id:
$ref: "#/components/schemas/EventId"
creationDate:
$ref: "#/components/schemas/CreationDate"
orderId:
$ref: "#/components/schemas/OrderId"
basketId:
type: string
format: uuid
description: Basket identifier in the event payload. The current Order mapper supplies the Buyer's ID for this field.
fullName:
$ref: "#/components/schemas/FullName"
email:
$ref: "#/components/schemas/Email"
totalMoney:
$ref: "#/components/schemas/TotalMoney"
BasketDeletedCompletePayload:
type: object
additionalProperties: false
required:
- id
- creationDate
- orderId
- basketId
- totalMoney
properties:
id:
$ref: "#/components/schemas/EventId"
creationDate:
$ref: "#/components/schemas/CreationDate"
orderId:
$ref: "#/components/schemas/OrderId"
basketId:
type: string
format: uuid
description: Identifier of the basket deleted during checkout cleanup.
totalMoney:
$ref: "#/components/schemas/TotalMoney"
BasketDeletedFailedPayload:
type: object
additionalProperties: false
required:
- id
- creationDate
- orderId
- basketId
- totalMoney
properties:
id:
$ref: "#/components/schemas/EventId"
creationDate:
$ref: "#/components/schemas/CreationDate"
orderId:
$ref: "#/components/schemas/OrderId"
basketId:
type: string
format: uuid
description: Identifier of the basket whose cleanup failed.
email:
$ref: "#/components/schemas/Email"
totalMoney:
$ref: "#/components/schemas/TotalMoney"
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 used by Basket to delete the checkout basket.
orderId:
$ref: "#/components/schemas/OrderId"
fullName:
$ref: "#/components/schemas/FullName"
email:
$ref: "#/components/schemas/Email"
totalMoney:
$ref: "#/components/schemas/TotalMoney"
DeleteBasketCompletePayload:
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"
totalMoney:
$ref: "#/components/schemas/TotalMoney"
DeleteBasketFailedPayload:
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: Identifier of the basket whose cleanup failed.
email:
$ref: "#/components/schemas/Email"
orderId:
$ref: "#/components/schemas/OrderId"
totalMoney:
$ref: "#/components/schemas/TotalMoney"
OrderNotificationPayload:
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 message is constructed.
CreationDate:
type: string
format: date-time
description: UTC timestamp when the integration message is constructed.
OrderId:
type: string
format: uuid
description: Order identifier used to correlate saga state and partition messages.
FullName:
type:
- string
- "null"
description: Customer display name, when available.
Email:
type:
- string
- "null"
format: email
description: Customer email address, when available. Notification skips blank addresses.
TotalMoney:
type: number
description: C# decimal total associated with the Order. No currency is specified in this contract.
---
id: presidio-api
name: Presidio API
version: 1.0.0
summary: |
External HTTP sidecar API for detecting PII in text and anonymizing detected
entities in the Chat and Rating AI agent pipelines.
externalSystem: true
owners:
- platform-engineering-team
badges:
- content: External
backgroundColor: purple
textColor: purple
- content: HTTP API
backgroundColor: teal
textColor: teal
receives:
- id: AnalyzeText
version: 1.0.0
group: PII Processing
- id: AnonymizeText
version: 1.0.0
group: PII Processing
- id: GetRecognizers
version: 1.0.0
group: Presidio Configuration Queries
- id: GetSupportedEntities
version: 1.0.0
group: Presidio Configuration Queries
- id: GetAnonymizers
version: 1.0.0
group: Presidio Configuration Queries
styles:
icon: /icons/third-party/presidio.svg
specifications:
- type: openapi
path: https://raw.githubusercontent.com/data-privacy-stack/presidio/refs/heads/main/docs/api-docs/api-docs.yml
name: OpenAPI V2
---
## Integration Purpose & Boundary
Presidio provides external sidecar HTTP services (Analyzer and Anonymizer) for detecting and redacting personally identifiable information (PII) in text before and after AI model execution. BookWorm's deterministic PII middleware invokes Presidio on behalf of [[service|chat-api]] and [[service|rating-api]] agents so foundation models cannot bypass privacy screening.
:::warning
Although the attached upstream OpenAPI specification documents discovery endpoints (`GetRecognizers`, `GetSupportedEntities`, `GetAnonymizers`), BookWorm's runtime integration invokes only [[command|AnalyzeText]] and [[command|AnonymizeText]]—targeting email addresses, phone numbers, and credit-card numbers. All screening executes **fail-closed**: any timeout or non-success response aborts the AI turn rather than sending unscreened text.
:::
## Integration Profile
| Property | Value |
| :------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Provider / Sidecar** | Microsoft Presidio (`presidio-analyzer` and `presidio-anonymizer` sidecar containers) |
| **BookWorm Consumers** | [[service\|chat-api]] ([[agent\|book-agent]], [[agent\|book-catalog-researcher]], [[agent\|book-recommendation-researcher]], [[agent\|qa-agent]]) and [[service\|rating-api]] ([[agent\|rating-agent]]) |
| **Runtime Transport & Protocol** | Internal HTTP/HTTPS via service discovery (not routed via public API Gateway) |
| **Auth / Credential Boundary** | Internal cluster network boundary; no public exposure or customer credentials forwarded |
| **Data / PII Sensitivity** | Critical — processes raw customer prompts, review text, and model responses; never log raw inputs, outputs, or detected PII spans |
| **Failure / Fallback Behavior** | Fail-closed — connection errors, timeouts, or non-success status codes propagate and fail the request immediately |
## Visualizations & Specifications
### Privacy Screening Context
### Service Interactions
## Related Documentation
- [[doc|platform/006-api-and-contracts]] — Consolidated service and contract index.
- [[service|chat-api]] — Conversational consumer of Presidio PII middleware.
- [[service|rating-api]] — Review summarization consumer of Presidio PII middleware.
- [[command|AnalyzeText]] — Request and response contract for PII detection.
- [[command|AnonymizeText]] — Request and response contract for PII redaction.
- [[system|data-privacy]] — External Data Privacy system boundary.
---
id: rating-api
name: Rating API
version: 1.0.0
summary: |
Internal HTTP and A2A gRPC service for collecting, listing, deleting, and
summarizing customer feedback for Catalog books.
readsFrom:
- id: rating-database
version: 1.0.0
- id: rating-cache
version: 1.0.0
writesTo:
- id: rating-database
version: 1.0.0
- id: rating-cache
version: 1.0.0
entities:
- id: feedback
version: 1.0.0
owners:
- catalog-experience-team
badges:
- content: Internal
backgroundColor: gray
textColor: gray
- content: HTTP API
backgroundColor: teal
textColor: teal
diagrams:
- id: rating-summarizer-workflow
version: 1.0.0
receives:
- id: CreateFeedback
version: 1.0.0
group: Feedback Commands
- id: DeleteFeedback
version: 1.0.0
group: Feedback Commands
- id: ListFeedbacks
version: 1.0.0
group: Feedback Queries
- id: SummarizeFeedback
version: 1.0.0
group: Feedback Queries
- id: BookUpdatedRatingFailedIntegrationEvent
version: 1.0.0
from:
- id: "bookworm.{env}.catalog.book-update-rating-failed"
parameters:
env: development
sends:
- id: FeedbackCreatedIntegrationEvent
version: 1.0.0
group: Feedback Events
to:
- id: "bookworm.{env}.rating.feedback-create"
parameters:
env: development
- id: FeedbackDeletedIntegrationEvent
version: 1.0.0
group: Feedback Events
to:
- id: "bookworm.{env}.rating.feedback-delete"
parameters:
env: development
styles:
icon: /icons/languages/dotnet.svg
specifications:
- type: openapi
path: openapi-v1.yaml
name: OpenAPI V1
- type: asyncapi
path: asyncapi-v1.yml
name: AsyncAPI V1
attachments:
- url: https://foxminchan.github.io/BookWorm/docs/domains/reviews/1.0.0/engineering/feedback-contracts-and-integration
title: Feedback contracts and integration
description: HTTP routes, validation rules, Cosmos DB mapping, and Kafka contracts.
type: documentation
- url: https://foxminchan.github.io/BookWorm/docs/domains/reviews/1.0.0/guides/feedback-lifecycle
title: Feedback lifecycle
description: End-to-end lifecycle of customer feedback and its derived rating projection.
type: guides
- url: https://foxminchan.github.io/BookWorm/docs/domains/reviews/1.0.0/runbooks/catalog-rating-projection-failure
title: Recover a failed Catalog rating projection
description: Operational triage for BookUpdatedRatingFailedIntegrationEvent.
type: runbooks
repository:
language: C#
url: "https://github.com/foxminchan/BookWorm"
---
## Service Responsibility & Boundary
Rating API is the system of record within the [[domain|reviews]] domain for individual customer [[entity|feedback]] records on Catalog books. It exposes versioned HTTP endpoints for feedback management and read-time AI summarization, hosts BookWorm's Agent-to-Agent (A2A) gRPC server for [[agent|rating-agent]], and synchronizes rating deltas with [[service|catalog-api]] over Kafka. Book metadata and derived rating totals remain owned by [[service|catalog-api]].
## Service Profile
| Property | Value |
| :---------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context / Domain** | [[domain\|reviews]] |
| **Owner Team** | [[team\|catalog-experience-team]] |
| **Runtime Style** | REST API, A2A gRPC Server, and Async Kafka Producer/Consumer |
| **Public / Gateway Exposure** | Yes via API Gateway (HTTP) and Internal Only (A2A gRPC) |
| **Authentication & Authorization Policy** | Microsoft Entra ID JWT and Entra Agent Identity via [[system\|identity-provider]]; `admin` policy for deletion, `rating_read` scope for A2A gRPC |
| **Owned Data Store(s)** | [[container\|rating-database]] (Azure Cosmos DB partitioned by book ID), [[container\|rating-cache]] (Redis read cache & idempotency) |
| **Key Resilience / Idempotency Pattern** | Compensating delete on Catalog rejection, fail-closed PII screening, per-user rate limiting, and dead-letter routing on [[channel\|bookworm.{env}.rating.dead-letter-queue]] |
## Contracts & Data Ownership
Rating API owns the [[entity|feedback]] aggregate in [[container|rating-database]] and enforces uniqueness per `(bookId, firstName, lastName)`.
:::note
Read-time summarization via [[agent|rating-agent]] retrieves book metadata and analysis prompts from [[service|mcp-server]], reads raw reviews in-process under a rate cap, and screens inputs and outputs fail-closed through [[service|presidio-api]] without mutating stored feedback.
:::
:::warning
If [[service|catalog-api]] emits [[event|BookUpdatedRatingFailedIntegrationEvent]] because a reviewed book does not exist, Rating API executes an idempotent compensating delete on the orphaned feedback record.
:::
## Architecture Visualizations & Specifications
### Rating API Context
### Service Interactions
### Owned Entities
## Attached Resources & Related Docs
- [[doc|platform/006-api-and-contracts]] — Consolidated service, HTTP, gRPC, and Kafka directory.
- [[agent|rating-agent]] — AI review summarization agent contract.
- [[container|rating-database]] — Azure Cosmos DB persistence reference.
- [[container|rating-cache]] — Redis caching and idempotency reference.
- [[diagram|rating-summarizer-workflow]] — Read-time feedback summarization flow.
## Raw Schema:openapi-v1.yaml
openapi: 3.2.0
info:
title: Rating Service API
description: "Handles the collection, storage, and aggregation of user feedback and ratings for books on the BookWorm platform"
contact:
name: BookWorm Engineering
url: https://github.com/foxminchan
email: engineering@bookworm.com
license:
name: MIT
url: https://opensource.org/licenses/MIT
version: "1.0"
summary: A service responsible for managing user feedback and ratings for books on the BookWorm platform
paths:
"/api/v1/feedbacks/{id}/summarize":
get:
tags:
- Feedback
summary: Summarize Feedback
description: Summarize the feedback for a book by its ID
operationId: SummarizeFeedbackEndpoint
parameters:
- name: id
in: path
description: The unique identifier of the book to be summarized
required: true
schema:
type: string
responses:
"200":
description: OK
content:
application/json:
schema:
$ref: "#/components/schemas/SummarizeResult"
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
/api/v1/feedbacks:
get:
tags:
- Feedback
summary: List Feedbacks
description: List feedbacks for a book with pagination and filtering
operationId: ListFeedbacksEndpoint
parameters:
- name: BookId
in: query
description: The ID of the book to get feedback for
required: true
schema:
type: string
format: uuid
- name: PageIndex
in: query
description: Number of items to return in a single page of results
schema:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int32
default: 1
- name: PageSize
in: query
description: Number of items to return in a single page of results
schema:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int32
default: 20
- name: OrderBy
in: query
description: Property to order results by
schema:
type: string
default: Rating
- name: IsDescending
in: query
description: Whether to order results in descending order
schema:
type: boolean
default: false
responses:
"200":
description: OK
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/FeedbackDto"
"400":
description: Bad Request
content:
application/problem+json:
schema:
$ref: "#/components/schemas/HttpValidationProblemDetails"
post:
tags:
- Feedback
summary: Create Feedback
description: Create a new feedback
operationId: CreateFeedbackEndpoint
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/CreateFeedbackCommand"
required: true
responses:
"200":
description: OK
content:
application/json:
schema:
$ref: "#/components/schemas/FeedbackId"
"400":
description: Bad Request
content:
application/problem+json:
schema:
$ref: "#/components/schemas/HttpValidationProblemDetails"
"/api/v1/feedbacks/{id}":
delete:
tags:
- Feedback
summary: Delete Feedback
description: Delete a feedback if it exists
operationId: DeleteFeedbackEndpoint
parameters:
- name: id
in: path
description: The unique identifier of the feedback to be deleted
required: true
schema:
type: string
responses:
"204":
description: No Content
"404":
description: Not Found
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ProblemDetails"
components:
schemas:
CreateFeedbackCommand:
required:
- bookId
- firstName
- lastName
- comment
- rating
type: object
properties:
bookId:
type: string
format: uuid
firstName:
type:
- "null"
- string
lastName:
type:
- "null"
- string
comment:
type:
- "null"
- string
rating:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int32
FeedbackDto:
required:
- id
- firstName
- lastName
- comment
- rating
- bookId
type: object
properties:
id:
type: string
format: uuid
firstName:
type:
- "null"
- string
lastName:
type:
- "null"
- string
comment:
type:
- "null"
- string
rating:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int32
bookId:
type: string
format: uuid
FeedbackId:
type: string
format: uuid
HttpValidationProblemDetails:
type: object
properties:
type:
type:
- "null"
- string
title:
type:
- "null"
- string
status:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- "null"
- integer
- string
format: int32
detail:
type:
- "null"
- string
instance:
type:
- "null"
- string
errors:
type: object
additionalProperties:
type: array
items:
type: string
ProblemDetails:
type: object
properties:
type:
type:
- "null"
- string
title:
type:
- "null"
- string
status:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- "null"
- integer
- string
format: int32
detail:
type:
- "null"
- string
instance:
type:
- "null"
- string
RatingClassification:
enum:
- NoData
- Bad
- Good
- TopRated
default: NoData
SummarizeResult:
required:
- summary
type: object
properties:
summary:
type: string
classification:
$ref: "#/components/schemas/RatingClassification"
averageRating:
pattern: "^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$"
type:
- "null"
- number
- string
format: double
reviewCount:
pattern: "^-?(?:0|[1-9]\\d*)$"
type:
- integer
- string
format: int32
default: 0
evidence:
type: string
default: ""
confidence:
type: string
default: ""
tags:
- name: Feedback
## Raw Schema:asyncapi-v1.yml
---
asyncapi: 3.1.0
info:
title: Rating API integration events
version: 1.0.0
description: |
AsyncAPI contract for the Rating service's Kafka integration events.
Rating publishes feedback lifecycle events for Catalog and consumes
compensation events when Catalog cannot apply a rating update.
defaultContentType: application/cloudevents+json
channels:
feedbackCreated:
address: bookworm.{env}.rating.feedback-create
description: Rating service publishes this event when feedback is created.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
feedbackCreated:
$ref: "#/components/messages/FeedbackCreatedIntegrationEvent"
feedbackDeleted:
address: bookworm.{env}.rating.feedback-delete
description: Rating service publishes this event when feedback is deleted.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
feedbackDeleted:
$ref: "#/components/messages/FeedbackDeletedIntegrationEvent"
bookUpdatedRatingFailed:
address: bookworm.{env}.catalog.book-update-rating-failed
description: Catalog publishes this event when a feedback-created event cannot update a book.
parameters:
env:
$ref: "#/components/parameters/env"
messages:
bookUpdatedRatingFailed:
$ref: "#/components/messages/BookUpdatedRatingFailedIntegrationEvent"
operations:
sendFeedbackCreated:
action: send
channel:
$ref: "#/channels/feedbackCreated"
summary: Publish feedback-created events
messages:
- $ref: "#/channels/feedbackCreated/messages/feedbackCreated"
sendFeedbackDeleted:
action: send
channel:
$ref: "#/channels/feedbackDeleted"
summary: Publish feedback-deleted events
messages:
- $ref: "#/channels/feedbackDeleted/messages/feedbackDeleted"
receiveBookUpdatedRatingFailed:
action: receive
channel:
$ref: "#/channels/bookUpdatedRatingFailed"
summary: Consume failed rating update notifications
messages:
- $ref: "#/channels/bookUpdatedRatingFailed/messages/bookUpdatedRatingFailed"
components:
parameters:
env:
description: BookWorm deployment environment.
enum:
- development
- staging
- production
default: development
messages:
FeedbackCreatedIntegrationEvent:
name: FeedbackCreatedIntegrationEvent
title: Feedback created
summary: A new rating was created for a book.
contentType: application/json
payload:
$ref: "#/components/schemas/FeedbackCreatedPayload"
FeedbackDeletedIntegrationEvent:
name: FeedbackDeletedIntegrationEvent
title: Feedback deleted
summary: An existing rating was deleted from a book.
contentType: application/json
payload:
$ref: "#/components/schemas/FeedbackDeletedPayload"
BookUpdatedRatingFailedIntegrationEvent:
name: BookUpdatedRatingFailedIntegrationEvent
title: Book rating update failed
summary: Catalog could not update a book rating for the feedback event.
contentType: application/json
payload:
$ref: "#/components/schemas/BookUpdatedRatingFailedPayload"
schemas:
FeedbackCreatedPayload:
type: object
additionalProperties: false
required:
- bookId
- rating
- feedbackId
properties:
bookId:
type: string
format: uuid
description: Identifier of the book whose rating summary changes.
rating:
type: integer
minimum: 0
maximum: 5
description: Rating value added to the book.
feedbackId:
type: string
format: uuid
description: Identifier of the feedback record.
FeedbackDeletedPayload:
type: object
additionalProperties: false
required:
- bookId
- rating
- feedbackId
properties:
bookId:
type: string
format: uuid
description: Identifier of the book whose rating summary changes.
rating:
type: integer
minimum: 0
maximum: 5
description: Rating value removed from the book.
feedbackId:
type: string
format: uuid
description: Identifier of the deleted feedback record.
BookUpdatedRatingFailedPayload:
type: object
additionalProperties: false
required:
- feedbackId
properties:
feedbackId:
type: string
format: uuid
description: Identifier of the feedback that could not be applied.
---
id: scheduler-service
name: Scheduler Service
version: 1.0.0
summary: |
Single-host Quartz.NET job execution engine and operational dashboard UI
for scheduling recurring platform jobs and inspecting execution history.
styles:
icon: /icons/languages/dotnet.svg
owners:
- platform-engineering-team
badges:
- content: Internal
backgroundColor: gray
textColor: gray
- content: Operations
backgroundColor: yellow
textColor: yellow
sends:
- id: ProcessVectorBatchIntegrationEvent
version: 1.0.0
group: Catalog Maintenance
to:
- id: scheduler.process-vector-batch
version: 1.0.0
readsFrom:
- id: scheduler-database
version: 1.0.0
writesTo:
- id: scheduler-database
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
Scheduler Service is the Quartz.NET job host and paired administrative dashboard within the [[domain|platform]] domain that manages durable UTC cron schedules, emits liveness heartbeats, and dispatches recurring catalog vector ingestion triggers over Kafka. It persists schedules and 30-day execution history in [[container|scheduler-database]], while delegating actual vector indexing to [[service|catalog-ingestion]].
## Service Profile
| Property | Value |
| :---------------------------------------- | :------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context / Domain** | [[domain\|platform]] |
| **Owner Team** | [[team\|platform-engineering-team]] |
| **Runtime Style** | Scheduled Job Host & Administrative Dashboard UI |
| **Public / Gateway Exposure** | Admin UI exposed via OIDC; job host is Internal Only (not routed via API Gateway) |
| **Authentication & Authorization Policy** | Microsoft Entra ID OIDC requiring the `admin` app role for the operator dashboard; internal worker for job execution |
| **Owned Data Store(s)** | [[container\|scheduler-database]] (Quartz schedule state, 30-day execution history, and transactional outbox) |
| **Key Resilience / Idempotency Pattern** | Non-concurrent job execution, durable misfire recovery (`FireOnceNow`), and transactional outbox publishing |
## Contracts & Data Ownership
Scheduler Service owns schedule definitions, trigger state, and execution history in [[container|scheduler-database]]. Every five minutes UTC, it publishes [[event|ProcessVectorBatchIntegrationEvent]] to [[channel|scheduler.process-vector-batch]] via its transactional outbox for [[service|catalog-ingestion]] to consume.
:::note
A successful job firing proves only that the trigger event was dispatched—not that downstream indexing completed. Operators should inspect pending vector update counts in [[container|catalog-database]] alongside [[service|catalog-ingestion]] logs when diagnosing search lag.
:::
:::warning
Never store credentials, authorization headers, notification bodies, or personal data in Quartz job metadata or trigger data maps.
:::
## Architecture Visualizations & Specifications
### Scheduler Host Context
### Service Interactions
## Attached Resources & Related Docs
- [[doc|platform/006-api-and-contracts]] — Consolidated service and messaging index.
- [[container|scheduler-database]] — Persistent storage for Quartz schedules and outbox.
- [[doc|platform/005-quartz-schema]] — Persistent Quartz table definitions.
- [[service|catalog-ingestion]] — Downstream worker consuming scheduled batch triggers.
## Raw Schema:asyncapi-v1.yml
asyncapi: 3.1.0
info:
title: Scheduler integration events
version: 1.0.0
description: |
Kafka integration contract for the BookWorm Scheduler host. A durable Quartz
job publishes a vector-batch trigger event to Catalog Ingestion every five
minutes in UTC (cron 0 0/5 * * * ?, misfire policy FireOnceNow). The job
disallows concurrent executions and reports publication failures to Quartz
as JobExecutionException.
Payload schemas describe the camelCase JSON data inside BookWorm's
CloudEvents-compatible envelope, not the complete transport envelope.
HeartbeatJob writes logs only and does not publish a Kafka integration event.
defaultContentType: application/cloudevents+json
channels:
processVectorBatch:
address: scheduler.process-vector-batch
description: Scheduler triggers Catalog Ingestion to process a bounded batch of pending vector updates.
messages:
processVectorBatch:
$ref: "#/components/messages/ProcessVectorBatchIntegrationEvent"
operations:
sendProcessVectorBatch:
action: send
channel:
$ref: "#/channels/processVectorBatch"
summary: Publish a five-minute catalog vector batch trigger
description: |
ProcessVectorBatchJob publishes this event through Wolverine. Catalog
Ingestion consumes it via a Kafka-triggered Azure Function, acquires a
PostgreSQL advisory lock, and processes up to 200 pending updates.
messages:
- $ref: "#/channels/processVectorBatch/messages/processVectorBatch"
components:
messages:
ProcessVectorBatchIntegrationEvent:
name: ProcessVectorBatchIntegrationEvent
title: Process catalog vector batch
summary: Triggers Catalog Ingestion to process pending book embedding updates.
description: "Wolverine message identity: BookWorm.Contracts.ProcessVectorBatchIntegrationEvent."
contentType: application/json
payload:
$ref: "#/components/schemas/IntegrationEventPayload"
examples:
- name: processVectorBatchTrigger
payload:
id: "019a1c00-0000-7000-8000-000000000001"
creationDate: "2026-11-17T00:05:00Z"
schemas:
IntegrationEventPayload:
type: object
additionalProperties: false
required:
- id
- creationDate
properties:
id:
type: string
format: uuid
description: Unique identifier of the integration event.
creationDate:
type: string
format: date-time
description: UTC timestamp when the event was created.
---
id: sendgrid-api
name: SendGrid API
version: 1.0.0
summary: |
External SMTP email delivery provider used by BookWorm to submit rendered
order notification emails over authenticated SMTP.
externalSystem: true
badges:
- content: External
backgroundColor: purple
textColor: purple
- content: SMTP
backgroundColor: teal
textColor: teal
styles:
icon: /icons/third-party/sendgrid.svg
owners:
- platform-engineering-team
---
## Integration Purpose & Boundary
SendGrid is BookWorm's external email delivery provider in publish environments, offloading internet mail routing, sender reputation, and downstream delivery. At runtime, only [[service|notification-api]] integrates with SendGrid to transmit rendered order lifecycle emails.
:::note
Although SendGrid's platform exposes a REST v3 HTTP API, BookWorm does **not** invoke SendGrid HTTP endpoints at runtime—[[service|notification-api]] submits rendered MIME messages exclusively over **authenticated SMTP** (using a local test inbox during development).
:::
## Integration Profile
| Property | Value |
| :------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Provider / Sidecar** | Twilio SendGrid (SMTP relay in publish environments; local test inbox in development) |
| **BookWorm Consumers** | [[service\|notification-api]] only |
| **Runtime Transport & Protocol** | SMTP over TLS (port 587) |
| **Auth / Credential Boundary** | API key injected via runtime secret configuration (`apikey` username); domain-authenticated sender identity recommended for production |
| **Data / PII Sensitivity** | High — carries customer recipient email addresses and order notification content; redact recipient metadata in logs and never log rendered email bodies |
| **Failure / Fallback Behavior** | Bounded client retries followed by Kafka listener backoff and dead-letter routing on [[channel\|bookworm.{env}.notification.dead-letter-queue]]; no delivery webhooks ingested |
## Visualizations & Specifications
### Delivery Integration Context
### Service Interactions
- **Least-privilege API keys:** Provision SendGrid keys scoped strictly to mail-send permissions,
store them in the deployment secret store, and rotate or revoke keys immediately if exposed. -
**Submission vs. business truth:** SMTP acceptance confirms only provider handoff, not recipient
inbox delivery or order status.
## Related Documentation
- [[doc|platform/006-api-and-contracts]] — Consolidated service, HTTP, gRPC, and Kafka directory.
- [[service|notification-api]] — Consuming Kafka email worker.
- [[system|sendgrid]] — External SendGrid system boundary.
- [[doc|domains/bookworm/subdomains/platform/engineering/platform-integration-boundaries]] — Platform service and external provider boundaries.
---
id: bookworm
name: BookWorm
summary: |
Core e-commerce domain for the BookWorm online bookstore, coordinating catalog discovery,
customer baskets, order fulfillment, customer reviews, conversational guidance, and platform operations.
version: 1.0.0
owners:
- architecture-enabling-team
domains:
- id: catalog
- id: reviews
- id: ordering
- id: shopping
- id: platform
- id: conversational
diagrams:
- id: bookworm-event-storming
badges:
- content: Core Domain
backgroundColor: blue
textColor: blue
icon: RectangleGroupIcon
- content: Business Critical
backgroundColor: red
textColor: red
icon: ShieldCheckIcon
repository:
url: "https://github.com/foxminchan/BookWorm"
---
## Business Purpose & Boundary
BookWorm is the root business domain for an online bookstore marketplace, decomposed into six autonomous bounded contexts by Domain-Driven Design (DDD) strategic importance: four Core domains ([[domain|catalog]], [[domain|shopping]], [[domain|ordering]], [[domain|conversational]]), one Supporting domain ([[domain|reviews]]), and one Generic domain ([[domain|platform]]). Each bounded context owns its authoritative business state and communicates across boundaries exclusively through explicit, versioned synchronous and asynchronous contracts. Explicitly **out of scope** for BookWorm are external payment-provider settlement, physical shipping carrier execution, external SMTP delivery internals, AI model hosting internals, and external identity provider infrastructure ([[system|identity-provider]]).
:::warning
Bounded contexts never share databases or reach directly into another context's persistence store. Derived projections—such as catalog rating summaries, semantic search indexes, and order dashboard summaries—remain strictly rebuildable from their authoritative owning contexts.
:::
## Core Responsibilities & Capabilities
| Subdomain | DDD Classification | Core Capability | Owning Team |
| :----------------------------- | :----------------- | :------------------------------------------------------------------------------------------------ | :---------------------------------- |
| **[[domain\|catalog]]** | Core | Canonical book metadata, taxonomies, pricing, availability, and hybrid discovery | [[team\|catalog-experience-team]] |
| **[[domain\|shopping]]** | Core | Authenticated customer baskets, pre-purchase intent, and checkout cleanup | [[team\|commerce-fulfillment-team]] |
| **[[domain\|ordering]]** | Core | Accepted purchase records, locked order pricing, lifecycle state, and post-checkout orchestration | [[team\|commerce-fulfillment-team]] |
| **[[domain\|conversational]]** | Core | Privacy-filtered multi-agent book discovery and read-only store-policy guidance | [[team\|ai-capabilities-team]] |
| **[[domain\|reviews]]** | Supporting | Individual customer feedback submissions, rating publication, and review summarization | [[team\|catalog-experience-team]] |
| **[[domain\|platform]]** | Generic | Cross-cutting recurring job scheduling and transactional email delivery | [[team\|platform-engineering-team]] |
## Cross-Domain Interactions (Context Map)
| Neighboring Domain / System | Direction | Integration Mechanism | Business Data Exchanged |
| :------------------------------------------------------------------------- | :-------------------------------------------------------------- | :------------------------------------ | :--------------------------------------------------------------------------------------- |
| **[[domain\|catalog]] ↔ [[domain\|shopping]]** | Upstream (`Catalog`) → Downstream (`Shopping`) | Sync (gRPC) | Book titles, live prices, and availability for basket enrichment |
| **[[domain\|shopping]] ↔ [[domain\|ordering]]** | Upstream (`Shopping`) → Downstream (`Ordering`) | Sync (gRPC) & Async (Events/Commands) | Basket item quantities at checkout; post-checkout basket cleanup commands and outcomes |
| **[[domain\|catalog]] ↔ [[domain\|ordering]]** | Upstream (`Catalog`) → Downstream (`Ordering`) | Sync (gRPC) | Authoritative book pricing resolved and locked onto accepted orders |
| **[[domain\|reviews]] ↔ [[domain\|catalog]]** | Bidirectional (Partnership / Compensation) | Async (Events) | Feedback created/deleted events for rating aggregation; missing-book compensation events |
| **[[domain\|conversational]] ↔ [[domain\|catalog]] / [[domain\|reviews]]** | Downstream (`Conversational`) ← Upstream (`Catalog`, `Reviews`) | Sync (MCP & A2A gRPC) | Read-only book discovery lookups and AI-summarized customer feedback |
| **[[domain\|platform]] ↔ [[domain\|catalog]] / [[domain\|ordering]]** | Supporting (`Platform`) ↔ Core (`Catalog`, `Ordering`) | Async (Events/Commands) | Scheduled vector batch triggers and transactional order email commands |
| **[[system\|identity-provider]] & [[system\|data-privacy]]** | Upstream (External Systems) → Downstream (`BookWorm`) | Sync (OIDC / HTTP) | User and agent identity tokens; fail-closed PII detection and anonymization |
:::note
**Domain Invariants:** A basket cannot proceed to checkout without valid [[domain|catalog]] book identities and current pricing. Every accepted checkout creates one authoritative `Order` in [[domain|ordering]] with status `New`, and only explicit ordering commands transition it to `Completed` or `Cancelled`.
:::
## Ubiquitous Language Highlights
BookWorm's shared domain vocabulary prevents ambiguity across bounded contexts (see [[doc|arc42/12-glossary]] and the BookWorm Ubiquitous Language dictionary):
- **Book:** A canonical title owned by [[domain|catalog]]; other contexts reference it strictly by identifier.
- **Basket:** Mutable pre-purchase shopping intent owned by [[domain|shopping]]—never an order or inventory reservation.
- **Order & Order Item:** Durable purchase records owned by [[domain|ordering]] with locked purchase-time pricing and lifecycle status.
- **Feedback:** An individual customer rating and optional comment owned by [[domain|reviews]], distinct from [[domain|catalog]]'s aggregate rating summary.
- **Checkout:** The cross-context process that transitions a checked-out basket into the ordering workflow.
- **Chat Request:** A customer question routed by [[domain|conversational]] agents without taking ownership of referenced books or orders.
## Architecture Visualizations
### Enterprise Context Overview
### Commerce Capabilities Overview
### Conversational & Platform Capabilities Overview
## Related Governance & Documentation
- [[adr|adr-bw-001-capability-aligned-boundaries]] — Decompose BookWorm by business capability and bounded context.
- [[adr|adr-bw-005-kafka-integration-backbone]] — Standardize asynchronous cross-context messaging.
- [[adr|adr-bw-006-service-owned-business-state]] — Keep persistence isolated inside each owning bounded context.
- [[diagram|bookworm-event-storming]] — Whole-domain event storming overview.
---
id: catalog
name: Catalog
summary: |
Core BookWorm subdomain that makes books discoverable, purchasable, and
consistently described across the customer journey.
version: 1.0.0
owners:
- catalog-experience-team
systems:
- id: product-catalog-system
version: 1.0.0
flows:
- id: product-ingestion
version: 1.0.0
- id: feedback-publication
version: 1.0.0
entities:
- id: book
version: 1.0.0
- id: author
version: 1.0.0
- id: category
version: 1.0.0
- id: publisher
version: 1.0.0
badges:
- content: Core Domain
backgroundColor: blue
textColor: blue
icon: RectangleGroupIcon
- content: Business Critical
backgroundColor: red
textColor: red
icon: ShieldCheckIcon
---
## Business Purpose & Boundary
[[domain|catalog]] is BookWorm's Core bounded context for authoritative book information, classification taxonomies ([[entity|author]], [[entity|category]], [[entity|publisher]]), pricing, availability, and hybrid text-and-semantic search. It serves low-latency product discovery reads, manages book cover assets, and projects aggregate rating summaries asynchronously from customer feedback events. Explicitly **out of scope** are customer shopping baskets ([[domain|shopping]]), accepted purchase snapshots ([[domain|ordering]]), and individual customer feedback records ([[domain|reviews]]).
:::warning
Catalog listing availability describes whether a title is in stock for discovery—it is **not** an inventory reservation held by a basket or a fulfillment guarantee. Catalog price updates never retroactively alter purchase-time prices locked onto accepted orders.
:::
## Core Responsibilities & Capabilities
| Capability | Owning Service / Agent | Primary Entities |
| :---------------------------------- | :----------------------------- | :-------------------------------------------------------------------------------- |
| **Product Lifecycle & Taxonomies** | [[service\|catalog-api]] | [[entity\|book]], [[entity\|author]], [[entity\|category]], [[entity\|publisher]] |
| **Hybrid Text & Semantic Search** | [[service\|catalog-api]] | [[entity\|book]] |
| **Rating Summary Projection** | [[service\|catalog-api]] | [[entity\|book]] |
| **Scheduled Vector Embedding Sync** | [[service\|catalog-ingestion]] | [[entity\|book]] |
## Cross-Domain Interactions (Context Map)
| Neighboring Domain | Direction | Integration Mechanism | Business Data Exchanged |
| :----------------------------- | :---------------------------------------- | :-------------------- | :----------------------------------------------------------------------------------------- |
| **[[domain\|shopping]]** | Downstream (`Catalog` → `Shopping`) | Sync (gRPC) | Book titles, current prices, and availability for basket display enrichment |
| **[[domain\|ordering]]** | Downstream (`Catalog` → `Ordering`) | Sync (gRPC) | Authoritative unit and discount prices resolved at checkout time |
| **[[domain\|reviews]]** | Upstream (`Reviews` → `Catalog`) | Async (Events) | Feedback created/deleted events updating aggregate rating; missing-book compensation event |
| **[[domain\|platform]]** | Upstream (`Platform` → `Catalog`) | Async (Events) | Recurring vector-batch trigger initiating semantic index refreshes |
| **[[domain\|conversational]]** | Downstream (`Catalog` → `Conversational`) | Sync (via MCP Tools) | Read-only catalog search, book details, categories, and authors |
:::note
**Eventual Consistency & Compensation:** Catalog never queries [[domain|reviews]] synchronously, keeping storefront discovery available even if Reviews is degraded. Instead, rating summaries and semantic search vectors are rebuildable derived projections. If a rating event references a nonexistent or deleted book, [[service|catalog-api]] publishes [[event|BookUpdatedRatingFailedIntegrationEvent]] so [[domain|reviews]] can compensate idempotently.
:::
## Ubiquitous Language Highlights
- **Book:** The canonical listed title available for discovery, carrying descriptive metadata, cover image, pricing, availability, and taxonomy links.
- **Price:** A book's original price paired with an optional discount price (never negative and never exceeding the original price), modeled as an attribute of [[entity|book]] rather than a separate product.
- **Availability:** Whether a catalog listing is in stock or out of stock, independent of any customer basket.
- **Rating Summary:** The derived average rating and total review count displayed for a book—an aggregate projection rather than individual customer feedback.
## Architecture Visualizations
### Catalog Context Overview
## Related Governance & Documentation
- [[system|product-catalog-system]] — System boundary, containers, and owned services.
- [[flow|product-ingestion]] — End-to-end scheduled vector indexing workflow.
- [[adr|adr-bw-004-explicit-http-and-grpc-contracts]] — Versioned synchronous HTTP and gRPC contract boundaries.
- [[adr|adr-bw-006-service-owned-business-state]] — Service-owned persistence isolation.
- [[adr|adr-bw-007-derived-eventually-consistent-views]] — Authoritative state vs. rebuildable derived projections.
- [[doc|arc42/12-glossary]] — Shared catalog and cross-domain vocabulary.
---
id: conversational
name: Conversational
summary: |
Routes BookWorm customer requests through privacy-filtered AI agents for
catalog-backed book discovery and read-only store-policy guidance.
owners:
- ai-capabilities-team
version: 1.0.0
systems:
- id: chat-system
version: 1.0.0
- id: mcp-tools
version: 1.0.0
flows:
- id: agent-orchestration
version: 1.0.0
agents:
- id: book-agent
version: 1.0.0
- id: qa-agent
version: 1.0.0
- id: book-catalog-researcher
version: 1.0.0
- id: book-recommendation-researcher
version: 1.0.0
badges:
- content: Core Domain
backgroundColor: blue
textColor: blue
icon: RectangleGroupIcon
- content: Business Critical
backgroundColor: red
textColor: red
icon: ShieldCheckIcon
---
## Business Purpose & Boundary
[[domain|conversational]] is BookWorm's Core bounded context for AI-assisted customer book discovery and store-policy guidance. It validates incoming customer requests, routes them in a single pass across safety, language, scope, and specialist selection, protects all prompts and responses with fail-closed PII redaction, and coordinates specialist agents ([[agent|book-agent]], [[agent|qa-agent]], and delegated research subagents) backed by read-only [[service|mcp-server]] tools. Explicitly **out of scope** are mutating books ([[domain|catalog]]), modifying shopping baskets ([[domain|shopping]]), creating or canceling orders ([[domain|ordering]]), and persisting customer feedback ([[domain|reviews]]).
:::warning
Conversational agents operate strictly **read-only** across transactional domains. When a customer asks about orders, shipping, or baskets, [[agent|qa-agent]] provides policy guidance only, and privacy middleware fails closed rather than forwarding unredacted text.
:::
## Core Responsibilities & Capabilities
| Capability | Owning Service / Agent | Primary Entities |
| :------------------------------------------------- | :--------------------------------------------------------------------------------------------------- | :---------------------------- |
| **Multi-Agent Chat Orchestration & Session State** | [[service\|chat-api]] | — (Session state only) |
| **Single-Pass Safety, Scope & Specialist Routing** | [[service\|chat-api]] | — |
| **Book Discovery & Recommendations** | [[agent\|book-agent]], [[agent\|book-catalog-researcher]], [[agent\|book-recommendation-researcher]] | — (Reads [[domain\|catalog]]) |
| **Store Policy & Support Guidance** | [[agent\|qa-agent]] | — |
| **Read-Only Catalog Tool & Prompt Exposure** | [[service\|mcp-server]] | — (Reads [[domain\|catalog]]) |
## Cross-Domain Interactions (Context Map)
| Neighboring Domain / System | Direction | Integration Mechanism | Business Data Exchanged |
| :-------------------------------- | :------------------------------------------------ | :-------------------------------------- | :---------------------------------------------------------------------------------- |
| **[[domain\|catalog]]** | Upstream (`Catalog` → `Conversational`) | Sync (gRPC via [[service\|mcp-server]]) | Read-only book searches, book details, categories, and authors |
| **[[domain\|reviews]]** | Upstream (`Reviews` → `Conversational`) | Sync (A2A gRPC) | Delegated requests to [[agent\|rating-agent]] for summarized book feedback |
| **[[system\|data-privacy]]** | Upstream (`Data Privacy` → `Conversational`) | Sync (HTTP) | Fail-closed PII analysis and anonymization on incoming prompts and buffered replies |
| **[[system\|identity-provider]]** | Upstream (`Identity Provider` → `Conversational`) | Sync (OIDC / OBO) | Customer and agent identity tokens with per-agent claim isolation |
:::note
**Read-Only Boundary & Fail-Closed Privacy:** Conversational has no transactional SQL database, cache, or broker integration. Any recommendation that a customer chooses to add to a basket requires explicit customer confirmation in the storefront UI, preserving [[domain|shopping]]'s ownership of basket mutations.
:::
## Ubiquitous Language Highlights
- **Customer Request:** An incoming BookWorm conversation turn; referencing a book, basket, or order never transfers ownership of that record into Conversational.
- **Decision Router:** The single-pass entry gatekeeper that evaluates safety, English compliance, domain scope, and target specialist before invoking a generative agent.
- **Book Agent & Research Subagents:** [[agent|book-agent]] handles catalog discovery and delegates deep lookups and personalized synthesis to [[agent|book-catalog-researcher]] and [[agent|book-recommendation-researcher]].
- **QA Agent:** [[agent|qa-agent]] answers shipping, returns, account, and store-policy questions without accessing live customer records.
- **Handoff:** A transfer of conversational control between specialists (never a transactional business workflow).
## Architecture Visualizations
### Conversational Context Overview
## Related Governance & Documentation
- [[system|chat-system]] — Chat orchestration boundary and [[service|chat-api]].
- [[system|mcp-tools]] — Read-only MCP tool server boundary and [[service|mcp-server]].
- [[flow|agent-orchestration]] — End-to-end request validation, routing, privacy screening, and agent delegation.
- [[adr|adr-bw-014-composable-ai-governance]] — Composable validation, PII, and guardrail controls on every AI path.
- [[doc|misc/001-ms-decisions-model-use-case-and-lessons-learned]] — Single-pass decision routing design and lessons learned.
- [[doc|arc42/12-glossary]] — Shared conversational and cross-domain terminology.
---
id: ordering
name: Ordering
summary: |
Creates durable Orders from a buyer's current basket, locks purchase-time pricing,
and owns order lifecycle transitions from New to Completed or Cancelled.
version: 1.0.0
owners:
- commerce-fulfillment-team
systems:
- id: order-system
version: 1.0.0
- id: finance-system
version: 1.0.0
flows:
- id: order-lifecycle
version: 1.0.0
- id: user-checkout
version: 1.0.0
diagrams:
- id: order-lifecycle
version: 1.0.0
- id: checkout-interaction
version: 1.0.0
entities:
- id: order
version: 1.0.0
- id: buyer
version: 1.0.0
- id: order-item
version: 1.0.0
badges:
- content: Core Domain
backgroundColor: blue
textColor: blue
icon: RectangleGroupIcon
- content: Business Critical
backgroundColor: red
textColor: red
icon: ShieldCheckIcon
---
## Business Purpose & Boundary
[[domain|ordering]] is BookWorm's Core bounded context for committed customer purchases ([[entity|buyer]], [[entity|order]], [[entity|order-item]]) and their business lifecycle (`New` → `Completed` or `Cancelled`). It accepts checkouts by locking purchase-time pricing onto immutable order lines, maintains buyer profiles and delivery addresses, projects real-time order summaries, and orchestrates post-checkout basket cleanup and customer email triggers through [[service|order-orchestration]]. Explicitly **out of scope** are pre-order mutable baskets ([[domain|shopping]]), live catalog descriptions ([[domain|catalog]]), external payment settlement, physical shipping execution, and email rendering or transport ([[domain|platform]]).
:::warning
Only explicit Ordering commands transition an [[entity|order]]'s business status. Post-checkout orchestration retries, timeouts, and [[domain|platform]] email delivery outcomes never mark an order `Completed` or `Cancelled`.
:::
## Core Responsibilities & Capabilities
| Capability | Owning Service / Agent | Primary Entities |
| :----------------------------------------- | :------------------------------- | :---------------------------------------- |
| **Order Creation & Lifecycle Transitions** | [[service\|order-api]] | [[entity\|order]], [[entity\|order-item]] |
| **Buyer & Delivery Address Management** | [[service\|order-api]] | [[entity\|buyer]] |
| **Order Summary Projections** | [[service\|order-api]] | [[entity\|order]] |
| **Post-Checkout Saga Orchestration** | [[service\|order-orchestration]] | [[entity\|order]] |
## Cross-Domain Interactions (Context Map)
| Neighboring Domain | Direction | Integration Mechanism | Business Data Exchanged |
| :----------------------- | :----------------------------------- | :------------------------ | :-------------------------------------------------------------------------------------- |
| **[[domain\|shopping]]** | Upstream (`Shopping` → `Ordering`) | Sync (gRPC) | Customer basket book IDs and quantities fetched at checkout |
| **[[domain\|catalog]]** | Upstream (`Catalog` → `Ordering`) | Sync (gRPC) | Current unit and promotional prices locked onto [[entity\|order-item]] lines |
| **[[domain\|shopping]]** | Downstream (`Ordering` → `Shopping`) | Async (Commands & Events) | [[command\|PlaceOrderCommand]] for basket cleanup; completion or failure outcome events |
| **[[domain\|platform]]** | Downstream (`Ordering` → `Platform`) | Async (Commands) | Order placement, completion, and cancellation email notification commands |
:::note
**Checkout Consistency & Compensation:** Concurrent checkout submissions are serialized using buyer-scoped distributed locking and request idempotency keys. If post-checkout basket cleanup fails after bounded retries, [[service|order-orchestration]] issues a compensation command so [[service|order-api]] soft-deletes the order and suppresses confirmation emails.
:::
## Ubiquitous Language Highlights
- **Buyer:** The named person associated with one or more orders, holding a delivery address distinct from [[domain|shopping]]'s customer identifier.
- **Order:** The durable purchase record beginning in `New` and transitioning once to a terminal state (`Completed` or `Cancelled`).
- **Order Item & Order Total:** Each line records a book identifier, positive quantity, and locked purchase-time price; the order total is strictly the sum of all line totals.
- **New / Completed / Cancelled:** Explicit lifecycle states governing when orders are active versus terminally closed.
## Architecture Visualizations
### Ordering Context Overview
### Checkout Handoff & Cleanup Interaction
## Related Governance & Documentation
- [[system|order-system]] — Authoritative order persistence and [[service|order-api]].
- [[system|finance-system]] — Durable post-checkout workflow and [[service|order-orchestration]].
- [[flow|order-lifecycle]] — Order state transitions and downstream triggers.
- [[flow|user-checkout]] — End-to-end checkout, cleanup, and notification workflow.
- [[diagram|order-lifecycle]] — Order status transition model.
- [[adr|adr-bw-006-service-owned-business-state]] — Service-owned persistence isolation.
- [[adr|adr-bw-008-durable-message-handoffs]] — Durable inbox/outbox message handoffs.
- [[doc|arc42/12-glossary]] — Canonical order, buyer, and lifecycle definitions.
---
id: platform
name: Platform
summary: |
Provides cross-cutting capabilities for recurring scheduled triggers and durable,
idempotent transactional email notification delivery across BookWorm.
version: 1.0.0
owners:
- platform-engineering-team
systems:
- id: scheduler-system
version: 1.0.0
- id: notification-system
version: 1.0.0
- id: sendgrid
version: 1.0.0
flows:
- id: notification-delivery
version: 1.0.0
- id: product-ingestion
version: 1.0.0
badges:
- content: Generic Domain
backgroundColor: purple
textColor: purple
icon: LayersIcon
- content: Cross-Cutting Capability
backgroundColor: gray
textColor: gray
icon: ArrowsRightLeftIcon
---
## Business Purpose & Boundary
[[domain|platform]] is BookWorm's Generic bounded context for cross-cutting background job scheduling and transactional email delivery. Through [[service|scheduler-service]] and [[service|notification-api]], it emits recurring operational triggers (such as catalog vector-batch refreshes) and renders and submits order lifecycle emails via [[service|sendgrid-api]]. Explicitly **out of scope** are owning books, baskets, orders, payments, or reviews; guaranteeing recipient inbox placement after SMTP handoff; and maintaining a relational email-outbox database.
:::warning
Platform delivery outcomes and scheduled job executions **never** mutate authoritative business state in upstream domains. A successful scheduler trigger confirms event publication only—not downstream indexing completion—and email delivery status never alters an [[entity|order]]'s lifecycle state.
:::
## Core Responsibilities & Capabilities
| Capability | Owning Service / Agent | Primary Entities |
| :------------------------------------------------------ | :----------------------------- | :------------------------------ |
| **Recurring Job Scheduling & Operational History** | [[service\|scheduler-service]] | — (Operational schedules only) |
| **Transactional Order Email Rendering & Deduplication** | [[service\|notification-api]] | — (Stateless idempotency guard) |
| **External SMTP Relay Boundary** | [[service\|sendgrid-api]] | — (External delivery provider) |
## Cross-Domain Interactions (Context Map)
| Neighboring Domain / System | Direction | Integration Mechanism | Business Data Exchanged |
| :-------------------------- | :----------------------------------- | :-------------------- | :----------------------------------------------------------------------------------------------------------------------------- |
| **[[domain\|catalog]]** | Upstream (`Platform` → `Catalog`) | Async (Event) | [[event\|ProcessVectorBatchIntegrationEvent]] triggers periodic vector embedding refreshes |
| **[[domain\|ordering]]** | Downstream (`Ordering` → `Platform`) | Async (Commands) | [[command\|PlaceOrderCommand]], [[command\|CompleteOrderCommand]], and [[command\|CancelOrderCommand]] trigger customer emails |
| **[[system\|sendgrid]]** | Downstream (`Platform` → `SendGrid`) | Sync (SMTP) | Rendered MIME HTML order confirmation, completion, and cancellation emails |
:::note
**Idempotency & Dead-Letter Resilience:** Because [[service|notification-api]] operates statelessly without a relational outbox, it protects customers from duplicate emails using a 24-hour Redis idempotency guard. Commands with blank recipient addresses are skipped safely, and messages that exhaust transient delivery retries route to the notification dead-letter queue for operator triage.
:::
## Ubiquitous Language Highlights
- **Vector Batch Job:** A recurring scheduled trigger that asks [[domain|catalog]] ingestion to refresh search embeddings without owning book records.
- **Idempotency Guard:** A time-bounded deduplication check ensuring repeated notification commands do not send duplicate customer emails.
- **Email Template:** Responsive email markup compiled into HTML at runtime for transactional order notifications.
- **Dead-Letter Queue:** A dedicated message channel holding commands that exhausted transient delivery retries for inspection and replay.
## Architecture Visualizations
### Platform Context Overview
## Related Governance & Documentation
- [[system|scheduler-system]] — Recurring job scheduling boundary and [[service|scheduler-service]].
- [[system|notification-system]] — Stateless email rendering and [[service|notification-api]].
- [[system|sendgrid]] — External SMTP relay boundary.
- [[flow|notification-delivery]] — End-to-end order notification delivery workflow.
- [[flow|product-ingestion]] — Scheduled vector batch trigger to Catalog ingestion.
- [[adr|adr-bw-005-kafka-integration-backbone]] — Standardized asynchronous messaging backbone.
- [[doc|arc42/12-glossary]] — Shared platform and operational terminology.
---
id: reviews
name: Reviews
summary: |
Captures individual customer feedback for books, publishes rating changes for
Catalog discovery, and provides privacy-screened AI feedback summaries.
version: 1.0.0
owners:
- catalog-experience-team
systems:
- id: rating-system
version: 1.0.0
flows:
- id: feedback-publication
version: 1.0.0
diagrams:
- id: rating-summarizer-workflow
version: 1.0.0
entities:
- id: feedback
version: 1.0.0
agents:
- id: rating-agent
version: 1.0.0
badges:
- content: Supporting Domain
backgroundColor: teal
textColor: teal
---
## Business Purpose & Boundary
[[domain|reviews]] is BookWorm's Supporting bounded context for individual customer book feedback, centered on the [[entity|feedback]] entity (a book reference, integer rating from `0` to `5`, reviewer name, and optional comment). It persists authoritative feedback records, publishes rating lifecycle events so [[domain|catalog]] can project aggregate scores, compensates orphaned feedback when a referenced book does not exist, and hosts [[agent|rating-agent]] to generate read-only AI review summaries. Explicitly **out of scope** are owning canonical book metadata ([[domain|catalog]]), managing shopping baskets ([[domain|shopping]]), and processing orders ([[domain|ordering]]).
:::warning
Reviews references books strictly by identifier and never duplicates Catalog metadata. AI-generated feedback summaries are read-only derived insights—they never alter persisted [[entity|feedback]] records or Catalog's numeric rating summary.
:::
## Core Responsibilities & Capabilities
| Capability | Owning Service / Agent | Primary Entities |
| :------------------------------------------- | :---------------------------------------------------- | :------------------- |
| **Customer Feedback Lifecycle** | [[service\|rating-api]] | [[entity\|feedback]] |
| **Rating Event Publication & Compensation** | [[service\|rating-api]] | [[entity\|feedback]] |
| **Privacy-Screened AI Review Summarization** | [[agent\|rating-agent]] (via [[service\|rating-api]]) | [[entity\|feedback]] |
## Cross-Domain Interactions (Context Map)
| Neighboring Domain / System | Direction | Integration Mechanism | Business Data Exchanged |
| :----------------------------- | :---------------------------------------- | :------------------------- | :------------------------------------------------------------------------------------------------------------------------- |
| **[[domain\|catalog]]** | Downstream (`Reviews` → `Catalog`) | Async (Events) | [[event\|FeedbackCreatedIntegrationEvent]] and [[event\|FeedbackDeletedIntegrationEvent]] to update aggregate book ratings |
| **[[domain\|catalog]]** | Upstream (`Catalog` → `Reviews`) | Async (Compensation Event) | [[event\|BookUpdatedRatingFailedIntegrationEvent]] triggers idempotent deletion of orphaned feedback |
| **[[domain\|conversational]]** | Downstream (`Reviews` → `Conversational`) | Sync (A2A gRPC) | [[agent\|rating-agent]] returns read-only sentiment and review summaries for a requested book |
| **[[system\|data-privacy]]** | Upstream (`Data Privacy` → `Reviews`) | Sync (HTTP) | Fail-closed PII detection and anonymization before AI summarization |
:::note
**Decoupled Availability & Compensation:** Storefront discovery in [[domain|catalog]] never calls Reviews synchronously, so catalog browsing stays available even during Reviews maintenance. Eventual consistency between individual feedback writes and Catalog's rating summary is maintained asynchronously, with explicit compensating deletion when feedback targets an invalid or deleted book.
:::
## Ubiquitous Language Highlights
- **Feedback & Review:** Synonyms for the same individual customer submission about a book (`Review` in customer-facing experiences, [[entity|feedback]] in the domain model).
- **Rating & Comment:** An integer score from `0` through `5` paired with an optional written customer comment.
- **Book Reference:** The book identifier linking feedback to [[domain|catalog]] without copying catalog attributes.
- **Rating Summary:** [[domain|catalog]]'s aggregated average rating and review count—explicitly distinct from individual feedback records.
## Architecture Visualizations
### Reviews Context Overview
## Related Governance & Documentation
- [[system|rating-system]] — System boundary, Cosmos DB persistence, and [[service|rating-api]].
- [[flow|feedback-publication]] — Feedback publication, Catalog projection, and compensation workflow.
- [[adr|adr-bw-007-derived-eventually-consistent-views]] — Authoritative feedback vs. derived Catalog rating summaries.
- [[adr|adr-bw-014-composable-ai-governance]] — Fail-closed privacy and guardrail governance for [[agent|rating-agent]].
- [[doc|arc42/12-glossary]] — Shared feedback, rating, and summary terminology.
---
id: shopping
name: Shopping
summary: |
Coordinates the customer basket and pre-purchase checkout intent, from selecting books
through handing an accepted purchase to Ordering.
version: 1.0.0
owners:
- commerce-fulfillment-team
systems:
- id: cart-system
version: 1.0.0
entities:
- id: basket
version: 1.0.0
- id: basket-item
version: 1.0.0
diagrams:
- id: checkout-interaction
version: 1.0.0
flows:
- id: user-checkout
version: 1.0.0
badges:
- content: Core Domain
backgroundColor: blue
textColor: blue
icon: RectangleGroupIcon
- content: Business Critical
backgroundColor: red
textColor: red
icon: ShieldCheckIcon
---
## Business Purpose & Boundary
[[domain|shopping]] is BookWorm's Core bounded context for pre-purchase customer intent, centered on the [[entity|basket]] and its [[entity|basket-item]] entries. It enables authenticated customers to create, inspect, replace, and clear their baskets with sub-millisecond reads, enriches basket items with live [[domain|catalog]] metadata at read time, and executes post-checkout basket cleanup once an order is accepted. Explicitly **out of scope** are owning canonical book details ([[domain|catalog]]), creating or managing accepted orders ([[domain|ordering]]), coordinating post-checkout workflows ([[domain|ordering]]), and external payment settlement.
:::warning
A [[entity|basket]] represents mutable shopping intent—**not** a confirmed order and **not** an inventory reservation. Basket items store only book identifiers and quantities, never copied catalog descriptions or locked order prices.
:::
## Core Responsibilities & Capabilities
| Capability | Owning Service / Agent | Primary Entities |
| :------------------------------------ | :---------------------- | :------------------------------------------ |
| **Customer-Scoped Basket Management** | [[service\|basket-api]] | [[entity\|basket]], [[entity\|basket-item]] |
| **Read-Time Catalog Enrichment** | [[service\|basket-api]] | [[entity\|basket-item]] |
| **Checkout Basket Read Contract** | [[service\|basket-api]] | [[entity\|basket]] |
| **Idempotent Post-Checkout Cleanup** | [[service\|basket-api]] | [[entity\|basket]] |
## Cross-Domain Interactions (Context Map)
| Neighboring Domain | Direction | Integration Mechanism | Business Data Exchanged |
| :----------------------------- | :----------------------------------------- | :------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **[[domain\|catalog]]** | Upstream (`Catalog` → `Shopping`) | Sync (gRPC) | Live book titles, unit prices, and discount prices to enrich basket reads |
| **[[domain\|ordering]]** | Downstream (`Shopping` → `Ordering`) | Sync (gRPC) | Customer basket book IDs and quantities read during checkout order creation |
| **[[domain\|ordering]]** | Upstream (`Ordering` → `Shopping`) | Async (Commands & Events) | [[command\|PlaceOrderCommand]] triggers basket deletion; Shopping replies with [[event\|BasketDeletedCompleteIntegrationEvent]] or [[event\|BasketDeletedFailedIntegrationEvent]] |
| **[[domain\|conversational]]** | Downstream (`Shopping` ← `Conversational`) | User-confirmed UI action | Conversational recommendations require explicit customer confirmation before mutating a basket |
:::note
**Explicit Cleanup Outcomes & Idempotency:** Duplicate cleanup commands during post-checkout retries are deduplicated by Shopping's idempotency guard. When cleanup fails, [[service|basket-api]] emits [[event|BasketDeletedFailedIntegrationEvent]] so [[domain|ordering]] can compensate explicitly—cleanup failure is never treated as a successful cleanup or payment status.
:::
## Ubiquitous Language Highlights
- **Basket:** A customer's mutable collection of items before purchase; updates replace the entire item collection as a set rather than merging partial diffs.
- **Basket Item:** A book identifier paired with a positive quantity, enriched from [[domain|catalog]] at read time.
- **Customer Identifier:** The authenticated identity used to scope a customer's basket, distinct from the [[entity|buyer]] identity managed inside [[domain|ordering]].
- **Checkout:** The cross-context action that hands basket contents to [[domain|ordering]] to initiate order placement.
## Architecture Visualizations
### Shopping Context Overview
## Related Governance & Documentation
- [[system|cart-system]] — System boundary, Redis persistence container, and [[service|basket-api]].
- [[flow|user-checkout]] — End-to-end checkout, basket cleanup, and compensation sequence.
- [[diagram|checkout-interaction]] — Checkout interaction between Shopping and Ordering.
- [[adr|adr-bw-004-explicit-http-and-grpc-contracts]] — Explicit HTTP and gRPC service contracts.
- [[adr|adr-bw-006-service-owned-business-state]] — Isolated basket state ownership.
- [[doc|arc42/12-glossary]] — Shared shopping and checkout terminology.
---
id: ai-capabilities-team
name: AI Capabilities Team
summary: |
Complicated-Subsystem team owning BookWorm's multi-agent conversational discovery, MCP/A2A protocols, vector ingestion, and AI governance guardrails.
members:
- nxnhan
---
## Mission & Topology Boundary
The **AI Capabilities Team** encapsulates specialized AI engineering complexity within [[domain|conversational]] so stream-aligned teams do not have to manage LLM orchestration, embedding pipelines, or agentic protocol details. It owns multi-agent routing, Model Context Protocol (MCP) adapters, Agent-to-Agent (A2A) integration, vector batch scheduling contracts, and composable AI governance. Explicitly **out of scope** are authoritative book inventory, basket mutations, order state transitions, and core PII detection engine hosting (consumed from [[system|data-privacy]]).
## Team Profile & Interaction Modes
| Property | Value |
| :---------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------- |
| **Topology Type** | Complicated-Subsystem |
| **Primary Mission** | Deliver safe, privacy-filtered conversational book discovery and read-only store guidance |
| **Default Interaction Mode** | _X-as-a-Service_ (exposes conversational & MCP endpoints); _Collaboration_ (with Catalog & Platform on embeddings and guardrails) |
| **Key Partner Teams** | [[team\|catalog-experience-team]], [[team\|platform-engineering-team]], [[team\|architecture-enabling-team]] |
| **Escalation / Engagement Channel** | [GitHub Discussions](https://github.com/foxminchan/BookWorm/discussions) · [[doc\|arc42/08-crosscutting-concepts/005-ai-governance]] |
## Owned Capabilities & Assets
- **Domain:** [[domain|conversational]]
- **Systems:** [[system|chat-system]], [[system|mcp-tools]]
- **Services:** [[service|chat-api]], [[service|mcp-server]]
- **Agents:** [[agent|book-agent]], [[agent|book-catalog-researcher]], [[agent|book-recommendation-researcher]], [[agent|qa-agent]]
- **Flows & Channels:** [[flow|agent-orchestration]], [[channel|scheduler.process-vector-batch]]
- **Governance & Decisions:** [[doc|arc42/08-crosscutting-concepts/005-ai-governance]]
- **With [[team|catalog-experience-team]] (_Collaboration_):** Consumes read-only book and review summaries via MCP tools and A2A contracts without duplicating authoritative domain state.
- **With [[team|platform-engineering-team]] (_X-as-a-Service_):** Enforces fail-closed PII filtering via [[service|presidio-api]], agent identities via [[system|identity-provider]], and scheduled batch triggers via [[service|scheduler-service]].
- **With [[team|architecture-enabling-team]] (_Facilitating_):** Validates AI governance controls, tool-scoping boundaries, and episodic/semantic memory policies against platform ADRs.
## Working Agreements
- Enforce fail-closed PII detection and anonymization on every inbound prompt and outbound response.
- Keep [[service|mcp-server]] strictly read-only over domain APIs; conversational agents never bypass domain boundaries to mutate catalog, basket, or order state.
- Govern tool access per agent and maintain explicit model-routing decisions.
:::warning
Agents must never fabricate order or inventory state; all factual book and review responses must ground in live read-only lookups from [[domain|catalog]] and [[domain|reviews]].
:::
---
id: architecture-enabling-team
name: Architecture Enabling Team
summary: |
Enabling team facilitating BookWorm's architecture governance, ADRs, arc42 documentation, engineering standards, testing practices, and EventCatalog curation.
members:
- nxnhan
---
## Mission & Topology Boundary
The **Architecture Enabling Team** elevates engineering capability across BookWorm through _Facilitating_ guidance rather than owning runtime production services. It stewards the root [[domain|bookworm]] architecture narrative, cross-cutting Architecture Decision Records (ADRs), arc42 documentation, developer onboarding, layered testing standards, and EventCatalog fitness/linter quality gates. Explicitly **out of scope** are day-to-day feature delivery for commerce/catalog domains and runtime infrastructure operations.
## Team Profile & Interaction Modes
| Property | Value |
| :---------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ |
| **Topology Type** | Enabling |
| **Primary Mission** | Upskill teams on DDD boundaries, contract evolution, testing rigor, and living architecture documentation |
| **Default Interaction Mode** | _Facilitating_ (advisory pairing, ADR reviews, fitness-function guidance) |
| **Key Partner Teams** | [[team\|catalog-experience-team]], [[team\|commerce-fulfillment-team]], [[team\|platform-engineering-team]], [[team\|ai-capabilities-team]] |
| **Escalation / Engagement Channel** | [GitHub Discussions](https://github.com/foxminchan/BookWorm/discussions) · [[doc\|arc42/09-architecture-decisions]] |
## Owned Capabilities & Assets
- **Root Domain & Context:** [[domain|bookworm]]
- **Architecture Documentation:** [[doc|arc42/09-architecture-decisions]] and cross-cutting arc42 views
- **Developer Experience & Quality:** [[doc|development/004-engineering-standards]], [[doc|development/006-pull-request-process]]
- **With [[team|catalog-experience-team]] (_Facilitating_):** Advises on bounded-context separation between catalog metadata and customer reviews, plus compatible contract evolution.
- **With [[team|commerce-fulfillment-team]] (_Facilitating_):** Reviews saga boundary decisions, CQRS handler conventions, and contract test coverage.
- **With [[team|platform-engineering-team]] (_Collaboration_):** Aligns cross-cutting architecture decisions with Aspire service defaults, observability, and deployment views.
- **With [[team|ai-capabilities-team]] (_Facilitating_):** Ensures AI governance decisions and agent boundaries remain consistent with BookWorm's single-source ADR practices.
## Working Agreements
- **Advisory, Not Gatekeeping:** The enabling team equips stream-aligned and platform teams with clear standards and automated fitness checks so teams own their own delivery velocity.
- **Single-Source Decisions:** Significant cross-boundary architectural choices are captured as ADRs and linked directly from affected domains and services.
- **Catalog Hygiene:** Every service, message, channel, and decision in EventCatalog maintains valid team ownership and verified contract links.
:::note
Need an architecture review or ADR template? Start a thread in [GitHub Discussions](https://github.com/foxminchan/BookWorm/discussions) and reference [[doc|development/004-engineering-standards]].
:::
---
id: catalog-experience-team
name: Catalog Experience Team
summary: |
Stream-Aligned team owning BookWorm's product catalog, customer reviews, and storefront/backoffice discovery experience.
members:
- nxnhan
---
## Mission & Topology Boundary
The **Catalog Experience Team** owns end-to-end delivery for book discovery, canonical product metadata, pricing, taxonomies, and customer feedback across [[domain|catalog]] and [[domain|reviews]]. Its cognitive-load boundary centers on authoritative product information and customer sentiment without owning shopping-cart state, order fulfillment, or underlying platform infrastructure. Explicitly **out of scope** are checkout sagas, payment/order lifecycle transitions, conversational agent orchestration, and shared messaging or hosting infrastructure.
## Team Profile & Interaction Modes
| Property | Value |
| :---------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------- |
| **Topology Type** | Stream-Aligned |
| **Primary Mission** | Deliver reliable book discovery, catalog management, and customer review capabilities |
| **Default Interaction Mode** | _X-as-a-Service_ (consumes platform capabilities); _Collaboration_ (with AI & Commerce teams on read contracts) |
| **Key Partner Teams** | [[team\|commerce-fulfillment-team]], [[team\|ai-capabilities-team]], [[team\|platform-engineering-team]], [[team\|architecture-enabling-team]] |
| **Escalation / Engagement Channel** | [GitHub Discussions](https://github.com/foxminchan/BookWorm/discussions) · [Issue Tracker](https://github.com/foxminchan/BookWorm/issues) |
## Owned Capabilities & Assets
- **Domains:** [[domain|catalog]], [[domain|reviews]]
- **Systems:** [[system|product-catalog-system]], [[system|rating-system]]
- **Services:** [[service|catalog-api]], [[service|catalog-ingestion]], [[service|rating-api]]
- **Agents:** [[agent|rating-agent]]
- **Frontend & Guides:** [[doc|frontend/006-microfrontend-architecture]]
- **Messaging Channels:** [[channel|bookworm.{env}.catalog.book-update-rating-failed]], [[channel|bookworm.{env}.rating.feedback-create]], [[channel|bookworm.{env}.rating.feedback-delete]]
- **With [[team|commerce-fulfillment-team]] (_X-as-a-Service_ / _Collaboration_):** Provides read-only gRPC book metadata and pricing lookups for basket enrichment and order price locking.
- **With [[team|ai-capabilities-team]] (_Collaboration_):** Partners on semantic search index maintenance and read-only catalog/review exposure for conversational discovery.
- **With [[team|platform-engineering-team]] (_X-as-a-Service_):** Consumes shared service defaults, Kafka messaging, observability, and scheduled vector-batch triggers.
- **With [[team|architecture-enabling-team]] (_Facilitating_):** Adopts ADR standards, contract evolution rules, and EventCatalog documentation practices.
## Working Agreements
- Publish versioned HTTP, gRPC, and integration event contracts before downstream teams consume new catalog or rating fields.
- Keep rating aggregations in [[domain|catalog]] strictly derived and rebuildable from authoritative feedback events in [[domain|reviews]].
- Escalate dead-letter queue anomalies in catalog or rating topics jointly with [[team|platform-engineering-team]].
:::note
Changes that alter shared gRPC book contracts or feedback integration events require a compatibility check with [[team|commerce-fulfillment-team]] and [[team|ai-capabilities-team]] prior to merge.
:::
---
id: commerce-fulfillment-team
name: Commerce Fulfillment Team
summary: |
Stream-Aligned team owning customer shopping baskets, checkout coordination, order lifecycle, and financial saga orchestration.
members:
- nxnhan
---
## Mission & Topology Boundary
The **Commerce Fulfillment Team** owns the end-to-end purchase journey across [[domain|shopping]] and [[domain|ordering]], from pre-purchase basket management through checkout saga execution and durable order lifecycle tracking. Its boundary focuses on transactional integrity, customer-scoped basket ownership, and locked purchase-time order records. Explicitly **out of scope** are canonical catalog metadata, customer review authoring, external payment settlement internals, and transactional email delivery infrastructure.
## Team Profile & Interaction Modes
| Property | Value |
| :---------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------- |
| **Topology Type** | Stream-Aligned |
| **Primary Mission** | Ensure accurate basket state, reliable checkout sagas, and durable order fulfillment |
| **Default Interaction Mode** | _X-as-a-Service_ (consumes catalog & platform services); _Collaboration_ (with Catalog on checkout pricing) |
| **Key Partner Teams** | [[team\|catalog-experience-team]], [[team\|platform-engineering-team]], [[team\|architecture-enabling-team]] |
| **Escalation / Engagement Channel** | [GitHub Discussions](https://github.com/foxminchan/BookWorm/discussions) · [Issue Tracker](https://github.com/foxminchan/BookWorm/issues) |
## Owned Capabilities & Assets
- **Domains:** [[domain|shopping]], [[domain|ordering]]
- **Systems:** [[system|cart-system]], [[system|order-system]], [[system|finance-system]]
- **Services:** [[service|basket-api]], [[service|order-api]], [[service|order-orchestration]]
- **Flows:** [[flow|user-checkout]]
- **Messaging Channels:** [[channel|bookworm.{env}.basket.delete-complete]], [[channel|bookworm.{env}.basket.delete-failed]], [[channel|bookworm.{env}.finance.place-order]], [[channel|bookworm.{env}.finance.complete-order]], [[channel|bookworm.{env}.finance.cancel-order]], [[channel|bookworm.{env}.finance.delete-basket-complete]], [[channel|bookworm.{env}.finance.delete-basket-failed]], [[channel|bookworm.{env}.ordering.user-checked-out]], [[channel|bookworm.{env}.ordering.order-status-change-to-complete]], [[channel|bookworm.{env}.ordering.order-status-change-to-cancel]]
- **With [[team|catalog-experience-team]] (_X-as-a-Service_):** Calls catalog gRPC endpoints to enrich basket views and lock authoritative book prices at checkout.
- **With [[team|platform-engineering-team]] (_X-as-a-Service_):** Delegates customer order email delivery via asynchronous notification commands and relies on shared messaging, identity, and observability primitives.
- **With [[team|architecture-enabling-team]] (_Facilitating_):** Aligns saga state machines, idempotency guarantees, and contract evolution with platform ADRs.
## Working Agreements
- Never share mutable persistence between [[domain|shopping]] and [[domain|ordering]]; coordinate checkout cleanup and order transitions exclusively through documented events and commands.
- Lock book titles and unit prices onto order items at purchase time so historical orders remain immutable when catalog prices change.
- Delegate notification rendering and SMTP dispatch to [[service|notification-api]] rather than embedding email provider logic in ordering or finance services.
:::note
Any change to checkout saga states or basket cleanup contracts must preserve idempotent retry semantics across [[flow|user-checkout]].
:::
---
id: platform-engineering-team
name: Platform Engineering Team
summary: |
Platform team providing BookWorm's thinnest viable platform—orchestration, messaging fabric, scheduling, notifications, observability, identity, and privacy guardrails.
members:
- nxnhan
---
## Mission & Topology Boundary
The **Platform Engineering Team** builds and operates BookWorm's shared technical foundation across [[domain|platform]], [[system|identity-provider]], and [[system|data-privacy]], delivering self-service paved roads that reduce cognitive load for stream-aligned and complicated-subsystem teams. It owns service defaults, distributed orchestration, Kafka/Wolverine messaging infrastructure, recurring job scheduling, transactional email delivery, telemetry pipelines, and security/PII boundaries. Explicitly **out of scope** are domain-specific business rules, catalog pricing, basket contents, order lifecycle decisions, and conversational agent prompts.
## Team Profile & Interaction Modes
| Property | Value |
| :---------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- |
| **Topology Type** | Platform |
| **Primary Mission** | Deliver reliable, observable, secure paved roads and shared operational capabilities (_X-as-a-Service_) |
| **Default Interaction Mode** | _X-as-a-Service_ (primary); _Collaboration_ (short-lived onboarding of new platform primitives) |
| **Key Partner Teams** | [[team\|catalog-experience-team]], [[team\|commerce-fulfillment-team]], [[team\|ai-capabilities-team]], [[team\|architecture-enabling-team]] |
| **Escalation / Engagement Channel** | [GitHub Discussions](https://github.com/foxminchan/BookWorm/discussions) · [[doc\|operational/003-incident-response-and-runbooks]] |
## Owned Capabilities & Assets
- **Domain:** [[domain|platform]]
- **Internal Systems:** [[system|notification-system]], [[system|scheduler-system]], [[system|sendgrid]]
- **External Platform Systems:** [[system|identity-provider]], [[system|data-privacy]]
- **Services:** [[service|notification-api]], [[service|scheduler-service]], [[service|sendgrid-api]], [[service|presidio-api]], [[service|oauth-api]]
- **Flows & Channels:** [[flow|notification-delivery]], and all dead-letter queue channels (`*.dead-letter-queue`)
- **Platform & Operations Guides:** [[doc|platform/001-platform-overview]], [[doc|operational/001-azure-deployment-guide]], [[doc|operational/003-incident-response-and-runbooks]]
- **With [[team|catalog-experience-team]] (_X-as-a-Service_):** Provides scheduled vector-batch triggers, OpenTelemetry pipelines, and dead-letter queue monitoring.
- **With [[team|commerce-fulfillment-team]] (_X-as-a-Service_):** Operates transactional order notification delivery via [[service|notification-api]] and [[service|sendgrid-api]], plus durable outbox/inbox messaging defaults.
- **With [[team|ai-capabilities-team]] (_X-as-a-Service_ / _Collaboration_):** Supplies fail-closed PII detection and anonymization via [[system|data-privacy]] and agent identity boundaries via [[system|identity-provider]].
- **With [[team|architecture-enabling-team]] (_Collaboration_):** Co-evolves platform ADRs covering resilience, correlation, observability, and environment configuration.
## Platform Working Agreements
- **Paved-Road Self-Service:** All services adopt shared Aspire service defaults, OpenTelemetry instrumentation, and resilience policies out of the box without bespoke per-service wiring.
- **Zero Business State Ownership:** Platform services never authoritatively own books, baskets, orders, or reviews; they transport, schedule, authenticate, or sanitize payloads on behalf of owning domains.
- **Operational Guardrails:** Dead-letter queues, secret rotation, backup/restore procedures, and deployment pipelines are maintained with documented runbooks.
- **Requesting Platform Changes:** Stream-aligned teams propose new shared capabilities or infrastructure adjustments via [GitHub Discussions](https://github.com/foxminchan/BookWorm/discussions) before introducing custom workarounds.
:::note
For production incidents, dead-letter queue spikes, or identity/PII gateway issues, start with [[doc|operational/003-incident-response-and-runbooks]].
:::
---
id: nxnhan
name: Nhan Nguyen
avatarUrl: https://avatars.githubusercontent.com/u/56079798?v=4
role: Software Engineer
email: nguyenxuannhan407@gmail.com
---
## Overview
Nhan Nguyen (`@foxminchan`) is the principal maintainer of BookWorm, focusing on cloud-native distributed systems, .NET microservices, event-driven architecture, and platform engineering. Across the catalog, Nhan stewards all five Team Topologies groups to keep bounded-context ownership, asynchronous messaging contracts, AI governance, and developer experience aligned.
## Team Memberships & Focus Areas
| Team | Topology Type | Primary Focus |
| :----------------------------------- | :-------------------- | :------------------------------------------------------------------------------------------------------------------------------ |
| [[team\|catalog-experience-team]] | Stream-Aligned | Catalog discovery, taxonomy, pricing metadata, customer reviews, and storefront/backoffice experience |
| [[team\|commerce-fulfillment-team]] | Stream-Aligned | Customer baskets, checkout orchestration, order lifecycle, and financial saga coordination |
| [[team\|platform-engineering-team]] | Platform | Shared service defaults, messaging fabric, scheduling, transactional notifications, observability, identity, and PII protection |
| [[team\|ai-capabilities-team]] | Complicated-Subsystem | Multi-agent conversational discovery, MCP/A2A protocols, vector ingestion, and AI governance guardrails |
| [[team\|architecture-enabling-team]] | Enabling | Architecture decision records, arc42 documentation, testing standards, and EventCatalog curation |
## How to Engage
- **Architecture Reviews & Proposals:** Open a thread in [GitHub Discussions](https://github.com/foxminchan/BookWorm/discussions) for cross-domain contract changes, new bounded-context integrations, or ADR proposals.
- **PR Ownership & Reviews:** Route pull requests to the owning team boundary; follow [[doc|development/006-pull-request-process]] and [[doc|development/004-engineering-standards]] before requesting review.
- **Escalation & Defects:** Report bugs or feature requests through the repository's GitHub issue templates rather than direct email.
- **Direct Profiles:** [GitHub (@foxminchan)](https://github.com/foxminchan) | [LinkedIn](https://www.linkedin.com/in/nxnhan/)
:::note
For security vulnerabilities or sensitive operational disclosures, follow the repository's private security reporting policy rather than opening public issues.
:::
---
id: author
name: Author
version: 1.0.0
identifier: id
aggregateRoot: true
summary: Represents a credited author of one or more books in the product catalog, enforcing display-name validity and referential integrity against linked titles.
owners:
- catalog-experience-team
badges:
- content: Aggregate Root
backgroundColor: blue
textColor: blue
properties:
- name: id
type: UUID
required: true
description: Globally unique UUIDv7 identifier for the author.
- name: name
type: string
required: true
description: Author display name (non-whitespace, up to 100 characters).
---
## Domain Role & Boundary
**Author** is an Aggregate Root in the [[domain|catalog]] bounded context representing a person credited on one or more books. Owned by [[service|catalog-api]], it serves as the authoritative source for author identity and display names across storefront discovery and backoffice management. It explicitly does **not** own book metadata, publication details, or customer review attribution, which remain separate aggregates or bounded-context concerns.
## Entity Profile
| Property | Value |
| :---------------------------- | :----------------------------------------------------------- |
| **Bounded Context / Domain** | [[domain\|catalog]] |
| **Owning Service** | [[service\|catalog-api]] |
| **DDD Role** | Aggregate Root |
| **Identifier Strategy** | UUIDv7 generated at persistence |
| **Persistence Store** | Catalog relational database (`authors`) |
| **Deletion Semantics** | Hard-delete, restricted while linked to any [[entity\|book]] |
| **Concurrency Control** | Last-write-wins (no optimistic concurrency token) |
| **PII / Data Classification** | Public catalog metadata (non-PII) |
## Attributes & Constraints
| Attribute | Business Rule / Constraint | Sensitivity / Notes |
| :-------- | :--------------------------------------------------------------- | :----------------------- |
| `id` | Immutable primary identifier generated as UUIDv7. | Public identifier |
| `name` | Required; must contain non-whitespace text up to 100 characters. | Public display attribute |
## Domain Invariants & Lifecycle
- **Non-empty display name:** Creating or renaming an author with a null, empty, or whitespace-only name is rejected by the domain model.
- **Referential deletion guard:** An author cannot be deleted while at least one [[entity|book]] references it; all book associations must be removed or reassigned first.
- **Lifecycle events:** Creation, renaming, and removal emit internal domain events within [[service|catalog-api]] to keep catalog projections and search indexes synchronized.
:::warning
Deleting an author is a permanent hard-delete operation. Unlike [[entity|book]], authors do not support soft-delete recovery once all book links are removed.
:::
## Relationships & Associated Operations
| Category | Resource | Role / Interaction |
| :-------------------- | :------------------------------------------------------------------------------ | :------------------------------------------------------------ |
| **Related Entities** | [[entity\|book]] | Many-to-many attribution linking authors to catalog titles |
| **Mutating Commands** | [[command\|CreateAuthor]], [[command\|UpdateAuthor]], [[command\|DeleteAuthor]] | Create, rename, or remove an author record |
| **Read Queries** | [[query\|ListAuthors]], [[query\|ListAuthorsGrpc]] | Paginated storefront/backoffice listings and internal lookups |
---
id: basket
name: Basket
version: 1.0.0
identifier: customerId
aggregateRoot: true
summary: Customer-scoped, mutable pre-order collection of requested books and quantities managed prior to checkout.
owners:
- commerce-fulfillment-team
badges:
- content: Aggregate Root
backgroundColor: blue
textColor: blue
properties:
- name: customerId
type: string
required: true
description: Authenticated customer identifier scoping the basket (one active basket per customer).
- name: items
type: array
required: true
description: Requested book entries, replaced atomically as a complete set on update.
references: basket-item
referencesIdentifier: bookId
relationType: contains
items:
type: basket-item
- name: createdAt
type: datetime
required: true
description: UTC timestamp when the basket was created.
- name: lastModifiedAt
type: datetime
required: false
description: UTC timestamp of the most recent basket update.
---
## Domain Role & Boundary
**Basket** is the Aggregate Root in the [[domain|shopping]] bounded context representing an authenticated customer's mutable pre-purchase selection of books. Owned by [[service|basket-api]], it provides sub-millisecond read and write access during storefront browsing and supplies checkout snapshots to [[service|order-api]]. It explicitly does **not** own product pricing or availability (resolved dynamically from [[domain|catalog]]), inventory reservations, or accepted purchase records (owned by [[domain|ordering]]).
## Entity Profile
| Property | Value |
| :---------------------------- | :------------------------------------------------------------------------------------ |
| **Bounded Context / Domain** | [[domain\|shopping]] |
| **Owning Service** | [[service\|basket-api]] |
| **DDD Role** | Aggregate Root |
| **Identifier Strategy** | Authenticated customer ID (GUID-formatted string, derived from access token) |
| **Persistence Store** | Shopping key-value store (`basket:{customerId}`, no SQL database) |
| **Deletion Semantics** | Hard-delete (customer clear or idempotent post-checkout cleanup; no automatic TTL) |
| **Concurrency Control** | Last-write-wins with whole-set replacement; idempotent message handling on cleanup |
| **PII / Data Classification** | Internal customer-scoped identifier (`customerId` only; no names or addresses stored) |
## Attributes & Constraints
| Attribute | Business Rule / Constraint | Sensitivity / Notes |
| :---------------------------- | :---------------------------------------------------------------------------------------------------- | :-------------------- |
| `customerId` | Required; derived strictly from the authenticated customer token (one basket per customer). | Customer-scoped key |
| `items` | Required; must contain at least one [[entity\|basket-item]] on create and update at the API boundary. | Whole-set replacement |
| `createdAt`, `lastModifiedAt` | UTC audit timestamps serialized with the basket payload. | Metadata |
## Domain Invariants & Lifecycle
- **Authenticated ownership:** A basket always belongs to a single authenticated customer; anonymous baskets are not persisted.
- **Non-empty creation and update:** Creating or updating a basket via the API requires at least one valid [[entity|basket-item]]. To empty a basket, the customer explicitly deletes it.
- **Whole-set replacement:** Updating a basket replaces the entire `items` collection rather than merging partial line-item diffs.
- **Post-checkout cleanup:** Upon receiving [[command|PlaceOrderCommand]] from [[service|order-orchestration]], [[service|basket-api]] deletes the basket idempotently and publishes [[event|BasketDeletedCompleteIntegrationEvent]] or [[event|BasketDeletedFailedIntegrationEvent]].
:::warning
A basket represents mutable shopping intent—never a confirmed order or an inventory hold. If a basket fails to delete after checkout, [[domain|ordering]] compensates rather than allowing stale basket state to be misread as an active order.
:::
## Relationships & Associated Operations
| Category | Resource | Role / Interaction |
| :--------------------------- | :-------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------ |
| **Related Entities** | [[entity\|basket-item]] | Embedded collection of requested books and quantities |
| **Cross-Context References** | [[entity\|book]], [[entity\|order]] | Items reference Catalog books; checkout hands off to Ordering |
| **Mutating Commands** | [[command\|CreateBasket]], [[command\|UpdateBasket]], [[command\|DeleteBasket]], [[command\|PlaceOrderCommand]] | Create, replace, or delete the customer's basket |
| **Read Queries** | [[query\|GetBasket]], [[query\|GetBasketGrpc]] | Enriched storefront read and internal checkout snapshot |
| **Emitted Events** | [[event\|BasketDeletedCompleteIntegrationEvent]], [[event\|BasketDeletedFailedIntegrationEvent]] | Report post-checkout cleanup outcome to Finance |
---
id: basket-item
name: Basket Item
version: 1.0.0
identifier: bookId
aggregateRoot: false
summary: Child entry within a Basket pairing a Catalog book identifier with a positive requested quantity.
owners:
- commerce-fulfillment-team
badges:
- content: Child Entity
backgroundColor: teal
textColor: teal
properties:
- name: bookId
type: UUID
required: true
description: Cross-context identifier of the requested Catalog Book.
references: book
referencesIdentifier: id
relationType: references
- name: quantity
type: integer
required: true
description: Positive number of copies requested (must be greater than zero).
---
## Domain Role & Boundary
**Basket Item** is a child object owned by the [[entity|basket]] Aggregate Root in the [[domain|shopping]] bounded context, recording a single requested book identifier and its desired quantity. Stored embedded inside the parent basket payload by [[service|basket-api]], it is enriched at read time with live titles and prices from [[service|catalog-api]]. It explicitly does **not** store or lock book titles, descriptions, or prices—those remain owned by [[domain|catalog]] until checkout locks them onto an [[entity|order-item]].
## Entity Profile
| Property | Value |
| :---------------------------- | :-------------------------------------------------------------------------------------------------- |
| **Bounded Context / Domain** | [[domain\|shopping]] |
| **Owning Service** | [[service\|basket-api]] |
| **DDD Role** | Child Entity / Value Object (embedded in [[entity\|basket]]) |
| **Identifier Strategy** | Scoped by Catalog `bookId` within parent [[entity\|basket]] |
| **Persistence Store** | Embedded inside parent `basket:{customerId}` key-value payload |
| **Deletion Semantics** | Removed by replacing parent `items` without the entry, or when parent [[entity\|basket]] is deleted |
| **Concurrency Control** | Governed by parent [[entity\|basket]] whole-set replacement |
| **PII / Data Classification** | Internal pre-order item reference (non-PII) |
## Attributes & Constraints
| Attribute | Business Rule / Constraint | Sensitivity / Notes |
| :--------- | :----------------------------------------------------------------------------- | :------------------------- |
| `bookId` | Required non-empty UUID referencing a [[entity\|book]] in [[domain\|catalog]]. | Cross-context ID reference |
| `quantity` | Required integer strictly greater than zero (`> 0`). | Domain invariant |
## Domain Invariants & Lifecycle
- **Positive quantity:** Zero or negative quantities are rejected; removing an item requires submitting the updated basket without that item.
- **No persisted price snapshot:** Basket items intentionally omit prices so customers always see current [[domain|catalog]] pricing while browsing.
- **Read-time enrichment:** When reading a basket, [[service|basket-api]] batches distinct `bookId` values into a single lookup against [[service|catalog-api]] to attach `name`, `price`, and `priceSale` to the response.
:::note
If [[service|catalog-api]] returns no match for a `bookId` during read-time enrichment (for example, if the book was soft-deleted), the item remains in the basket response with unpopulated display fields rather than inventing metadata.
:::
## Relationships & Associated Operations
| Category | Resource | Role / Interaction |
| :--------------------------- | :--------------------------------------------------- | :-------------------------------------------------------------- |
| **Parent Aggregate** | [[entity\|basket]] | Embedded child item within the customer's basket |
| **Cross-Context References** | [[entity\|book]] | Referenced strictly by `bookId` for live price/title enrichment |
| **Mutating Commands** | [[command\|CreateBasket]], [[command\|UpdateBasket]] | Replaced as part of parent basket mutations |
| **Read Queries** | [[query\|GetBasket]], [[query\|GetBasketGrpc]] | Returned enriched to storefront or raw to checkout |
---
id: book
name: Book
version: 1.0.0
identifier: id
aggregateRoot: true
summary: Canonical sellable title in the product catalog, encapsulating descriptive metadata, pricing, stock availability, taxonomy links, and derived rating summaries.
owners:
- catalog-experience-team
badges:
- content: Aggregate Root
backgroundColor: blue
textColor: blue
properties:
- name: id
type: UUID
required: true
description: Globally unique UUIDv7 identifier for the book.
- name: name
type: string
required: true
description: Display title of the book (non-whitespace, up to 50 characters).
- name: description
type: string
required: true
description: Synopsis or editorial description of the book (up to 1,000 characters).
- name: image
type: string
required: false
description: Cover image asset reference or URL (up to 255 characters).
- name: price
type: object
required: true
description: Regular price and optional promotional sale price.
properties:
- name: originalPrice
type: decimal
required: true
description: Regular non-negative unit price.
- name: discountPrice
type: decimal
required: false
description: Optional sale price; must be non-negative and not exceed originalPrice.
- name: status
type: string
required: true
description: Catalog listing availability state.
enum:
- InStock
- OutOfStock
- name: averageRating
type: double
required: true
description: Derived mean rating projected asynchronously from customer feedback.
- name: totalReviews
type: integer
required: true
description: Derived count of customer reviews projected asynchronously.
- name: categoryId
type: UUID
required: false
description: Identifier of the assigned Category, if any.
references: category
referencesIdentifier: id
relationType: belongsTo
- name: publisherId
type: UUID
required: false
description: Identifier of the assigned Publisher, if any.
references: publisher
referencesIdentifier: id
relationType: publishedBy
- name: authorIds
type: array
required: false
description: Identifiers of the Authors credited on this book.
references: author
referencesIdentifier: id
relationType: writtenBy
items:
type: UUID
- name: isDeleted
type: boolean
required: true
description: Soft-delete marker hiding retired books from standard queries.
- name: createdAt
type: datetime
required: true
description: UTC timestamp when the book was created.
- name: lastModifiedAt
type: datetime
required: false
description: UTC timestamp of the most recent modification.
- name: rowVersion
type: string
required: true
description: Persistence-managed optimistic concurrency token.
---
## Domain Role & Boundary
**Book** is the central Aggregate Root in the [[domain|catalog]] bounded context, representing a sellable title with its descriptive metadata, pricing value object, availability status, taxonomy associations, and derived rating summary. Owned by [[service|catalog-api]] (with vector index synchronization handled by [[service|catalog-ingestion]]), it serves as the single source of truth for product discovery and checkout price resolution. It explicitly does **not** own customer shopping baskets ([[domain|shopping]]), locked purchase-time order prices ([[domain|ordering]]), or individual customer reviews ([[domain|reviews]]).
## Entity Profile
| Property | Value |
| :---------------------------- | :-------------------------------------------------------------------------- |
| **Bounded Context / Domain** | [[domain\|catalog]] |
| **Owning Service** | [[service\|catalog-api]] |
| **DDD Role** | Aggregate Root |
| **Identifier Strategy** | UUIDv7 generated at persistence |
| **Persistence Store** | Catalog relational database (`books`) |
| **Deletion Semantics** | Soft-delete (`isDeleted` flag excludes retired books from standard queries) |
| **Concurrency Control** | Optimistic concurrency via persistence-managed row version |
| **PII / Data Classification** | Public catalog metadata (non-PII) |
## Attributes & Constraints
| Attribute | Business Rule / Constraint | Sensitivity / Notes |
| :------------------------------ | :----------------------------------------------------------------------------------------- | :--------------------------- |
| `name` | Required; non-whitespace, max 50 characters, indexed for lookup. | Public |
| `description` | Required on persistence and update; non-whitespace, max 1,000 characters. | Public |
| `price` | Embedded value object (`originalPrice >= 0`; `discountPrice >= 0` and `<= originalPrice`). | Monetary precision `(18, 2)` |
| `status` | Defaults to `InStock`; transitions between `InStock` and `OutOfStock`. | Availability indicator only |
| `averageRating`, `totalReviews` | Default to `0.0` and `0`; updated exclusively via asynchronous feedback events. | Derived projection |
| `categoryId`, `publisherId` | Nullable taxonomy references; cleared to null if the parent taxonomy is deleted. | Optional foreign keys |
## Domain Invariants & Lifecycle
- **Pricing integrity:** Original price cannot be negative, and an optional discount price must be non-negative and never exceed the original price.
- **Availability semantics:** New books default to `InStock`. Catalog availability indicates listing status for discovery and never acts as an inventory reservation or fulfillment guarantee.
- **Derived rating summary:** `averageRating` and `totalReviews` are rebuilt from [[domain|reviews]] events; removing the last review resets both fields to `0`.
- **Soft-delete isolation:** Deleting a book marks `isDeleted = true` rather than removing the record, automatically hiding the book and its author links from standard catalog queries.
- **Taxonomy replacement:** Updating a book replaces its credited [[entity|author]] links as a complete set.
:::warning
Catalog price updates never retroactively change prices on existing [[entity|order-item]] records. Conversely, if a [[domain|reviews]] event arrives for a soft-deleted or nonexistent book, [[service|catalog-api]] emits [[event|BookUpdatedRatingFailedIntegrationEvent]] so Reviews can compensate.
:::
## Relationships & Associated Operations
| Category | Resource | Role / Interaction |
| :--------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------- |
| **Related Entities** | [[entity\|author]], [[entity\|category]], [[entity\|publisher]] | Intra-context taxonomy and authorship relationships |
| **Cross-Context References** | [[entity\|feedback]], [[entity\|basket-item]], [[entity\|order-item]] | Referenced strictly by `bookId` across service boundaries |
| **Mutating Commands** | [[command\|CreateBook]], [[command\|UpdateBook]], [[command\|DeleteBook]] | Manage book lifecycle, metadata, and soft deletion |
| **Read Queries** | [[query\|GetBook]], [[query\|ListBooks]], [[query\|GetBookGrpc]], [[query\|GetBooksGrpc]], [[query\|ListBooksGrpc]], [[query\|GetBookDetailsGrpc]], [[query\|GetDashboardGrpc]] | HTTP discovery, hybrid search, and internal gRPC lookups |
| **Events** | [[event\|FeedbackCreatedIntegrationEvent]], [[event\|FeedbackDeletedIntegrationEvent]], [[event\|BookUpdatedRatingFailedIntegrationEvent]] | Consume rating deltas and signal missing-book compensation |
---
id: buyer
name: Buyer
version: 1.0.0
identifier: id
aggregateRoot: true
summary: Represents a customer's ordering profile and delivery address within the Ordering bounded context.
owners:
- commerce-fulfillment-team
badges:
- content: Aggregate Root
backgroundColor: blue
textColor: blue
- content: Contains PII
backgroundColor: yellow
textColor: yellow
properties:
- name: id
type: UUID
required: true
description: Identifier associated with the authenticated customer.
- name: name
type: string
required: true
description: Buyer's display name (non-whitespace, up to 20 characters).
- name: address
type: object
required: true
description: Buyer's delivery address value object.
properties:
- name: street
type: string
required: true
description: Street address line (non-whitespace, up to 50 characters).
- name: city
type: string
required: true
description: City name (non-whitespace, up to 50 characters).
- name: province
type: string
required: true
description: Province or state name (non-whitespace, up to 50 characters).
---
## Domain Role & Boundary
**Buyer** is an Aggregate Root in the [[domain|ordering]] bounded context representing a customer's ordering profile and delivery address. Owned by [[service|order-api]], it links an authenticated customer identity to their placed [[entity|order]] history. It explicitly does **not** own authentication credentials or roles (owned by [[system|identity-provider]]) or pre-purchase shopping baskets (owned by [[domain|shopping]]).
## Entity Profile
| Property | Value |
| :---------------------------- | :-------------------------------------------------------------------------------------------------- |
| **Bounded Context / Domain** | [[domain\|ordering]] |
| **Owning Service** | [[service\|order-api]] |
| **DDD Role** | Aggregate Root |
| **Identifier Strategy** | Authenticated customer UUID |
| **Persistence Store** | Ordering relational database (`buyers`) |
| **Deletion Semantics** | Hard-delete; clears `buyerId` to null on existing [[entity\|order]] records without deleting orders |
| **Concurrency Control** | Buyer-scoped distributed write locks during mutations |
| **PII / Data Classification** | Confidential PII (`name`, `address`) — redacted from logs, events, and incident reports |
## Attributes & Constraints
| Attribute | Business Rule / Constraint | Sensitivity / Notes |
| :-------- | :------------------------------------------------------------------------------------------------ | :------------------------------ |
| `id` | Required; derived from the authenticated customer identity. | Internal/Customer identifier |
| `name` | Required; non-whitespace, max 20 characters. | PII — redact in structured logs |
| `address` | Embedded value object (`street`, `city`, `province` each required, non-whitespace, max 50 chars). | PII — redact in structured logs |
## Domain Invariants & Lifecycle
- **Required profile fields:** Both the buyer's name and all three delivery address components (`street`, `city`, `province`) must be non-whitespace; invalid inputs are rejected at creation and update.
- **Whole-address replacement:** Updating a buyer's delivery address replaces the entire `address` value object atomically rather than patching individual fields.
- **Order preservation on delete:** Deleting a buyer removes the buyer profile while preserving historical [[entity|order]] records with `buyerId` set to null.
:::warning
`name` and `address` are Personal Identifiable Information (PII). Never emit raw buyer names or street addresses into structured application logs, integration events, or telemetry traces.
:::
## Relationships & Associated Operations
| Category | Resource | Role / Interaction |
| :-------------------- | :----------------------------------------------------------------------------- | :------------------------------------------------------------------ |
| **Related Entities** | [[entity\|order]] | One buyer places zero or more orders |
| **Mutating Commands** | [[command\|CreateBuyer]], [[command\|UpdateAddress]], [[command\|DeleteBuyer]] | Register buyer profile, replace delivery address, or remove profile |
| **Read Queries** | [[query\|GetBuyer]], [[query\|ListBuyers]] | Retrieve individual buyer details or paginated buyer lists |
---
id: category
name: Category
version: 1.0.0
identifier: id
aggregateRoot: true
summary: Single-level taxonomy classification grouping books by subject or genre within the product catalog.
owners:
- catalog-experience-team
badges:
- content: Aggregate Root
backgroundColor: blue
textColor: blue
properties:
- name: id
type: UUID
required: true
description: Globally unique UUIDv7 identifier for the category.
- name: name
type: string
required: true
description: Unique category display name (non-whitespace, up to 50 characters).
---
## Domain Role & Boundary
**Category** is an Aggregate Root in the [[domain|catalog]] bounded context representing a single-level subject or genre classification for books. Owned by [[service|catalog-api]], it provides a controlled vocabulary for storefront filtering and backoffice organization. It explicitly does **not** own a collection of books or hierarchical parent-child category trees; books reference their category by identifier.
## Entity Profile
| Property | Value |
| :---------------------------- | :---------------------------------------------------------------------------- |
| **Bounded Context / Domain** | [[domain\|catalog]] |
| **Owning Service** | [[service\|catalog-api]] |
| **DDD Role** | Aggregate Root |
| **Identifier Strategy** | UUIDv7 generated at persistence |
| **Persistence Store** | Catalog relational database (`categories`) |
| **Deletion Semantics** | Hard-delete; clears `categoryId` to null on affected [[entity\|book]] records |
| **Concurrency Control** | Last-write-wins (unique name constraint enforced by store) |
| **PII / Data Classification** | Public catalog metadata (non-PII) |
## Attributes & Constraints
| Attribute | Business Rule / Constraint | Sensitivity / Notes |
| :-------- | :------------------------------------------------------------------------------ | :-------------------- |
| `id` | Immutable primary identifier generated as UUIDv7. | Public identifier |
| `name` | Required, non-whitespace, max 50 characters, globally unique across categories. | Unique index enforced |
## Domain Invariants & Lifecycle
- **Name required:** Creating or renaming a category with a null, empty, or whitespace-only name is rejected.
- **Global uniqueness:** Duplicate category names are rejected by the persistence layer to keep storefront filters unambiguous.
- **Non-cascading hard delete:** Removing a category permanently deletes the category record and sets `categoryId` to null on any linked [[entity|book]] without deleting the books themselves.
- **Lifecycle events:** Creation, renaming, and deletion raise internal domain events within [[service|catalog-api]].
:::note
Because categories are flat (single-level) and hard-deleted, renaming a category immediately reflects across all referencing books without migrating child trees.
:::
## Relationships & Associated Operations
| Category | Resource | Role / Interaction |
| :-------------------- | :------------------------------------------------------------------------------------ | :---------------------------------------------------------------- |
| **Related Entities** | [[entity\|book]] | One category classifies zero or more books via `books.categoryId` |
| **Mutating Commands** | [[command\|CreateCategory]], [[command\|UpdateCategory]], [[command\|DeleteCategory]] | Create, rename, or remove a category |
| **Read Queries** | [[query\|ListCategories]], [[query\|ListCategoriesGrpc]] | Storefront filter lists and internal gRPC lookups |
---
id: feedback
name: Feedback
version: 1.0.0
identifier: id
aggregateRoot: true
summary: Represents an individual customer's rating and optional written review for a Catalog book.
owners:
- catalog-experience-team
badges:
- content: Aggregate Root
backgroundColor: blue
textColor: blue
- content: Contains PII
backgroundColor: yellow
textColor: yellow
properties:
- name: id
type: UUID
required: true
description: Globally unique UUIDv7 identifier generated when the feedback is created.
- name: bookId
type: UUID
required: true
description: Cross-context identifier of the Catalog Book being reviewed (also the partition key).
references: book
referencesIdentifier: id
relationType: references
- name: firstName
type: string
required: true
description: Reviewer's first name (non-empty, up to 50 characters).
- name: lastName
type: string
required: true
description: Reviewer's last name (non-empty, up to 50 characters).
- name: comment
type: string
required: false
description: Optional written review text (up to 1,000 characters).
- name: rating
type: integer
required: true
description: Integer satisfaction score from 0 through 5, inclusive.
- name: createdAt
type: datetime
required: true
description: UTC timestamp when the feedback was submitted.
- name: lastModifiedAt
type: datetime
required: false
description: UTC timestamp of the most recent modification.
---
## Domain Role & Boundary
**Feedback** is the Aggregate Root in the [[domain|reviews]] bounded context representing one customer's numeric rating and optional written review for a book. Owned by [[service|rating-api]], it serves as the authoritative source for individual customer sentiment and AI-assisted review summarization via [[agent|rating-agent]]. It explicitly does **not** own canonical book metadata or the aggregate rating summary displayed on product listings (both owned by [[domain|catalog]]).
## Entity Profile
| Property | Value |
| :---------------------------- | :---------------------------------------------------------------------------------------- |
| **Bounded Context / Domain** | [[domain\|reviews]] |
| **Owning Service** | [[service\|rating-api]] |
| **DDD Role** | Aggregate Root |
| **Identifier Strategy** | UUIDv7 generated at creation |
| **Persistence Store** | Reviews document store (`feedbacks`, partitioned by `bookId`) |
| **Deletion Semantics** | Hard-delete (explicit admin removal or automated compensation) |
| **Concurrency Control** | Optimistic concurrency via document ETag |
| **PII / Data Classification** | Confidential PII (`firstName`, `lastName`) — screened fail-closed before AI summarization |
## Attributes & Constraints
| Attribute | Business Rule / Constraint | Sensitivity / Notes |
| :---------------------- | :--------------------------------------------------------------------------------------------------- | :------------------------------------ |
| `bookId` | Required non-empty UUID; serves as both the cross-context book reference and document partition key. | Cross-context ID reference |
| `firstName`, `lastName` | Required at API boundary; non-empty, max 50 characters each. | PII — redacted in logs and AI prompts |
| `comment` | Optional free text, max 1,000 characters. | Screened for PII during summarization |
| `rating` | Required integer from `0` through `5`, inclusive. | Domain invariant |
## Domain Invariants & Lifecycle
- **Bounded rating score:** Ratings outside `0`–`5` (inclusive) are rejected by the domain model.
- **Asynchronous rating projection:** Creating or deleting feedback emits integration events so [[service|catalog-api]] can update [[entity|book]] `averageRating` and `totalReviews` eventually.
- **Compensating deletion:** If [[service|catalog-api]] rejects a rating delta because the target book does not exist or was soft-deleted, [[service|rating-api]] performs an idempotent compensating delete on the orphaned feedback.
- **Read-only AI summarization:** [[agent|rating-agent]] reads feedback for a book and screens inputs/outputs fail-closed through [[service|presidio-api]] without mutating persisted records.
:::warning
Because Reviews references [[entity|book]] strictly by `bookId` without synchronous Catalog validation on write, orphaned feedback is resolved asynchronously via [[event|BookUpdatedRatingFailedIntegrationEvent]]. Additionally, reviewer uniqueness per `(bookId, firstName, lastName)` is enforced at the application/conflict layer rather than via a database unique-key policy.
:::
## Relationships & Associated Operations
| Category | Resource | Role / Interaction |
| :--------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------- |
| **Cross-Context References** | [[entity\|book]] | Referenced strictly by `bookId` across service boundaries |
| **Mutating Commands** | [[command\|CreateFeedback]], [[command\|DeleteFeedback]] | Submit a new review or remove an existing review |
| **Read Queries** | [[query\|ListFeedbacks]], [[query\|SummarizeFeedback]] | List book reviews or generate a privacy-screened AI summary |
| **Events** | [[event\|FeedbackCreatedIntegrationEvent]], [[event\|FeedbackDeletedIntegrationEvent]], [[event\|BookUpdatedRatingFailedIntegrationEvent]] | Propagate rating deltas to Catalog and handle compensation |
---
id: order
name: Order
version: 1.0.0
identifier: id
aggregateRoot: true
summary: Durable purchase record owned by a Buyer, capturing immutable purchase-time line items and governing order lifecycle transitions.
owners:
- commerce-fulfillment-team
badges:
- content: Aggregate Root
backgroundColor: blue
textColor: blue
properties:
- name: id
type: UUID
required: true
description: Globally unique UUIDv7 identifier for the order.
- name: buyerId
type: UUID
required: false
description: Identifier of the Buyer who placed the order (nullable if the buyer profile is later deleted).
references: buyer
referencesIdentifier: id
relationType: placedBy
- name: status
type: string
required: true
description: Authoritative business lifecycle status owned by Ordering.
enum:
- New
- Completed
- Cancelled
- name: note
type: string
required: false
description: Optional customer delivery or order note (up to 500 characters).
- name: orderItems
type: array
required: true
description: Purchase-time line items composing the order.
references: order-item
referencesIdentifier: id
relationType: contains
items:
type: order-item
- name: totalPrice
type: decimal
required: true
description: Computed sum of unit price multiplied by quantity across all order items.
- name: isDeleted
type: boolean
required: true
description: Soft-delete marker independent of the order's business status.
- name: createdAt
type: datetime
required: true
description: UTC timestamp when the order was placed.
- name: lastModifiedAt
type: datetime
required: false
description: UTC timestamp of the most recent modification.
- name: rowVersion
type: string
required: true
description: Persistence-managed optimistic concurrency token.
---
## Domain Role & Boundary
**Order** is the central Aggregate Root in the [[domain|ordering]] bounded context, representing an accepted customer purchase with its locked purchase-time [[entity|order-item]] lines and authoritative lifecycle status. Owned by [[service|order-api]] (with post-checkout saga coordination by [[service|order-orchestration]]), it records what was bought and at what price. It explicitly does **not** own pre-purchase mutable baskets ([[domain|shopping]]), live catalog metadata ([[domain|catalog]]), payment settlement, or email transport ([[domain|platform]]).
## Entity Profile
| Property | Value |
| :---------------------------- | :------------------------------------------------------------------------------------------------------ |
| **Bounded Context / Domain** | [[domain\|ordering]] |
| **Owning Service** | [[service\|order-api]] |
| **DDD Role** | Aggregate Root |
| **Identifier Strategy** | UUIDv7 generated at persistence |
| **Persistence Store** | Ordering relational database (`orders`) and event-sourced summary stream |
| **Deletion Semantics** | Soft-delete (`isDeleted` flag excludes deleted orders and items without altering `status`) |
| **Concurrency Control** | Optimistic concurrency via row version, paired with buyer-scoped distributed locks and idempotency keys |
| **PII / Data Classification** | Internal transactional record (`note` may contain customer-provided free text) |
## Attributes & Constraints
| Attribute | Business Rule / Constraint | Sensitivity / Notes |
| :----------- | :-------------------------------------------------------------------------------------------------------------- | :---------------------------- |
| `buyerId` | Links to [[entity\|buyer]]; becomes null if the buyer profile is hard-deleted so accepted orders remain intact. | Customer reference |
| `status` | Starts as `New`; transitions once to `Completed` or `Cancelled`. | Authoritative lifecycle state |
| `note` | Optional free-text customer note, max 500 characters. | May contain user-entered PII |
| `totalPrice` | Computed dynamically as the sum of `price * quantity` across `orderItems`; not stored separately. | Derived monetary total |
| `isDeleted` | Defaults to `false`; hides the order and its items from standard queries when `true`. | Independent of `status` |
## Domain Invariants & Lifecycle
- **Single terminal transition:** Every new order begins in `New`. Only `New` orders may transition to `Completed` or `Cancelled`; repeated identical transitions are idempotent, while cross-transitions (`Completed` ↔ `Cancelled`) are rejected.
- **Price snapshot isolation:** Line-item prices are locked from [[domain|catalog]] at checkout time so future catalog price changes never alter accepted orders.
- **Soft-delete vs. business status:** Soft-deleting an order (for example, during failed basket-cleanup compensation) hides it from standard queries without changing its `status`.
- **Saga separation:** Post-checkout orchestration progress in [[service|order-orchestration]] and email delivery in [[service|notification-api]] never directly mutate an order's business `status`.
:::warning
If post-checkout basket cleanup fails after bounded retries, [[service|order-orchestration]] issues a compensation command so [[service|order-api]] soft-deletes the order and suppresses confirmation emails.
:::
### Order Status Lifecycle
## Relationships & Associated Operations
| Category | Resource | Role / Interaction |
| :--------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------ |
| **Related Entities** | [[entity\|buyer]], [[entity\|order-item]] | Placed by a buyer; owns one or more purchase-time order items |
| **Cross-Context References** | [[entity\|book]] | Referenced indirectly via [[entity\|order-item]] `bookId` |
| **Mutating Commands** | [[command\|CreateOrder]], [[command\|CompleteOrder]], [[command\|CancelOrder]], [[command\|DeleteOrder]], [[command\|DeleteBasketFailedCommand]] | Place, complete, cancel, or soft-delete/compensate an order |
| **Read Queries** | [[query\|GetOrder]], [[query\|ListOrders]] | Retrieve order details or filtered order history |
| **Emitted Events** | [[event\|UserCheckedOutIntegrationEvent]], [[event\|OrderStatusChangedToCompleteIntegrationEvent]], [[event\|OrderStatusChangedToCancelIntegrationEvent]] | Trigger post-checkout saga and lifecycle email notifications |
---
id: order-item
name: Order Item
version: 1.0.0
identifier: id
aggregateRoot: false
summary: Child entity within an Order capturing a purchased book identifier, positive quantity, and locked checkout-time unit price.
owners:
- commerce-fulfillment-team
badges:
- content: Child Entity
backgroundColor: teal
textColor: teal
properties:
- name: id
type: UUID
required: true
description: Globally unique UUIDv7 identifier for the order line item.
- name: orderId
type: UUID
required: true
description: Identifier of the parent Order aggregate.
references: order
referencesIdentifier: id
relationType: belongsTo
- name: bookId
type: UUID
required: true
description: Cross-context identifier of the Catalog Book purchased on this line.
references: book
referencesIdentifier: id
relationType: references
- name: quantity
type: integer
required: true
description: Positive number of copies purchased (must be greater than zero).
- name: price
type: decimal
required: true
description: Non-negative per-unit price locked at checkout time.
---
## Domain Role & Boundary
**Order Item** is a child Entity owned by the [[entity|order]] Aggregate Root in the [[domain|ordering]] bounded context. Persisted by [[service|order-api]], it records a single purchased title, its quantity, and its immutable checkout-time unit price. It explicitly does **not** own live book titles, descriptions, or promotional pricing (owned by [[domain|catalog]] and referenced strictly by `bookId`).
## Entity Profile
| Property | Value |
| :---------------------------- | :------------------------------------------------------------------------------------------------------ |
| **Bounded Context / Domain** | [[domain\|ordering]] |
| **Owning Service** | [[service\|order-api]] |
| **DDD Role** | Child Entity (owned by [[entity\|order]]) |
| **Identifier Strategy** | UUIDv7 generated at persistence |
| **Persistence Store** | Ordering relational database (`order_items`) |
| **Deletion Semantics** | Cascade-deleted if parent is purged; hidden automatically when parent [[entity\|order]] is soft-deleted |
| **Concurrency Control** | Governed by parent [[entity\|order]] aggregate concurrency token |
| **PII / Data Classification** | Internal transactional record (non-PII) |
## Attributes & Constraints
| Attribute | Business Rule / Constraint | Sensitivity / Notes |
| :--------- | :----------------------------------------------------------------------------------------- | :------------------------- |
| `orderId` | Required foreign key to parent [[entity\|order]]. | Aggregate containment |
| `bookId` | Required; unique per `(bookId, orderId)` so each book appears at most once per order. | Cross-context ID reference |
| `quantity` | Required; must be strictly greater than zero (`> 0`). | Domain invariant |
| `price` | Required; must be non-negative (`>= 0`), snapshotted from [[domain\|catalog]] at checkout. | Immutable after creation |
## Domain Invariants & Lifecycle
- **Positive quantity:** Zero or negative item quantities are rejected at creation.
- **Non-negative price snapshot:** Unit prices must be zero or greater and remain immutable even when [[entity|book]] prices later change in [[domain|catalog]].
- **One line per book:** An [[entity|order]] cannot contain duplicate line items for the same `bookId`.
- **Parent visibility coupling:** Order items have no independent lifecycle; soft-deleting the parent [[entity|order]] excludes all of its items from standard queries.
:::note
Order Item calculates its line subtotal (`price * quantity`), which the parent [[entity|order]] sums to derive `totalPrice`.
:::
## Relationships & Associated Operations
| Category | Resource | Role / Interaction |
| :--------------------------- | :------------------------------------------------- | :-------------------------------------------------------------------- |
| **Parent Aggregate** | [[entity\|order]] | Owned child collection (`orderItems`) |
| **Cross-Context References** | [[entity\|book]] | Referenced strictly by `bookId` (no database foreign key) |
| **Mutating Commands** | [[command\|CreateOrder]], [[command\|DeleteOrder]] | Created atomically with the parent order; hidden on order soft-delete |
| **Read Queries** | [[query\|GetOrder]], [[query\|ListOrders]] | Included as part of parent order projections |
---
id: publisher
name: Publisher
version: 1.0.0
identifier: id
aggregateRoot: true
summary: Represents a publishing house or imprint associated with books in the product catalog.
owners:
- catalog-experience-team
badges:
- content: Aggregate Root
backgroundColor: blue
textColor: blue
properties:
- name: id
type: UUID
required: true
description: Globally unique UUIDv7 identifier for the publisher.
- name: name
type: string
required: true
description: Unique publisher display name (non-whitespace, up to 100 characters).
---
## Domain Role & Boundary
**Publisher** is an Aggregate Root in the [[domain|catalog]] bounded context representing the publishing house or imprint that issues a book. Owned by [[service|catalog-api]], it maintains canonical publisher names for catalog filtering and attribution. It explicitly does **not** own book inventory, author contracts, or royalty/order accounting.
## Entity Profile
| Property | Value |
| :---------------------------- | :----------------------------------------------------------------------------- |
| **Bounded Context / Domain** | [[domain\|catalog]] |
| **Owning Service** | [[service\|catalog-api]] |
| **DDD Role** | Aggregate Root |
| **Identifier Strategy** | UUIDv7 generated at persistence |
| **Persistence Store** | Catalog relational database (`publishers`) |
| **Deletion Semantics** | Hard-delete; clears `publisherId` to null on affected [[entity\|book]] records |
| **Concurrency Control** | Last-write-wins (unique name constraint enforced by store) |
| **PII / Data Classification** | Public catalog metadata (non-PII) |
## Attributes & Constraints
| Attribute | Business Rule / Constraint | Sensitivity / Notes |
| :-------- | :------------------------------------------------------------------------------- | :-------------------- |
| `id` | Immutable primary identifier generated as UUIDv7. | Public identifier |
| `name` | Required, non-whitespace, max 100 characters, globally unique across publishers. | Unique index enforced |
## Domain Invariants & Lifecycle
- **Name required:** Creating or renaming a publisher with a null, empty, or whitespace-only name is rejected.
- **Global uniqueness:** Duplicate publisher names are rejected by the persistence layer.
- **Non-cascading hard delete:** Removing a publisher permanently deletes the publisher record and sets `publisherId` to null on any linked [[entity|book]] without deleting the books themselves.
- **Lifecycle events:** Creation, renaming, and deletion raise internal domain events within [[service|catalog-api]].
:::note
Publishers have no audit timestamps or soft-delete state; if a publisher is removed by mistake, a new record must be created and re-linked to affected books.
:::
## Relationships & Associated Operations
| Category | Resource | Role / Interaction |
| :-------------------- | :--------------------------------------------------------------------------------------- | :-------------------------------------------------------------- |
| **Related Entities** | [[entity\|book]] | One publisher issues zero or more books via `books.publisherId` |
| **Mutating Commands** | [[command\|CreatePublisher]], [[command\|UpdatePublisher]], [[command\|DeletePublisher]] | Create, rename, or remove a publisher |
| **Read Queries** | [[query\|ListPublishers]] | Storefront and backoffice publisher listings |
---
id: bookworm.{env}.basket.dead-letter-queue
name: Basket Dead Letter Queue
version: 1.0.0
type: topic
summary: |
Kafka dead-letter topic owned by the platform team that captures Basket API
messages after retry exhaustion or deserialization failure.
owners:
- platform-engineering-team
badges:
- content: Kafka
backgroundColor: blue
textColor: blue
- content: Dead-Letter Queue
backgroundColor: red
textColor: red
address: bookworm.{env}.basket.dead-letter-queue
parameters:
env:
enum:
- development
- staging
- production
default: development
examples:
- development
- staging
- production
description: BookWorm deployment environment.
deliveryGuarantee: at-least-once
protocols:
- kafka
---
## Purpose & Scope
This dead-letter channel captures failed checkout cleanup commands that [[service|basket-api]] could not process. Messages arrive here either after bounded transient retries (such as Redis connectivity or timeout errors) are exhausted, or immediately when a record fails deserialization or schema validation as a poison message.
## DLQ Profile
| Property | Value |
| :-------------------------------- | :---------------------------------------------------------------------------------------------- |
| **Owning Service** | [[service\|basket-api]] |
| **Address Pattern** | `bookworm.{env}.basket.dead-letter-queue` |
| **Upstream Source Channels** | [[channel\|bookworm.{env}.finance.place-order]] |
| **Routing Triggers** | Exhausted transient retries (storage/network faults) or immediate poison/deserialization errors |
| **Retention / Inspection Window** | Governed by Kafka broker retention policy; inspect and triage before broker expiry |
| **Replay Safety** | Idempotent if basket is already deleted; verify order and basket state first |
## Triage & Replay Guardrails
:::warning
Before replaying any record from this DLQ:
1. Verify that the corresponding order still exists and check whether the checkout saga in [[service|order-orchestration]] has already completed or compensated.
2. Confirm that Redis basket storage is healthy and whether the target basket has already been removed.
3. Isolate permanent schema or deserialization errors rather than replaying poison records.
4. **Replay only to [[service|basket-api]]** — never replay to the shared [[channel|bookworm.{env}.finance.place-order]] topic, as [[service|notification-api]] also consumes it and would send duplicate order emails.
Follow the operational triage procedures in [[doc|operational/003-incident-response-and-runbooks]].
:::
- **Preserved metadata:** Records retain the original CloudEvents envelope, `orderId` Kafka
partition key, and failure diagnostic headers (error reason, timestamp, and attempt count). -
**Cross-consumer isolation:** [[service|notification-api]] failures on the same upstream topic
route separately to [[channel|bookworm.{env}.notification.dead-letter-queue]].
## Channel Details & Visualization
---
id: bookworm.{env}.basket.delete-complete
name: Basket Delete Complete
version: 1.0.0
type: topic
summary: |
Kafka topic owned by the contributor team carrying Basket API's successful
checkout cleanup confirmation for Finance order orchestration.
owners:
- commerce-fulfillment-team
badges:
- content: Kafka
backgroundColor: blue
textColor: blue
- content: Topic
backgroundColor: teal
textColor: teal
address: bookworm.{env}.basket.delete-complete
parameters:
env:
enum:
- development
- staging
- production
default: development
examples:
- development
- staging
- production
description: BookWorm deployment environment.
deliveryGuarantee: at-least-once
protocols:
- kafka
---
## Purpose & Scope
This topic transports successful basket-cleanup confirmations published by [[service|basket-api]] within the Shopping bounded context after a submitted basket is removed. [[service|order-orchestration]] consumes these events to advance the post-checkout saga; confirmation here indicates basket cleanup only, not final order completion.
## Channel Specification
| Property | Value |
| :------------------------------------- | :------------------------------------------------------------------------ |
| **Bounded Context / Owner** | [[domain\|shopping]] / [[team\|commerce-fulfillment-team]] |
| **Channel Type** | Topic |
| **Address Pattern** | `bookworm.{env}.basket.delete-complete` |
| **Parameters** | `env` (`development`, `staging`, `production`; default: `development`) |
| **Protocol & Envelope Format** | Kafka + CloudEvents JSON (`application/json`) |
| **Partition Key & Ordering Guarantee** | Keyed by `orderId`; preserves per-order event ordering within a partition |
| **Delivery Semantics** | At-least-once |
| **Dead-Letter Channel** | None (direct worker consumption by [[service\|order-orchestration]]) |
## Messages & Participants
| Message | Type | Producer | Consumer(s) | Consumer Group |
| :----------------------------------------------- | :---- | :---------------------- | :------------------------------- | :--------------------------- |
| [[event\|BasketDeletedCompleteIntegrationEvent]] | Event | [[service\|basket-api]] | [[service\|order-orchestration]] | Finance orchestration worker |
## Ordering, Retries & Failure Handling
- **Partition-key ordering:** Records are partitioned by `orderId` so cleanup confirmations for a given order are processed sequentially.
- **Transient retries:** [[service|order-orchestration]] applies bounded retry/backoff on transient storage or orchestration host faults.
- **Poison & failure posture:** Because Finance consumes this topic directly via orchestration workers, there is no dedicated service DLQ; persistent consumer failures surface in worker diagnostics and orchestration state.
- **Consumer idempotency:** Repeated checkout cleanup requests may emit duplicate confirmations; [[service|order-orchestration]] ignores duplicates once the saga has recorded the outcome.
## Channel Details & Visualization
## Related Documentation
- [[service|basket-api]] — Basket cleanup producer
- [[service|order-orchestration]] — Finance saga consumer
- [[channel|bookworm.{env}.basket.delete-failed]] — Paired cleanup failure topic
- [[channel|bookworm.{env}.finance.delete-basket-complete]] — Downstream command issued to Ordering
- [[flow|user-checkout]] — End-to-end checkout workflow
- [[doc|arc42/08-crosscutting-concepts/002-contracts-and-messaging]] — Messaging standards and idempotency rules
---
id: bookworm.{env}.basket.delete-failed
name: Basket Delete Failed
version: 1.0.0
type: topic
summary: |
Kafka topic owned by the contributor team carrying Basket API's explicit
checkout cleanup failure outcome for Finance compensation.
owners:
- commerce-fulfillment-team
badges:
- content: Kafka
backgroundColor: blue
textColor: blue
- content: Topic
backgroundColor: teal
textColor: teal
address: bookworm.{env}.basket.delete-failed
parameters:
env:
enum:
- development
- staging
- production
default: development
examples:
- development
- staging
- production
description: BookWorm deployment environment.
deliveryGuarantee: at-least-once
protocols:
- kafka
---
## Purpose & Scope
This topic transports explicit business failure outcomes published by [[service|basket-api]] within the Shopping bounded context when a submitted basket cannot be deleted during checkout. [[service|order-orchestration]] consumes this signal to trigger compensating order soft-deletion without sending a customer email. Transient infrastructure exceptions during basket storage access are not published here; those route to [[channel|bookworm.{env}.basket.dead-letter-queue]].
## Channel Specification
| Property | Value |
| :------------------------------------- | :------------------------------------------------------------------------ |
| **Bounded Context / Owner** | [[domain\|shopping]] / [[team\|commerce-fulfillment-team]] |
| **Channel Type** | Topic |
| **Address Pattern** | `bookworm.{env}.basket.delete-failed` |
| **Parameters** | `env` (`development`, `staging`, `production`; default: `development`) |
| **Protocol & Envelope Format** | Kafka + CloudEvents JSON (`application/json`) |
| **Partition Key & Ordering Guarantee** | Keyed by `orderId`; preserves per-order event ordering within a partition |
| **Delivery Semantics** | At-least-once |
| **Dead-Letter Channel** | None (direct worker consumption by [[service\|order-orchestration]]) |
## Messages & Participants
| Message | Type | Producer | Consumer(s) | Consumer Group |
| :--------------------------------------------- | :---- | :---------------------- | :------------------------------- | :--------------------------- |
| [[event\|BasketDeletedFailedIntegrationEvent]] | Event | [[service\|basket-api]] | [[service\|order-orchestration]] | Finance orchestration worker |
## Ordering, Retries & Failure Handling
- **Partition-key ordering:** Records are partitioned by `orderId` so failure outcomes stay ordered with other lifecycle events for the same order.
- **Transient retries:** [[service|order-orchestration]] applies bounded retry/backoff on transient orchestration host or state faults.
- **Poison & failure posture:** Direct worker consumption has no dedicated service DLQ; inspect worker logs and order saga state before replaying, as replay can trigger order soft-deletion.
- **Consumer idempotency:** [[service|order-orchestration]] deduplicates repeated failure outcomes so the compensating transition is not applied twice.
## Channel Details & Visualization
## Related Documentation
- [[service|basket-api]] — Basket cleanup producer
- [[service|order-orchestration]] — Finance saga consumer
- [[channel|bookworm.{env}.basket.delete-complete]] — Paired cleanup success topic
- [[channel|bookworm.{env}.finance.delete-basket-failed]] — Downstream compensation command topic
- [[flow|user-checkout]] — End-to-end checkout workflow
- [[doc|arc42/08-crosscutting-concepts/002-contracts-and-messaging]] — Messaging standards and idempotency rules
---
id: bookworm.{env}.catalog.book-update-rating-failed
name: Book Rating Update Failed Channel
version: 1.0.0
type: topic
summary: |
Kafka compensation topic owned by the contributor team used by Catalog API
when a feedback-created event references a missing book.
owners:
- catalog-experience-team
badges:
- content: Kafka
backgroundColor: blue
textColor: blue
- content: Compensation
backgroundColor: orange
textColor: orange
address: bookworm.{env}.catalog.book-update-rating-failed
parameters:
env:
enum:
- development
- staging
- production
default: development
examples:
- development
- staging
- production
description: BookWorm deployment environment.
deliveryGuarantee: at-least-once
protocols:
- kafka
deadLetterChannel:
id: bookworm.{env}.rating.dead-letter-queue
version: 1.0.0
---
## Purpose & Scope
This compensation topic carries failure signals published by [[service|catalog-api]] within the Catalog bounded context when a newly submitted feedback event references a book that does not exist. [[service|rating-api]] consumes this event to remove the orphaned feedback record and keep rating data consistent. Feedback deletions for unknown books are ignored and do not emit this signal.
## Channel Specification
| Property | Value |
| :------------------------------------- | :------------------------------------------------------------------------ |
| **Bounded Context / Owner** | [[domain\|catalog]] / [[team\|catalog-experience-team]] |
| **Channel Type** | Topic |
| **Address Pattern** | `bookworm.{env}.catalog.book-update-rating-failed` |
| **Parameters** | `env` (`development`, `staging`, `production`; default: `development`) |
| **Protocol & Envelope Format** | Kafka + CloudEvents JSON (`application/json`) |
| **Partition Key & Ordering Guarantee** | Keyed by `feedbackId`; preserves per-feedback ordering within a partition |
| **Delivery Semantics** | At-least-once |
| **Dead-Letter Channel** | [[channel\|bookworm.{env}.rating.dead-letter-queue]] |
## Messages & Participants
| Message | Type | Producer | Consumer(s) | Consumer Group |
| :------------------------------------------------- | :---- | :----------------------- | :---------------------- | :---------------------- |
| [[event\|BookUpdatedRatingFailedIntegrationEvent]] | Event | [[service\|catalog-api]] | [[service\|rating-api]] | Rating service consumer |
## Ordering, Retries & Failure Handling
- **Partition-key ordering:** Records are partitioned by `feedbackId` so compensation actions for the same feedback item are serialized.
- **Transient retries:** [[service|rating-api]] performs bounded retries with backoff for transient database or network errors.
- **Immediate DLQ routing:** Poison payloads, deserialization errors, or exhausted retries route to [[channel|bookworm.{env}.rating.dead-letter-queue]].
- **Consumer idempotency:** Removing an already-deleted feedback record is a safe no-op.
## Channel Details & Visualization
## Related Documentation
- [[channel|bookworm.{env}.rating.dead-letter-queue]] — Consumer dead-letter queue
- [[channel|bookworm.{env}.rating.feedback-create]] — Upstream feedback creation topic
- [[service|catalog-api]] — Compensation producer
- [[service|rating-api]] — Compensation consumer
- [[flow|feedback-publication]] — Feedback publication and compensation flow
- [[doc|arc42/08-crosscutting-concepts/002-contracts-and-messaging]] — Messaging standards and idempotency rules
---
id: bookworm.{env}.catalog.dead-letter-queue
name: Catalog Dead Letter Queue
version: 1.0.0
type: topic
summary: |
Kafka dead-letter topic owned by the platform team that captures Rating
feedback events that Catalog API could not process.
owners:
- platform-engineering-team
badges:
- content: Kafka
backgroundColor: blue
textColor: blue
- content: Dead-Letter Queue
backgroundColor: red
textColor: red
address: bookworm.{env}.catalog.dead-letter-queue
parameters:
env:
enum:
- development
- staging
- production
default: development
examples:
- development
- staging
- production
description: BookWorm deployment environment.
deliveryGuarantee: at-least-once
protocols:
- kafka
---
## Purpose & Scope
This dead-letter channel captures customer feedback integration events that [[service|catalog-api]] could not apply to book rating summaries. Messages are routed here when transient database or lock failures exhaust retries, or immediately when a payload is malformed. Note that a missing-book business condition on feedback creation is handled via [[channel|bookworm.{env}.catalog.book-update-rating-failed]] rather than dead-lettering.
## DLQ Profile
| Property | Value |
| :-------------------------------- | :------------------------------------------------------------------------------------------------------------------------- |
| **Owning Service** | [[service\|catalog-api]] |
| **Address Pattern** | `bookworm.{env}.catalog.dead-letter-queue` |
| **Upstream Source Channels** | [[channel\|bookworm.{env}.rating.feedback-create]], [[channel\|bookworm.{env}.rating.feedback-delete]] |
| **Routing Triggers** | Exhausted transient retries (database/concurrency faults) or immediate poison/deserialization errors |
| **Retention / Inspection Window** | Governed by Kafka broker retention policy; inspect and triage before broker expiry |
| **Replay Safety** | Requires manual validation of current book rating summary and feedback state |
## Triage & Replay Guardrails
:::warning
Before replaying any record from this DLQ:
1. Verify [[service|catalog-api]] and [[service|rating-api]] health and confirm the underlying database or schema issue is resolved.
2. Check whether the feedback record still exists in Rating and whether the book's rating summary in Catalog already reflects the event.
3. Do not manually edit a book's rating summary as a substitute for replaying the authoritative event; isolate poison payloads before replaying valid records.
Follow the operational triage procedures in [[doc|operational/003-incident-response-and-runbooks]].
:::
- **Preserved metadata:** Records retain the original CloudEvents envelope, `bookId` Kafka
partition key, and failure diagnostic context. - **Business compensation vs. DLQ:** When a newly
rated book does not exist in Catalog, [[service|catalog-api]] emits
[[event|BookUpdatedRatingFailedIntegrationEvent]] to
[[channel|bookworm.{env}.catalog.book-update-rating-failed]] instead of sending the
event here.
## Channel Details & Visualization
---
id: bookworm.{env}.finance.cancel-order
name: Order Cancellation Command Channel
version: 1.0.0
type: topic
summary: |
Kafka topic owned by the contributor team carrying Finance order-cancellation
commands consumed by Notification API to send cancellation emails.
owners:
- commerce-fulfillment-team
badges:
- content: Kafka
backgroundColor: blue
textColor: blue
- content: Topic
backgroundColor: teal
textColor: teal
address: bookworm.{env}.finance.cancel-order
parameters:
env:
enum:
- development
- staging
- production
default: development
examples:
- development
- staging
- production
description: BookWorm deployment environment.
deliveryGuarantee: at-least-once
protocols:
- kafka
deadLetterChannel:
id: bookworm.{env}.notification.dead-letter-queue
version: 1.0.0
---
## Purpose & Scope
This topic transports order-cancellation notification commands published by [[service|order-orchestration]] after an order transitions to cancelled. [[service|notification-api]] consumes these commands to submit a cancellation email when valid customer contact details are present. No delivery confirmation is sent back to Finance.
## Channel Specification
| Property | Value |
| :------------------------------------- | :-------------------------------------------------------------------------- |
| **Bounded Context / Owner** | [[domain\|ordering]] / [[team\|commerce-fulfillment-team]] |
| **Channel Type** | Topic |
| **Address Pattern** | `bookworm.{env}.finance.cancel-order` |
| **Parameters** | `env` (`development`, `staging`, `production`; default: `development`) |
| **Protocol & Envelope Format** | Kafka + CloudEvents JSON (`application/json`) |
| **Partition Key & Ordering Guarantee** | Keyed by `orderId`; preserves per-order command ordering within a partition |
| **Delivery Semantics** | At-least-once |
| **Dead-Letter Channel** | [[channel\|bookworm.{env}.notification.dead-letter-queue]] |
## Messages & Participants
| Message | Type | Producer | Consumer(s) | Consumer Group |
| :------------------------------ | :------ | :------------------------------- | :---------------------------- | :---------------------------- |
| [[command\|CancelOrderCommand]] | Command | [[service\|order-orchestration]] | [[service\|notification-api]] | Notification service consumer |
## Ordering, Retries & Failure Handling
- **Partition-key ordering:** Keying by `orderId` preserves ordering for lifecycle notification commands targeting the same order.
- **Transient retries:** [[service|notification-api]] applies bounded SMTP client retries and Kafka listener cooldowns on transient mail-provider failures.
- **Immediate DLQ routing:** Malformed payloads, rendering errors, or exhausted retries route to [[channel|bookworm.{env}.notification.dead-letter-queue]].
- **Consumer idempotency:** [[service|notification-api]] deduplicates by message ID for 24 hours; blank email addresses are skipped safely, and operators must check [[service|sendgrid-api]] activity before replaying.
## Channel Details & Visualization
## Related Documentation
- [[channel|bookworm.{env}.notification.dead-letter-queue]] — Consumer dead-letter queue
- [[channel|bookworm.{env}.ordering.order-status-change-to-cancel]] — Upstream order cancellation event topic
- [[channel|bookworm.{env}.finance.complete-order]] — Paired order completion command topic
- [[service|order-orchestration]] — Command producer
- [[service|notification-api]] — Email consumer
- [[flow|notification-delivery]] — Notification delivery workflow
- [[flow|order-lifecycle]] — End-to-end order lifecycle flow
- [[doc|arc42/08-crosscutting-concepts/002-contracts-and-messaging]] — Messaging standards and idempotency rules
---
id: bookworm.{env}.finance.complete-order
name: Order Completion Command Channel
version: 1.0.0
type: topic
summary: |
Kafka topic owned by the contributor team carrying Finance order-completion
commands consumed by Notification API to send completion emails.
owners:
- commerce-fulfillment-team
badges:
- content: Kafka
backgroundColor: blue
textColor: blue
- content: Topic
backgroundColor: teal
textColor: teal
address: bookworm.{env}.finance.complete-order
parameters:
env:
enum:
- development
- staging
- production
default: development
examples:
- development
- staging
- production
description: BookWorm deployment environment.
deliveryGuarantee: at-least-once
protocols:
- kafka
deadLetterChannel:
id: bookworm.{env}.notification.dead-letter-queue
version: 1.0.0
---
## Purpose & Scope
This topic transports order-completion notification commands published by [[service|order-orchestration]] after [[service|order-api]] reports that an order has completed. [[service|notification-api]] consumes these commands to render and submit a completion email when usable customer contact details are present. No delivery confirmation is returned to Finance, and this channel never mutates order state.
## Channel Specification
| Property | Value |
| :------------------------------------- | :-------------------------------------------------------------------------- |
| **Bounded Context / Owner** | [[domain\|ordering]] / [[team\|commerce-fulfillment-team]] |
| **Channel Type** | Topic |
| **Address Pattern** | `bookworm.{env}.finance.complete-order` |
| **Parameters** | `env` (`development`, `staging`, `production`; default: `development`) |
| **Protocol & Envelope Format** | Kafka + CloudEvents JSON (`application/json`) |
| **Partition Key & Ordering Guarantee** | Keyed by `orderId`; preserves per-order command ordering within a partition |
| **Delivery Semantics** | At-least-once |
| **Dead-Letter Channel** | [[channel\|bookworm.{env}.notification.dead-letter-queue]] |
## Messages & Participants
| Message | Type | Producer | Consumer(s) | Consumer Group |
| :-------------------------------- | :------ | :------------------------------- | :---------------------------- | :---------------------------- |
| [[command\|CompleteOrderCommand]] | Command | [[service\|order-orchestration]] | [[service\|notification-api]] | Notification service consumer |
## Ordering, Retries & Failure Handling
- **Partition-key ordering:** Keying by `orderId` preserves ordering for lifecycle notification commands targeting the same order.
- **Transient retries:** [[service|notification-api]] applies bounded SMTP client retries and Kafka listener cooldowns on transient mail-provider failures.
- **Immediate DLQ routing:** Malformed payloads, rendering errors, or exhausted retries route to [[channel|bookworm.{env}.notification.dead-letter-queue]].
- **Consumer idempotency:** [[service|notification-api]] deduplicates by message ID for 24 hours; blank email addresses are skipped safely without error, and operators must check [[service|sendgrid-api]] activity before replaying to prevent duplicate emails.
## Channel Details & Visualization
## Related Documentation
- [[channel|bookworm.{env}.notification.dead-letter-queue]] — Consumer dead-letter queue
- [[channel|bookworm.{env}.ordering.order-status-change-to-complete]] — Upstream order completion event topic
- [[channel|bookworm.{env}.finance.cancel-order]] — Paired order cancellation command topic
- [[service|order-orchestration]] — Command producer
- [[service|notification-api]] — Email consumer
- [[flow|notification-delivery]] — Notification delivery workflow
- [[flow|order-lifecycle]] — End-to-end order lifecycle flow
- [[doc|arc42/08-crosscutting-concepts/002-contracts-and-messaging]] — Messaging standards and idempotency rules
---
id: bookworm.{env}.finance.delete-basket-complete
name: Successful Basket Cleanup Command Channel
version: 1.0.0
type: topic
summary: |
Kafka topic owned by the commerce-fulfillment-team carrying Finance's successful
basket-cleanup command consumed by Order API for operational tracking.
owners:
- commerce-fulfillment-team
badges:
- content: Kafka
backgroundColor: blue
textColor: blue
- content: Topic
backgroundColor: teal
textColor: teal
address: bookworm.{env}.finance.delete-basket-complete
parameters:
env:
enum:
- development
- staging
- production
default: development
examples:
- development
- staging
- production
description: BookWorm deployment environment.
deliveryGuarantee: at-least-once
protocols:
- kafka
deadLetterChannel:
id: bookworm.{env}.ordering.dead-letter-queue
version: 1.0.0
---
## Purpose & Scope
This topic transports successful basket-cleanup commands published by [[service|order-orchestration]] after [[service|basket-api]] confirms checkout cleanup. [[service|order-api]] consumes this command to record the operational outcome without altering the order's business status. This channel is distinct from Basket's upstream event topic, [[channel|bookworm.{env}.basket.delete-complete]].
## Channel Specification
| Property | Value |
| :------------------------------------- | :-------------------------------------------------------------------------- |
| **Bounded Context / Owner** | [[domain\|ordering]] / [[team\|commerce-fulfillment-team]] |
| **Channel Type** | Topic |
| **Address Pattern** | `bookworm.{env}.finance.delete-basket-complete` |
| **Parameters** | `env` (`development`, `staging`, `production`; default: `development`) |
| **Protocol & Envelope Format** | Kafka + CloudEvents JSON (`application/json`) |
| **Partition Key & Ordering Guarantee** | Keyed by `orderId`; preserves per-order command ordering within a partition |
| **Delivery Semantics** | At-least-once |
| **Dead-Letter Channel** | [[channel\|bookworm.{env}.ordering.dead-letter-queue]] |
## Messages & Participants
| Message | Type | Producer | Consumer(s) | Consumer Group |
| :--------------------------------------- | :------ | :------------------------------- | :--------------------- | :------------------------ |
| [[command\|DeleteBasketCompleteCommand]] | Command | [[service\|order-orchestration]] | [[service\|order-api]] | Ordering service consumer |
## Ordering, Retries & Failure Handling
- **Partition-key ordering:** Keying by `orderId` keeps cleanup outcome commands serialized per order.
- **Transient retries:** [[service|order-api]] applies bounded retries with backoff on transient database or connectivity faults.
- **Immediate DLQ routing:** Deserialization errors, poison payloads, or exhausted retries route to [[channel|bookworm.{env}.ordering.dead-letter-queue]].
- **Consumer idempotency:** Because [[service|order-api]] records an operational outcome without mutating order business status, duplicate delivery or replay is safe.
## Channel Details & Visualization
## Related Documentation
- [[channel|bookworm.{env}.ordering.dead-letter-queue]] — Consumer dead-letter queue
- [[channel|bookworm.{env}.basket.delete-complete]] — Upstream Basket cleanup event topic
- [[channel|bookworm.{env}.finance.delete-basket-failed]] — Paired cleanup failure command topic
- [[service|order-orchestration]] — Command producer
- [[service|order-api]] — Outcome consumer
- [[flow|user-checkout]] — End-to-end checkout workflow
- [[doc|arc42/08-crosscutting-concepts/002-contracts-and-messaging]] — Messaging standards and idempotency rules
---
id: bookworm.{env}.finance.delete-basket-failed
name: Failed Basket Cleanup Command Channel
version: 1.0.0
type: topic
summary: |
Kafka topic owned by the commerce-fulfillment-team carrying Finance's failed
basket-cleanup compensation command consumed by Order API.
owners:
- commerce-fulfillment-team
badges:
- content: Kafka
backgroundColor: blue
textColor: blue
- content: Compensation
backgroundColor: orange
textColor: orange
address: bookworm.{env}.finance.delete-basket-failed
parameters:
env:
enum:
- development
- staging
- production
default: development
examples:
- development
- staging
- production
description: BookWorm deployment environment.
deliveryGuarantee: at-least-once
protocols:
- kafka
deadLetterChannel:
id: bookworm.{env}.ordering.dead-letter-queue
version: 1.0.0
---
## Purpose & Scope
This compensation topic transports failed basket-cleanup commands published by [[service|order-orchestration]] when [[service|basket-api]] reports a cleanup failure or the checkout saga must compensate for a timeout. [[service|order-api]] consumes this command to soft-delete the order record without changing its business status. This channel is distinct from Basket's upstream failure event topic, [[channel|bookworm.{env}.basket.delete-failed]].
## Channel Specification
| Property | Value |
| :------------------------------------- | :-------------------------------------------------------------------------- |
| **Bounded Context / Owner** | [[domain\|ordering]] / [[team\|commerce-fulfillment-team]] |
| **Channel Type** | Topic |
| **Address Pattern** | `bookworm.{env}.finance.delete-basket-failed` |
| **Parameters** | `env` (`development`, `staging`, `production`; default: `development`) |
| **Protocol & Envelope Format** | Kafka + CloudEvents JSON (`application/json`) |
| **Partition Key & Ordering Guarantee** | Keyed by `orderId`; preserves per-order command ordering within a partition |
| **Delivery Semantics** | At-least-once |
| **Dead-Letter Channel** | [[channel\|bookworm.{env}.ordering.dead-letter-queue]] |
## Messages & Participants
| Message | Type | Producer | Consumer(s) | Consumer Group |
| :------------------------------------- | :------ | :------------------------------- | :--------------------- | :------------------------ |
| [[command\|DeleteBasketFailedCommand]] | Command | [[service\|order-orchestration]] | [[service\|order-api]] | Ordering service consumer |
## Ordering, Retries & Failure Handling
- **Partition-key ordering:** Keying by `orderId` serializes compensation commands for a given order within its partition.
- **Transient retries:** [[service|order-api]] applies bounded retries with backoff for transient database or service faults.
- **Immediate DLQ routing:** Malformed payloads, deserialization errors, or exhausted retries route to [[channel|bookworm.{env}.ordering.dead-letter-queue]].
- **Consumer idempotency:** If the order record is already absent, processing is a safe no-op; operators must verify order state before replaying so an active order is not unintentionally soft-deleted.
## Channel Details & Visualization
## Related Documentation
- [[channel|bookworm.{env}.ordering.dead-letter-queue]] — Consumer dead-letter queue
- [[channel|bookworm.{env}.basket.delete-failed]] — Upstream Basket failure event topic
- [[channel|bookworm.{env}.finance.delete-basket-complete]] — Paired cleanup success command topic
- [[service|order-orchestration]] — Command producer
- [[service|order-api]] — Compensation consumer
- [[flow|user-checkout]] — End-to-end checkout workflow
- [[doc|arc42/08-crosscutting-concepts/002-contracts-and-messaging]] — Messaging standards and idempotency rules
---
id: bookworm.{env}.finance.place-order
name: Order Placement Command Channel
version: 1.0.0
type: topic
summary: |
Shared Kafka topic owned by the contributor team carrying Finance order
placement commands to Basket API for cleanup and Notification API for email.
owners:
- commerce-fulfillment-team
badges:
- content: Kafka
backgroundColor: blue
textColor: blue
- content: Shared Topic
backgroundColor: purple
textColor: purple
address: bookworm.{env}.finance.place-order
parameters:
env:
enum:
- development
- staging
- production
default: development
examples:
- development
- staging
- production
description: BookWorm deployment environment.
deliveryGuarantee: at-least-once
protocols:
- kafka
deadLetterChannel:
id: bookworm.{env}.notification.dead-letter-queue
version: 1.0.0
---
## Purpose & Scope
This shared command topic carries order-placement commands published by [[service|order-orchestration]] after checkout begins. Two independent consumers subscribe to it: [[service|basket-api]] removes the submitted basket and reports the outcome, while [[service|notification-api]] renders and submits a new-order confirmation email. Publication here does not confirm that basket cleanup or email delivery succeeded.
:::warning
**Shared Multi-Consumer Topic:** Never blindly replay messages to `bookworm.{env}.finance.place-order`. Replaying to this topic triggers _both_ [[service|basket-api]] and [[service|notification-api]] again. Use the consumer-specific dead-letter channel ([[channel|bookworm.{env}.basket.dead-letter-queue]] or [[channel|bookworm.{env}.notification.dead-letter-queue]]) when recovering a single consumer.
:::
## Channel Specification
| Property | Value |
| :------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context / Owner** | [[domain\|ordering]] / [[team\|commerce-fulfillment-team]] |
| **Channel Type** | Topic |
| **Address Pattern** | `bookworm.{env}.finance.place-order` |
| **Parameters** | `env` (`development`, `staging`, `production`; default: `development`) |
| **Protocol & Envelope Format** | Kafka + CloudEvents JSON (`application/json`) |
| **Partition Key & Ordering Guarantee** | Keyed by `orderId`; preserves per-order command ordering within a partition |
| **Delivery Semantics** | At-least-once |
| **Dead-Letter Channel** | [[channel\|bookworm.{env}.notification.dead-letter-queue]] (Notification) and [[channel\|bookworm.{env}.basket.dead-letter-queue]] (Basket) |
## Messages & Participants
| Message | Type | Producer | Consumer(s) | Consumer Group |
| :----------------------------- | :------ | :------------------------------- | :----------------------------------------------------- | :----------------------------------------------------- |
| [[command\|PlaceOrderCommand]] | Command | [[service\|order-orchestration]] | [[service\|basket-api]], [[service\|notification-api]] | Basket service consumer; Notification service consumer |
## Ordering, Retries & Failure Handling
- **Partition-key ordering:** Keying by `orderId` ensures commands for the same order stay serialized per partition across both consumer groups.
- **Transient retries:** Each consumer group manages its own bounded retry/backoff policy independently (Redis retries in Basket; SMTP retries and listener cooldowns in Notification).
- **Immediate DLQ routing:** Poison payloads, deserialization errors, or exhausted retries route independently to [[channel|bookworm.{env}.basket.dead-letter-queue]] or [[channel|bookworm.{env}.notification.dead-letter-queue]].
- **Consumer idempotency:** [[service|basket-api]] handles repeated cleanup idempotently; [[service|notification-api]] uses a 24-hour message-ID cache, though timeout reissues with a new message ID can send another email.
## Channel Details & Visualization
## Related Documentation
- [[channel|bookworm.{env}.basket.dead-letter-queue]] — Basket consumer dead-letter queue
- [[channel|bookworm.{env}.notification.dead-letter-queue]] — Notification consumer dead-letter queue
- [[channel|bookworm.{env}.ordering.user-checked-out]] — Upstream checkout trigger topic
- [[channel|bookworm.{env}.basket.delete-complete]] — Basket cleanup success topic
- [[channel|bookworm.{env}.basket.delete-failed]] — Basket cleanup failure topic
- [[service|order-orchestration]] — Command producer
- [[service|basket-api]] — Cleanup consumer
- [[service|notification-api]] — Email consumer
- [[flow|user-checkout]] — End-to-end checkout workflow
- [[flow|notification-delivery]] — Notification delivery workflow
- [[doc|arc42/08-crosscutting-concepts/002-contracts-and-messaging]] — Messaging standards and idempotency rules
---
id: bookworm.{env}.notification.dead-letter-queue
name: Notification Dead Letter Queue
version: 1.0.0
type: topic
summary: |
Kafka dead-letter topic owned by the platform team that captures order
notification commands that Notification API could not deliver.
owners:
- platform-engineering-team
badges:
- content: Kafka
backgroundColor: blue
textColor: blue
- content: Dead-Letter Queue
backgroundColor: red
textColor: red
address: bookworm.{env}.notification.dead-letter-queue
parameters:
env:
enum:
- development
- staging
- production
default: development
examples:
- development
- staging
- production
description: BookWorm deployment environment.
deliveryGuarantee: at-least-once
protocols:
- kafka
---
## Purpose & Scope
This dead-letter channel captures order lifecycle email commands that [[service|notification-api]] failed to process. Records land here after bounded SMTP/MailKit retries and listener cooldowns are exhausted, or immediately upon template/deserialization failures.
## DLQ Profile
| Property | Value |
| :-------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Owning Service** | [[service\|notification-api]] |
| **Address Pattern** | `bookworm.{env}.notification.dead-letter-queue` |
| **Upstream Source Channels** | [[channel\|bookworm.{env}.finance.place-order]], [[channel\|bookworm.{env}.finance.complete-order]], [[channel\|bookworm.{env}.finance.cancel-order]] |
| **Routing Triggers** | Exhausted SMTP/provider retries or immediate poison/deserialization/rendering errors |
| **Retention / Inspection Window** | Governed by Kafka broker retention policy; inspect and triage before broker expiry |
| **Replay Safety** | Requires manual validation — check mail provider logs to avoid duplicate customer emails |
## Triage & Replay Guardrails
:::warning
Before replaying any record from this DLQ:
1. Check [[service|sendgrid-api]] (mail provider) activity logs first — an SMTP timeout may have occurred _after_ the provider already accepted the email.
2. Verify that the 24-hour message-ID deduplication cache behavior is understood; replaying a newly issued command ID can send a duplicate email.
3. **Never replay [[command|PlaceOrderCommand]] to [[channel|bookworm.{env}.finance.place-order]]** to recover email alone, as [[service|basket-api]] also consumes that topic.
4. Keep customer names and email addresses out of incident notes; correlate using `orderId` and message IDs only.
Follow the operational triage procedures in [[doc|operational/003-incident-response-and-runbooks]].
:::
- **PII sensitivity:** Dead-lettered payloads contain customer contact fields (`fullName`,
`email`). Restrict DLQ inspection access to authorized operators. - **Preserved metadata:**
Records retain the `orderId` Kafka partition key and original CloudEvents metadata.
## Channel Details & Visualization
---
id: bookworm.{env}.ordering.dead-letter-queue
name: Ordering Dead Letter Queue
version: 1.0.0
type: topic
summary: |
Kafka dead-letter topic owned by the platform-engineering-team that captures
basket-cleanup outcome commands that Order API could not process.
owners:
- platform-engineering-team
badges:
- content: Kafka
backgroundColor: blue
textColor: blue
- content: Dead-Letter Queue
backgroundColor: red
textColor: red
address: bookworm.{env}.ordering.dead-letter-queue
parameters:
env:
enum:
- development
- staging
- production
default: development
examples:
- development
- staging
- production
description: BookWorm deployment environment.
deliveryGuarantee: at-least-once
protocols:
- kafka
---
## Purpose & Scope
This dead-letter channel captures Finance basket-cleanup outcome commands that [[service|order-api]] could not process. Messages arrive here when transient database or service faults exhaust retries, or immediately when a command fails deserialization or validation.
## DLQ Profile
| Property | Value |
| :-------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------- |
| **Owning Service** | [[service\|order-api]] |
| **Address Pattern** | `bookworm.{env}.ordering.dead-letter-queue` |
| **Upstream Source Channels** | [[channel\|bookworm.{env}.finance.delete-basket-complete]], [[channel\|bookworm.{env}.finance.delete-basket-failed]] |
| **Routing Triggers** | Exhausted transient retries (database/service faults) or immediate poison/deserialization errors |
| **Retention / Inspection Window** | Governed by Kafka broker retention policy; inspect and triage before broker expiry |
| **Replay Safety** | Idempotent for cleanup-complete; requires manual validation for cleanup-failed (soft-deletes order) |
## Triage & Replay Guardrails
:::warning
Before replaying any record from this DLQ:
1. Distinguish between [[command|DeleteBasketCompleteCommand]] (records operational outcome without changing order state) and [[command|DeleteBasketFailedCommand]] (soft-deletes the order record).
2. Inspect the current order state in [[service|order-api]] before replaying a failure command to ensure soft-deletion is still the intended compensation.
3. Confirm database connectivity and isolate any malformed poison records before replaying valid messages.
Follow the operational triage procedures in [[doc|operational/003-incident-response-and-runbooks]].
:::
- **Preserved metadata:** Records retain the `orderId` Kafka partition key, CloudEvents envelope,
and failure context. - **Missing order handling:** If an order has already been removed, replaying
a cleanup-failed command is a safe no-op.
## Channel Details & Visualization
---
id: bookworm.{env}.ordering.order-status-change-to-cancel
name: Order Cancellation Event Channel
version: 1.0.0
type: topic
summary: |
Kafka topic owned by the commerce-fulfillment-team carrying Order API events
when an order transitions from New to Cancelled.
owners:
- commerce-fulfillment-team
badges:
- content: Kafka
backgroundColor: blue
textColor: blue
- content: Topic
backgroundColor: teal
textColor: teal
address: bookworm.{env}.ordering.order-status-change-to-cancel
parameters:
env:
enum:
- development
- staging
- production
default: development
examples:
- development
- staging
- production
description: BookWorm deployment environment.
deliveryGuarantee: at-least-once
protocols:
- kafka
---
## Purpose & Scope
This topic transports order cancellation events published by [[service|order-api]] when an order transitions from `New` to `Cancelled`. [[service|order-orchestration]] consumes these events to update the checkout saga and dispatch a cancellation email command to [[channel|bookworm.{env}.finance.cancel-order]]. This is a business status event, not an order soft-delete notification or email delivery confirmation.
:::note
In current payloads, the `basketId` field carries the buyer identifier rather than an independent Basket service record identifier.
:::
## Channel Specification
| Property | Value |
| :------------------------------------- | :------------------------------------------------------------------------ |
| **Bounded Context / Owner** | [[domain\|ordering]] / [[team\|commerce-fulfillment-team]] |
| **Channel Type** | Topic |
| **Address Pattern** | `bookworm.{env}.ordering.order-status-change-to-cancel` |
| **Parameters** | `env` (`development`, `staging`, `production`; default: `development`) |
| **Protocol & Envelope Format** | Kafka + CloudEvents JSON (`application/json`) |
| **Partition Key & Ordering Guarantee** | Keyed by `orderId`; preserves per-order event ordering within a partition |
| **Delivery Semantics** | At-least-once |
| **Dead-Letter Channel** | None (direct worker consumption by [[service\|order-orchestration]]) |
## Messages & Participants
| Message | Type | Producer | Consumer(s) | Consumer Group |
| :---------------------------------------------------- | :---- | :--------------------- | :------------------------------- | :--------------------------- |
| [[event\|OrderStatusChangedToCancelIntegrationEvent]] | Event | [[service\|order-api]] | [[service\|order-orchestration]] | Finance orchestration worker |
## Ordering, Retries & Failure Handling
- **Partition-key ordering:** Keying by `orderId` ensures cancellation events are serialized per order within a partition.
- **Transient retries:** [[service|order-orchestration]] applies bounded retry/backoff on transient orchestration host or state faults.
- **Poison & failure posture:** Direct worker consumption has no dedicated service DLQ; inspect Finance worker logs and saga state before replaying or resetting offsets.
- **Consumer idempotency:** Terminal orchestration instances ignore duplicate or late cancellation events; protect customer contact details in diagnostic logs.
## Channel Details & Visualization
## Related Documentation
- [[channel|bookworm.{env}.finance.cancel-order]] — Downstream notification command topic
- [[channel|bookworm.{env}.ordering.user-checked-out]] — Upstream checkout event topic
- [[channel|bookworm.{env}.ordering.order-status-change-to-complete]] — Paired completion event topic
- [[service|order-api]] — Order status event producer
- [[service|order-orchestration]] — Finance saga consumer
- [[flow|order-lifecycle]] — End-to-end order lifecycle flow
- [[doc|arc42/08-crosscutting-concepts/002-contracts-and-messaging]] — Messaging standards and idempotency rules
---
id: bookworm.{env}.ordering.order-status-change-to-complete
name: Order Completion Event Channel
version: 1.0.0
type: topic
summary: |
Kafka topic owned by the commerce-fulfillment-team carrying Order API events
when an order transitions from New to Completed.
owners:
- commerce-fulfillment-team
badges:
- content: Kafka
backgroundColor: blue
textColor: blue
- content: Topic
backgroundColor: teal
textColor: teal
address: bookworm.{env}.ordering.order-status-change-to-complete
parameters:
env:
enum:
- development
- staging
- production
default: development
examples:
- development
- staging
- production
description: BookWorm deployment environment.
deliveryGuarantee: at-least-once
protocols:
- kafka
---
## Purpose & Scope
This topic transports order completion events published by [[service|order-api]] when an order transitions from `New` to `Completed`. [[service|order-orchestration]] consumes these events to advance the order saga and dispatch a completion email command to [[channel|bookworm.{env}.finance.complete-order]]. This event reports order status only and does not confirm email delivery.
:::note
In current payloads, the `basketId` field carries the buyer identifier rather than an independent Basket service record identifier.
:::
## Channel Specification
| Property | Value |
| :------------------------------------- | :------------------------------------------------------------------------ |
| **Bounded Context / Owner** | [[domain\|ordering]] / [[team\|commerce-fulfillment-team]] |
| **Channel Type** | Topic |
| **Address Pattern** | `bookworm.{env}.ordering.order-status-change-to-complete` |
| **Parameters** | `env` (`development`, `staging`, `production`; default: `development`) |
| **Protocol & Envelope Format** | Kafka + CloudEvents JSON (`application/json`) |
| **Partition Key & Ordering Guarantee** | Keyed by `orderId`; preserves per-order event ordering within a partition |
| **Delivery Semantics** | At-least-once |
| **Dead-Letter Channel** | None (direct worker consumption by [[service\|order-orchestration]]) |
## Messages & Participants
| Message | Type | Producer | Consumer(s) | Consumer Group |
| :------------------------------------------------------ | :---- | :--------------------- | :------------------------------- | :--------------------------- |
| [[event\|OrderStatusChangedToCompleteIntegrationEvent]] | Event | [[service\|order-api]] | [[service\|order-orchestration]] | Finance orchestration worker |
## Ordering, Retries & Failure Handling
- **Partition-key ordering:** Keying by `orderId` ensures completion events are serialized per order within a partition.
- **Transient retries:** [[service|order-orchestration]] applies bounded retry/backoff on transient orchestration host or state faults.
- **Poison & failure posture:** Direct worker consumption has no dedicated service DLQ; inspect Finance worker logs and saga state before replaying or resetting offsets.
- **Consumer idempotency:** Completed orchestration instances ignore late or duplicate completion events.
## Channel Details & Visualization
## Related Documentation
- [[channel|bookworm.{env}.finance.complete-order]] — Downstream notification command topic
- [[channel|bookworm.{env}.ordering.user-checked-out]] — Upstream checkout event topic
- [[channel|bookworm.{env}.ordering.order-status-change-to-cancel]] — Paired cancellation event topic
- [[service|order-api]] — Order status event producer
- [[service|order-orchestration]] — Finance saga consumer
- [[flow|order-lifecycle]] — End-to-end order lifecycle flow
- [[doc|arc42/08-crosscutting-concepts/002-contracts-and-messaging]] — Messaging standards and idempotency rules
---
id: bookworm.{env}.ordering.user-checked-out
name: User Checkout Event Channel
version: 1.0.0
type: topic
summary: |
Kafka topic owned by the commerce-fulfillment-team carrying Order API checkout
events that initiate Finance post-checkout saga coordination.
owners:
- commerce-fulfillment-team
badges:
- content: Kafka
backgroundColor: blue
textColor: blue
- content: Topic
backgroundColor: teal
textColor: teal
address: bookworm.{env}.ordering.user-checked-out
parameters:
env:
enum:
- development
- staging
- production
default: development
examples:
- development
- staging
- production
description: BookWorm deployment environment.
deliveryGuarantee: at-least-once
protocols:
- kafka
---
## Purpose & Scope
This topic transports checkout integration events published by [[service|order-api]] immediately after a new order is persisted. [[service|order-orchestration]] consumes these events to start the post-checkout saga, which coordinates basket cleanup and confirmation emails. The event confirms order persistence only—not basket deletion or email delivery.
:::note
In current payloads, the `basketId` field carries the buyer identifier rather than an independent Basket service record identifier.
:::
## Channel Specification
| Property | Value |
| :------------------------------------- | :------------------------------------------------------------------------ |
| **Bounded Context / Owner** | [[domain\|ordering]] / [[team\|commerce-fulfillment-team]] |
| **Channel Type** | Topic |
| **Address Pattern** | `bookworm.{env}.ordering.user-checked-out` |
| **Parameters** | `env` (`development`, `staging`, `production`; default: `development`) |
| **Protocol & Envelope Format** | Kafka + CloudEvents JSON (`application/json`) |
| **Partition Key & Ordering Guarantee** | Keyed by `orderId`; preserves per-order event ordering within a partition |
| **Delivery Semantics** | At-least-once |
| **Dead-Letter Channel** | None (direct worker consumption by [[service\|order-orchestration]]) |
## Messages & Participants
| Message | Type | Producer | Consumer(s) | Consumer Group |
| :---------------------------------------- | :---- | :--------------------- | :------------------------------- | :--------------------------- |
| [[event\|UserCheckedOutIntegrationEvent]] | Event | [[service\|order-api]] | [[service\|order-orchestration]] | Finance orchestration worker |
## Ordering, Retries & Failure Handling
- **Partition-key ordering:** Keying by `orderId` ensures checkout initiation precedes subsequent status change events for the same order on that partition.
- **Transient retries:** [[service|order-orchestration]] applies bounded retry/backoff on transient orchestration host or state faults.
- **Poison & failure posture:** Direct worker consumption has no dedicated service DLQ; inspect Finance worker diagnostics and orchestration state before resetting offsets or replaying.
- **Consumer idempotency:** [[service|order-orchestration]] keys saga instances by `orderId` and ignores duplicate checkout events once an orchestration instance exists.
## Channel Details & Visualization
## Related Documentation
- [[channel|bookworm.{env}.finance.place-order]] — Downstream command topic triggered by checkout
- [[channel|bookworm.{env}.ordering.order-status-change-to-complete]] — Order completion event topic
- [[channel|bookworm.{env}.ordering.order-status-change-to-cancel]] — Order cancellation event topic
- [[service|order-api]] — Checkout event producer
- [[service|order-orchestration]] — Finance saga consumer
- [[flow|user-checkout]] — End-to-end checkout workflow
- [[flow|order-lifecycle]] — End-to-end order lifecycle flow
- [[doc|arc42/08-crosscutting-concepts/002-contracts-and-messaging]] — Messaging standards and idempotency rules
---
id: bookworm.{env}.rating.dead-letter-queue
name: Rating Dead Letter Queue
version: 1.0.0
type: topic
summary: |
Kafka dead-letter topic owned by the platform team that captures Catalog
compensation events that Rating API could not process.
owners:
- platform-engineering-team
badges:
- content: Kafka
backgroundColor: blue
textColor: blue
- content: Dead-Letter Queue
backgroundColor: red
textColor: red
address: bookworm.{env}.rating.dead-letter-queue
parameters:
env:
enum:
- development
- staging
- production
default: development
examples:
- development
- staging
- production
description: BookWorm deployment environment.
deliveryGuarantee: at-least-once
protocols:
- kafka
---
## Purpose & Scope
This dead-letter channel captures Catalog compensation events that [[service|rating-api]] could not process when attempting to remove orphaned feedback. Messages land here after transient database retries are exhausted, or immediately if a compensation payload is malformed.
## DLQ Profile
| Property | Value |
| :-------------------------------- | :----------------------------------------------------------------------------------------------- |
| **Owning Service** | [[service\|rating-api]] |
| **Address Pattern** | `bookworm.{env}.rating.dead-letter-queue` |
| **Upstream Source Channels** | [[channel\|bookworm.{env}.catalog.book-update-rating-failed]] |
| **Routing Triggers** | Exhausted transient retries (database/network faults) or immediate poison/deserialization errors |
| **Retention / Inspection Window** | Governed by Kafka broker retention policy; inspect and triage before broker expiry |
| **Replay Safety** | Idempotent if feedback is already removed; verify book absence first |
## Triage & Replay Guardrails
:::warning
Before replaying any record from this DLQ:
1. Confirm that the referenced book is still absent from [[service|catalog-api]] before replaying compensation. If the book now exists, investigate the projection mismatch instead of deleting feedback.
2. Verify [[service|rating-api]] database health and check whether the feedback record has already been removed (already-deleted feedback is a safe no-op).
3. Isolate poison or schema-incompatible records rather than replaying them blindly.
Follow the operational triage procedures in [[doc|operational/003-incident-response-and-runbooks]].
:::
- **Preserved metadata:** Records retain the `feedbackId` Kafka partition key, CloudEvents
envelope, and failure diagnostics.
## Channel Details & Visualization
---
id: bookworm.{env}.rating.feedback-create
name: Feedback Created Channel
version: 1.0.0
type: topic
summary: |
Kafka topic owned by the contributor team carrying Rating API feedback-created
events consumed by Catalog API to update book rating summaries.
owners:
- catalog-experience-team
badges:
- content: Kafka
backgroundColor: blue
textColor: blue
- content: Topic
backgroundColor: teal
textColor: teal
address: bookworm.{env}.rating.feedback-create
parameters:
env:
enum:
- development
- staging
- production
default: development
examples:
- development
- staging
- production
description: BookWorm deployment environment.
deliveryGuarantee: at-least-once
protocols:
- kafka
deadLetterChannel:
id: bookworm.{env}.catalog.dead-letter-queue
version: 1.0.0
---
## Purpose & Scope
This topic transports customer feedback-created events published by [[service|rating-api]] within the Reviews bounded context. [[service|catalog-api]] consumes these events to project the new rating into the book's summary. If the referenced book does not exist in Catalog, [[service|catalog-api]] emits a compensation event to [[channel|bookworm.{env}.catalog.book-update-rating-failed]] rather than dead-lettering.
## Channel Specification
| Property | Value |
| :------------------------------------- | :------------------------------------------------------------------------------ |
| **Bounded Context / Owner** | [[domain\|reviews]] / [[team\|catalog-experience-team]] |
| **Channel Type** | Topic |
| **Address Pattern** | `bookworm.{env}.rating.feedback-create` |
| **Parameters** | `env` (`development`, `staging`, `production`; default: `development`) |
| **Protocol & Envelope Format** | Kafka + CloudEvents JSON (`application/json`) |
| **Partition Key & Ordering Guarantee** | Keyed by `bookId`; preserves per-book rating update ordering within a partition |
| **Delivery Semantics** | At-least-once |
| **Dead-Letter Channel** | [[channel\|bookworm.{env}.catalog.dead-letter-queue]] |
## Messages & Participants
| Message | Type | Producer | Consumer(s) | Consumer Group |
| :----------------------------------------- | :---- | :---------------------- | :----------------------- | :----------------------- |
| [[event\|FeedbackCreatedIntegrationEvent]] | Event | [[service\|rating-api]] | [[service\|catalog-api]] | Catalog service consumer |
## Ordering, Retries & Failure Handling
- **Partition-key ordering:** Keying by `bookId` ensures rating additions and deletions for the same book are ordered per partition relative to concurrent updates.
- **Transient retries:** [[service|catalog-api]] applies bounded retries with backoff on transient database or concurrency faults.
- **Immediate DLQ routing:** Deserialization errors, malformed payloads, or exhausted retries route to [[channel|bookworm.{env}.catalog.dead-letter-queue]] (missing-book business rejections route to [[channel|bookworm.{env}.catalog.book-update-rating-failed]] instead).
- **Consumer idempotency:** [[service|catalog-api]] guards against duplicate feedback projection; verify the current book rating summary before manual replay.
## Channel Details & Visualization
## Related Documentation
- [[channel|bookworm.{env}.catalog.dead-letter-queue]] — Consumer dead-letter queue
- [[channel|bookworm.{env}.rating.feedback-delete]] — Paired feedback deletion topic
- [[channel|bookworm.{env}.catalog.book-update-rating-failed]] — Missing-book compensation topic
- [[service|rating-api]] — Feedback producer
- [[service|catalog-api]] — Rating projection consumer
- [[flow|feedback-publication]] — End-to-end feedback publication flow
- [[doc|arc42/08-crosscutting-concepts/002-contracts-and-messaging]] — Messaging standards and idempotency rules
---
id: bookworm.{env}.rating.feedback-delete
name: Feedback Deleted Channel
version: 1.0.0
type: topic
summary: |
Kafka topic owned by the contributor team carrying Rating API feedback-deleted
events consumed by Catalog API to update book rating summaries.
owners:
- catalog-experience-team
badges:
- content: Kafka
backgroundColor: blue
textColor: blue
- content: Topic
backgroundColor: teal
textColor: teal
address: bookworm.{env}.rating.feedback-delete
parameters:
env:
enum:
- development
- staging
- production
default: development
examples:
- development
- staging
- production
description: BookWorm deployment environment.
deliveryGuarantee: at-least-once
protocols:
- kafka
deadLetterChannel:
id: bookworm.{env}.catalog.dead-letter-queue
version: 1.0.0
---
## Purpose & Scope
This topic transports feedback-deleted events published by [[service|rating-api]] within the Reviews bounded context when a customer removes feedback. [[service|catalog-api]] consumes these events to subtract the removed rating from the book's displayed summary. If the book no longer exists in Catalog, the event is treated as a safe no-op without compensation.
## Channel Specification
| Property | Value |
| :------------------------------------- | :------------------------------------------------------------------------------ |
| **Bounded Context / Owner** | [[domain\|reviews]] / [[team\|catalog-experience-team]] |
| **Channel Type** | Topic |
| **Address Pattern** | `bookworm.{env}.rating.feedback-delete` |
| **Parameters** | `env` (`development`, `staging`, `production`; default: `development`) |
| **Protocol & Envelope Format** | Kafka + CloudEvents JSON (`application/json`) |
| **Partition Key & Ordering Guarantee** | Keyed by `bookId`; preserves per-book rating update ordering within a partition |
| **Delivery Semantics** | At-least-once |
| **Dead-Letter Channel** | [[channel\|bookworm.{env}.catalog.dead-letter-queue]] |
## Messages & Participants
| Message | Type | Producer | Consumer(s) | Consumer Group |
| :----------------------------------------- | :---- | :---------------------- | :----------------------- | :----------------------- |
| [[event\|FeedbackDeletedIntegrationEvent]] | Event | [[service\|rating-api]] | [[service\|catalog-api]] | Catalog service consumer |
## Ordering, Retries & Failure Handling
- **Partition-key ordering:** Keying by `bookId` preserves per-book ordering alongside feedback creation events.
- **Transient retries:** [[service|catalog-api]] applies bounded retries with backoff for transient database or concurrency errors.
- **Immediate DLQ routing:** Malformed payloads, deserialization errors, or exhausted retries route to [[channel|bookworm.{env}.catalog.dead-letter-queue]].
- **Consumer idempotency:** Deletions for missing books or already-removed feedback entries are handled as safe no-ops.
## Channel Details & Visualization
## Related Documentation
- [[channel|bookworm.{env}.catalog.dead-letter-queue]] — Consumer dead-letter queue
- [[channel|bookworm.{env}.rating.feedback-create]] — Paired feedback creation topic
- [[service|rating-api]] — Feedback producer
- [[service|catalog-api]] — Rating projection consumer
- [[flow|feedback-publication]] — End-to-end feedback publication flow
- [[doc|arc42/08-crosscutting-concepts/002-contracts-and-messaging]] — Messaging standards and idempotency rules
---
id: scheduler.process-vector-batch
name: Process Vector Batch Channel
version: 1.0.0
type: topic
summary: |
Unprefixed Kafka trigger topic owned by the platform team used by Scheduler
Service every five minutes to initiate Catalog Ingestion vector indexing.
owners:
- ai-capabilities-team
badges:
- content: Kafka
backgroundColor: blue
textColor: blue
- content: Scheduled Trigger
backgroundColor: yellow
textColor: yellow
address: scheduler.process-vector-batch
deliveryGuarantee: at-least-once
protocols:
- kafka
---
## Purpose & Scope
This platform trigger topic carries periodic five-minute signals published by [[service|scheduler-service]] to instruct [[service|catalog-ingestion]] to synchronize pending book-search embeddings into the vector store. The payload contains only an event identifier and timestamp, with no book or customer data.
:::note
**Intentional Naming Exception:** This topic is unprefixed (`scheduler.process-vector-batch`) across all environments and omits the `{env}` parameter so static serverless Kafka triggers can bind to a constant topic name.
:::
## Channel Specification
| Property | Value |
| :------------------------------------- | :-------------------------------------------------------------------------------------- |
| **Bounded Context / Owner** | [[domain\|platform]] / [[team\|platform-engineering-team]] |
| **Channel Type** | Topic |
| **Address Pattern** | `scheduler.process-vector-batch` |
| **Parameters** | None (static topic name across all environments) |
| **Protocol & Envelope Format** | Kafka + CloudEvents JSON (`application/json`) |
| **Partition Key & Ordering Guarantee** | Unkeyed; no strict partition ordering required (work is coalesced in the catalog queue) |
| **Delivery Semantics** | At-least-once |
| **Dead-Letter Channel** | None (unacknowledged work remains queued for the next 5-minute trigger) |
## Messages & Participants
| Message | Type | Producer | Consumer(s) | Consumer Group |
| :-------------------------------------------- | :---- | :----------------------------- | :----------------------------- | :----------------------- |
| [[event\|ProcessVectorBatchIntegrationEvent]] | Event | [[service\|scheduler-service]] | [[service\|catalog-ingestion]] | Catalog ingestion worker |
## Ordering, Retries & Failure Handling
- **Single-writer exclusivity:** [[service|catalog-ingestion]] acquires an exclusive database advisory lock; overlapping triggers exit immediately without duplicate indexing.
- **Transient retries:** If embedding generation or vector store writes fail, unacknowledged rows remain in the pending catalog queue rather than being discarded.
- **No DLQ required:** Because the five-minute schedule re-triggers batch processing automatically, failed batches self-heal on the next cycle once dependencies recover.
- **Consumer idempotency:** Queue revision checks prevent stale embeddings from overwriting newer book edits made while a batch is in flight.
## Channel Details & Visualization
## Related Documentation
- [[service|scheduler-service]] — Periodic trigger producer
- [[service|catalog-ingestion]] — Vector indexing worker consumer
- [[flow|product-ingestion]] — End-to-end catalog vector ingestion flow
- [[doc|arc42/08-crosscutting-concepts/002-contracts-and-messaging]] — Messaging standards and idempotency rules
---
id: basket-database
name: Basket Database
version: 1.0.0
summary: Authoritative Redis key-value store owned by the Shopping bounded context for customer-scoped pre-checkout shopping baskets.
owners:
- commerce-fulfillment-team
container_type: database
badges:
- content: Database
backgroundColor: blue
textColor: blue
technology: redis
authoritative: true
access_mode: readWrite
classification: internal
retention: transient
residency: eastasia
purpose: Authoritative store for active customer-scoped shopping baskets prior to checkout.
styles:
icon: /icons/database/redis.svg
---
## Purpose & Ownership Boundary
Basket Database is the authoritative Redis key-value store owned exclusively by [[service|basket-api]] in the Shopping bounded context. Redis was chosen for low-latency, customer-scoped key-value persistence of ephemeral pre-checkout [[entity|basket]] state without requiring a relational SQL database, while delegating product metadata to [[service|catalog-api]] and accepted orders to [[service|order-api]].
## Data Store Profile
| Property | Value |
| :---------------------------------- | :---------------------------------------------------------------------------------- |
| **Bounded Context / Owner** | Shopping — [[team\|commerce-fulfillment-team]] |
| **Engine / Technology** | Redis (Azure Managed Redis in cloud; Redis container locally) |
| **Store Type** | Database (Key-Value) |
| **Primary Writer(s)** | [[service\|basket-api]] |
| **Primary Reader(s)** | [[service\|basket-api]] |
| **Authoritative / Source of Truth** | Yes (for active pre-checkout baskets) |
| **Data Classification** | Internal |
| **Retention / TTL Policy** | Transient (persisted until replaced, explicitly deleted, or cleared after checkout) |
## Logical Data Layout & Key Patterns
| Key Pattern | Stored Data | TTL / Eviction | Invalidation / Update Trigger |
| :--------------------------- | :----------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `basket:{userId}` | UTF-8 JSON [[entity\|basket]] containing customer `id` (`uuid`) and non-empty [[entity\|basket-item]] array (`id`, `quantity`) | No explicit TTL set; persists until mutated or deleted | Full-document atomic replacement (`SET`) on basket updates; deleted (`DEL`) by customer request or post-checkout [[command\|PlaceOrderCommand]] cleanup. |
| Integration idempotency keys | 24-hour Kafka message deduplication markers | `24 hours` | Automatic TTL expiration after consumer processing. |
Note: Neither the Aspire Redis configuration nor the generated Azure Redis templates declare an explicit eviction policy; verify any externally configured memory-pressure eviction policy before assuming indefinite idle retention.
## Consistency, Isolation & Security Guardrails
- **No duplicated catalog metadata:** Titles, descriptions, and prices are never stored in Redis; [[service|basket-api]] enriches items from [[service|catalog-api]] over gRPC at read time.
- **Full-set replacement & invariants:** Basket updates atomically overwrite the complete item list and enforce a non-empty basket invariant (empty baskets are deleted rather than stored).
- **Not a record of accepted orders:** Once checkout completes, [[service|order-api]] persists the immutable purchase in [[container|order-database]], and post-checkout cleanup publishes [[event|BasketDeletedCompleteIntegrationEvent]] or [[event|BasketDeletedFailedIntegrationEvent]].
:::warning
**Shared Redis Key-Prefix & Flush Isolation:** Basket Database shares the `redis` cluster with [[container|catalog-cache]], [[container|order-cache]], [[container|rating-cache]], and Notification idempotency markers. Because `basket:{userId}` is **authoritative** for active pre-checkout carts, flushing the shared Redis instance permanently drops all active customer baskets alongside cached responses and distributed locks. Only [[service|basket-api]] may read or write `basket:*` keys.
:::
## Operational & Resilience Notes
- **Local vs. Cloud:** Local development runs a persistent single-container Redis instance with
RedisInsight; cloud environments run Azure Managed Redis (`BalancedB0` in Dev, `BalancedB1` with
HA in Staging, `BalancedB5` with HA in Production). - **Failure impact:** If a post-checkout
delete fails, [[service|basket-api]] emits [[event|BasketDeletedFailedIntegrationEvent]] so
[[service|order-orchestration]] can trigger compensation.
## Architecture Visualizations
## Related Documentation
- [[service|basket-api]] — Owning service REST/gRPC endpoints, authorization, and Kafka handlers.
- [[container|order-database]] — Authoritative PostgreSQL store for confirmed purchases after checkout.
- [[container|order-cache]] — Sibling logical workload on the shared Redis resource.
- [[adr|adr-001-redis-authoritative-basket-store]] — Decision adopting Redis as the authoritative basket store.
- [[adr|adr-004-catalog-enrichment-at-read-time]] — Decision to enrich basket items at read time instead of caching prices.
- [[doc|operational/005-backup-restore-and-dr]] — Platform backup, restore, and disaster recovery runbook.
---
id: catalog-blob
name: Catalog Blob Storage
version: 1.0.0
summary: Authoritative Azure Blob Storage container owned by the Catalog bounded context for binary book cover images and media assets.
owners:
- catalog-experience-team
container_type: objectStore
badges:
- content: Object Storage
backgroundColor: teal
textColor: teal
technology: azure-storage-account
authoritative: true
access_mode: readWrite
purpose: System of record for Catalog binary media assets, including book cover images.
classification: internal
retention: 10y
residency: eastasia
styles:
icon: /icons/database/blob.svg
---
## Purpose & Ownership Boundary
Catalog Blob Storage (`catalog-blob`) is the authoritative object store owned exclusively by [[service|catalog-api]] in the Catalog bounded context for binary book cover images. Object storage keeps large binary payloads out of [[container|catalog-database]], which stores only permanent blob URNs (`books.image`) while [[service|catalog-api]] mints short-lived, read-only Shared Access Signature (SAS) URLs on demand.
## Data Store Profile
| Property | Value |
| :---------------------------------- | :---------------------------------------------------------------------------- |
| **Bounded Context / Owner** | Catalog — [[team\|catalog-experience-team]] |
| **Engine / Technology** | Azure Blob Storage (Azure Storage Account in cloud; Azurite emulator locally) |
| **Store Type** | Object Storage |
| **Primary Writer(s)** | [[service\|catalog-api]] |
| **Primary Reader(s)** | [[service\|catalog-api]] (SAS URL minting; clients fetch directly via SAS) |
| **Authoritative / Source of Truth** | Yes |
| **Data Classification** | Internal |
| **Retention / TTL Policy** | 10 years (explicit delete on book/image removal; no automatic lifecycle TTL) |
## Logical Data Layout & Key Patterns
| Container / Key Pattern | Stored Data | TTL / Eviction | Invalidation / Update Trigger |
| :---------------------------------------------- | :----------------------------------------------------------------- | :--------------------------------------------------------- | :---------------------------------------------------------------------------------------- |
| `catalog-blob` / `{uuidv7}-{safeName}{safeExt}` | Binary book cover images (`image/jpeg`, `image/png`, `image/webp`) | `10y` retention; `1 hour` default read-only SAS URL expiry | Explicit deletion (including snapshots) on image replacement or [[entity\|book]] removal. |
| URN reference (`books.image` in `catalogdb`) | `urn:{account}:catalog-blob:{blobName}` | Permanent until book/image is updated or deleted | Validated on every read/delete to match target storage account and container. |
## Consistency, Isolation & Security Guardrails
- **No public blob access:** Public container/blob access is disabled (`AllowBlobPublicAccess = false`); access requires Managed Identity RBAC (`StorageBlobDataContributor`) for [[service|catalog-api]] and HTTPS-only, read-only SAS URLs (User Delegation Keys in Azure, account-key SAS in local Azurite) for browser downloads.
- **Strict URN & overwrite protection:** Uploads enforce non-empty allowed image MIME types, sanitize filenames (`[a-zA-Z0-9._-]`, max 100 chars), and guard against accidental overwrites via `If-None-Match: *`. URN validation rejects path traversal (`/`, `\`, `..`) or cross-account mismatches.
- **No cross-store distributed transaction:** Because PostgreSQL and Blob Storage do not share a two-phase commit, a failed database transaction after upload can leave an unreferenced blob that requires periodic reconciliation against `books.image`.
:::warning
**Shared Storage Account Isolation:** `catalog-blob` shares the Azure Storage Account with [[container|chat-session-blob]] (`chatting-blob`) and Azure Functions host storage. Services must use container-scoped references—[[service|catalog-api]] must never access `chatting-blob`, and external services must never read `catalog-blob` directly or persist expiring SAS URLs.
:::
## Operational & Resilience Notes
- **Local vs. Cloud:** Local development uses a persistent Azurite emulator with Azure Storage
Explorer; cloud environments use Azure Storage Account with TLS 1.2 minimum (`StandardLrs` in
Dev, `StandardZrs` in Staging, `StandardGzrs` in Production). - **Expired SAS (`403`):**
Re-fetch the book from [[service|catalog-api]] to mint a fresh 1-hour SAS URL. -
**Cross-environment URN mismatch:** Never copy `books.image` URNs across environments without
migrating the corresponding blobs and updating the storage account segment.
## Architecture Visualizations
## Related Documentation
- [[service|catalog-api]] — Owning service managing image uploads, URN persistence, and SAS minting.
- [[container|catalog-database]] — Relational store holding `books.image` URNs.
- [[container|chat-session-blob]] — Sibling container on the shared Azure Storage Account.
- [[adr|adr-005-blob-storage-for-book-images]] — Decision separating binary cover media from PostgreSQL.
- [[doc|operational/005-backup-restore-and-dr]] — Platform backup, restore, and disaster recovery runbook.
---
id: catalog-cache
name: Catalog Cache
version: 1.0.0
summary: Non-authoritative FusionCache and Redis caching layer owned by the Catalog bounded context for fast book detail lookups and dashboard summaries.
owners:
- catalog-experience-team
container_type: cache
badges:
- content: Cache
backgroundColor: orange
textColor: orange
technology: azure-managed-redis
authoritative: false
access_mode: readWrite
classification: internal
retention: transient
residency: eastasia
purpose: Non-authoritative cache used by Catalog API for frequently requested book details and dashboard aggregates.
styles:
icon: /icons/database/redis.svg
---
## Purpose & Ownership Boundary
Catalog Cache is the non-authoritative, read-through caching tier owned by [[service|catalog-api]] in the Catalog bounded context in front of [[container|catalog-database]]. It pairs an in-process L1 memory tier with a shared Redis L2 distributed tier and backplane to accelerate repeated book detail lookups and dashboard aggregations across replicas.
## Data Store Profile
| Property | Value |
| :---------------------------------- | :---------------------------------------------------------------------------------- |
| **Bounded Context / Owner** | Catalog — [[team\|catalog-experience-team]] |
| **Engine / Technology** | Redis + FusionCache (Azure Managed Redis in cloud; Redis container locally) |
| **Store Type** | Cache |
| **Primary Writer(s)** | [[service\|catalog-api]] |
| **Primary Reader(s)** | [[service\|catalog-api]] |
| **Authoritative / Source of Truth** | Derived Read Model (Ephemeral) |
| **Data Classification** | Internal |
| **Retention / TTL Policy** | Transient (30-minute default TTL; 15-second dashboard TTL; 2-hour fail-safe window) |
## Logical Data Layout & Key Patterns
| Key Pattern | Stored Data | TTL / Eviction | Invalidation / Update Trigger |
| :--------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------ | :------------------------------------------------------------------------------------------- |
| `book:{id}` | Pre-DTO [[entity\|book]] projection (title, description, permanent blob URN, pricing, status, relations, rating summary, `row_version`) | `30 minutes` (`Caching:Expiration` default) | Event-driven eviction on book mutations, propagated across replicas via the Redis backplane. |
| `catalog:dashboard:v1` | Aggregated catalog dashboard counts and summary metrics | `15 seconds` | Time-based TTL expiration only (no event-driven eviction). |
| Feature-scoped list keys | Paginated catalog book list payloads | `30 minutes` (`Caching:Expiration` default) | TTL expiration or tag/key eviction on catalog updates. |
| Integration idempotency keys | 24-hour message deduplication markers | `24 hours` | Automatic TTL expiration after consumer processing. |
## Consistency, Isolation & Security Guardrails
- **Permanent URNs over SAS URLs:** Cached book entries store the permanent blob URN from [[container|catalog-database]] rather than expiring SAS URLs, ensuring every API read resolves a fresh read-only SAS token from [[container|catalog-blob]].
- **Fail-safe & stampede protection:** Distributed Redis locking coordinates cache-miss factories across replicas, and a 2-hour fail-safe window serves stale entries briefly if the backing database is momentarily degraded.
- **Dashboard staleness window:** Dashboard aggregates (`catalog:dashboard:v1`) can lag live writes by up to `15 seconds` due to TTL-only expiration.
:::warning
**Shared Redis Key-Prefix & Flush Isolation:** Catalog Cache shares the `redis` cluster with [[container|basket-database]], [[container|order-cache]], [[container|rating-cache]], and Notification idempotency markers. Never issue a global `FLUSHALL`/`FLUSHDB` on the shared instance—doing so simultaneously erases active customer baskets, distributed checkout locks, and 24-hour Kafka idempotency guards across five services. Always target `book:{id}` or `catalog:*` keys for manual invalidation.
:::
## Operational & Resilience Notes
- **Local vs. Cloud:** Local development runs a persistent single-container Redis instance with
RedisInsight; cloud environments run Azure Managed Redis (`BalancedB0` in Dev, `BalancedB1` with
HA in Staging, `BalancedB5` with HA in Production). - **Disposable state:** Every entry in
Catalog Cache is fully rebuildable from [[container|catalog-database]] on cache miss. -
**Observability:** Monitor FusionCache OpenTelemetry hit/miss metrics and Redis latency when
diagnosing elevated PostgreSQL read load.
## Architecture Visualizations
## Related Documentation
- [[service|catalog-api]] — Owning service read/write paths and cache eviction handlers.
- [[container|catalog-database]] — Authoritative PostgreSQL system of record behind this cache.
- [[container|catalog-blob]] — SAS URL resolution for cached book image URNs.
- [[adr|adr-004-fusioncache-redis-for-catalog-reads]] — Decision adopting two-tier FusionCache with Redis backplane.
- [[doc|operational/005-backup-restore-and-dr]] — Platform backup, restore, and disaster recovery runbook.
---
id: catalog-database
name: Catalog Database
version: 1.0.0
summary: Authoritative PostgreSQL system of record owned by the Catalog bounded context for books, authors, categories, publishers, and vector-indexing coordination.
owners:
- catalog-experience-team
container_type: database
badges:
- content: Database
backgroundColor: blue
textColor: blue
technology: azure-postgresql-flexible-server
authoritative: true
access_mode: readWrite
purpose: System of record for Catalog domain entities and durable coordination of asynchronous vector indexing.
classification: internal
retention: indefinite
residency: eastasia
styles:
icon: /icons/database/postgresql.svg
---
## Purpose & Ownership Boundary
Catalog Database (`catalogdb`) is the authoritative relational system of record for the Catalog bounded context, owned by [[service|catalog-api]]. PostgreSQL was chosen for strict relational integrity across product taxonomy, transactional outbox messaging, and trigger-driven change capture for asynchronous search indexing by [[service|catalog-ingestion]].
## Data Store Profile
| Property | Value |
| :---------------------------------- | :--------------------------------------------------------------------------------------------------- |
| **Bounded Context / Owner** | Catalog — [[team\|catalog-experience-team]] |
| **Engine / Technology** | PostgreSQL 18 (Azure Database for PostgreSQL Flexible Server) |
| **Store Type** | Database |
| **Primary Writer(s)** | [[service\|catalog-api]] (domain writes), [[service\|catalog-ingestion]] (queue acknowledgment only) |
| **Primary Reader(s)** | [[service\|catalog-api]], [[service\|catalog-ingestion]] |
| **Authoritative / Source of Truth** | Yes |
| **Data Classification** | Internal |
| **Retention / TTL Policy** | Indefinite (soft-delete flag on books; transactional outbox pruned after dispatch) |
## Logical Data Layout & Key Patterns
All identifiers use `snake_case`, primary keys default to time-ordered `uuidv7()`, and audit timestamps (`created_at`, `last_modified_at`) are database-generated.
| Table / Schema | Owned Entity | Partition / Primary Key | Purpose & Concurrency |
| :----------------------- | :----------------------------------- | :----------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `books` | [[entity\|book]] | `id` (`uuidv7()`) | Canonical book catalog, pricing, availability status, soft-delete flag (`is_deleted`), blob URN (`image`), and derived rating projection (`average_rating`, `total_reviews`); optimistic concurrency via `row_version`. |
| `authors` | [[entity\|author]] | `id` (`uuidv7()`) | Author directory; deletion restricted while referenced in `book_authors`. |
| `categories` | [[entity\|category]] | `id` (`uuidv7()`) | Product category taxonomy with unique `name`; deleting a category sets `books.category_id` to `NULL`. |
| `publishers` | [[entity\|publisher]] | `id` (`uuidv7()`) | Publisher directory with unique `name`; deleting a publisher sets `books.publisher_id` to `NULL`. |
| `book_authors` | [[entity\|book]], [[entity\|author]] | (`book_id`, `author_id`) | Many-to-many join table; deleting a book cascades to its author links. |
| `pending_vector_updates` | — | `book_id` (`uuid`) | Coalescing change-capture queue with `revision` UUID and `updated_at`; repeated edits update the row in place. |
| `wolverine` schema | — | Envelope ID | Transactional outbox and inbox tables sharing the domain write transaction; partitions Kafka events by `BookId` and `FeedbackId`. |
## Consistency, Isolation & Security Guardrails
- **Transactional outbox:** Domain writes and outbound integration events commit in a single PostgreSQL transaction via the `wolverine` outbox schema.
- **Trigger-driven search sync:** Five database triggers (`books`, `book_authors`, `authors`, `categories`, `publishers`) enqueue affected `book_id` rows into `pending_vector_updates`. [[service|catalog-ingestion]] acquires PostgreSQL advisory lock `740031001`, processes up to `200` rows per batch, and deletes only rows whose `book_id` and `revision` still match.
- **Soft-delete & URN invariants:** Books use `is_deleted` soft deletion rather than physical row removal. The `books.image` column stores permanent blob URNs pointing to [[container|catalog-blob]], never raw bytes or expiring SAS URLs.
- **Derived rating projections:** `average_rating` and `total_reviews` on `books` are eventually consistent projections updated from [[event|FeedbackCreatedIntegrationEvent]] and [[event|FeedbackDeletedIntegrationEvent]]; [[container|rating-database]] remains authoritative for individual reviews.
:::warning
**Database-per-Service Isolation:** Only [[service|catalog-api]] may mutate catalog domain tables, and [[service|catalog-ingestion]] is restricted to reading catalog state and acknowledging `pending_vector_updates`. External services (such as [[service|basket-api]], [[service|order-api]], or [[service|rating-api]]) must never connect to `catalogdb` directly—all cross-context reads flow through [[service|catalog-api]] HTTP/gRPC contracts or Kafka events.
:::
## Operational & Resilience Notes
- **Local vs. Cloud:** Local development runs a single persistent PostgreSQL container with
automatic dev seeding; cloud environments run Azure Database for PostgreSQL Flexible Server on
the shared `postgres` instance alongside `orderingdb` and `schedulerdb`. - **Scaling & HA:**
Development uses `Standard_B1ms` (single zone, 7-day backup, 32 GB); Staging uses
`Standard_D2ds_v5` (zone-redundant HA, PgBouncer, 14-day backup, 128 GB); Production uses
`Standard_D4ds_v5` (zone-redundant HA, PgBouncer, 35-day backup, 256 GB). - **Upgrades &
monitoring:** Apply schema changes exclusively through versioned migrations (never by replaying
static SQL snapshots), and monitor `pending_vector_updates` row count and oldest `updated_at` to
detect ingestion lag.
## Architecture Visualizations & Schema
## Related Documentation
- [[service|catalog-api]] — Owning service endpoints, gRPC contracts, and transactional outbox.
- [[service|catalog-ingestion]] — Worker draining `pending_vector_updates` into [[container|catalog-vector]].
- [[container|catalog-vector]] — Derived Qdrant hybrid search index fed from this database.
- [[container|catalog-blob]] — Binary cover media store referenced by `books.image` URNs.
- [[adr|adr-001-postgresql-system-of-record]] — Decision establishing PostgreSQL as Catalog's system of record.
- [[adr|adr-003-database-queue-for-vector-indexing]] — Decision for trigger-based vector update coalescing.
- [[doc|operational/005-backup-restore-and-dr]] — Platform backup, restore, and disaster recovery runbook.
---
id: catalog-vector
name: Catalog Vector
version: 1.0.0
summary: Non-authoritative Qdrant vector search index owned by the Catalog bounded context for hybrid semantic and keyword book discovery.
owners:
- catalog-experience-team
container_type: searchIndex
badges:
- content: Search Index
backgroundColor: purple
textColor: purple
technology: qdrant
authoritative: false
access_mode: readWrite
classification: internal
retention: transient
residency: eastasia
purpose: Store searchable text and vector embeddings of active Catalog books for semantic and keyword-based discovery.
styles:
icon: /icons/database/qdrant.svg
---
## Purpose & Ownership Boundary
Catalog Vector (`vectordb`) is the non-authoritative Qdrant search index owned by the Catalog bounded context for hybrid semantic and keyword book discovery. [[service|catalog-ingestion]] writes 1,536-dimensional embeddings asynchronously in batches, while [[service|catalog-api]] queries the index for candidate book IDs before hydrating authoritative prices, stock status, and ratings from [[container|catalog-database]].
## Data Store Profile
| Property | Value |
| :---------------------------------- | :------------------------------------------------------------------------------ |
| **Bounded Context / Owner** | Catalog — [[team\|catalog-experience-team]] |
| **Engine / Technology** | Qdrant (Qdrant Cloud in cloud; Qdrant container locally) |
| **Store Type** | Vector |
| **Primary Writer(s)** | [[service\|catalog-ingestion]] |
| **Primary Reader(s)** | [[service\|catalog-api]] |
| **Authoritative / Source of Truth** | Derived Read Model (Ephemeral) |
| **Data Classification** | Internal |
| **Retention / TTL Policy** | Transient (rebuildable derived projection from [[container\|catalog-database]]) |
## Logical Data Layout & Key Patterns
| Collection / Point Key | Stored Data | TTL / Eviction | Invalidation / Update Trigger |
| :-------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `data-bookworm-snippets` / `book_id` (`uuid`) | Assembled text (`Title`, `Description`, `Authors`, `Category`, `Publisher`) + `1,536`-dim cosine embedding (`Cohere.EmbedV40`) | Retained while book is active (`is_deleted = false`) | Asynchronous 5-minute batch triggered by [[service\|scheduler-service]] (`scheduler.process-vector-batch`) draining `pending_vector_updates`. Soft-deleted books are removed from the index. |
Commercial fields—prices, stock status, cover image URNs, and rating summaries—are intentionally excluded from Qdrant and always resolved from [[container|catalog-database]].
## Consistency, Isolation & Security Guardrails
- **Eventual search consistency:** Catalog mutations appear in semantic search after the next 5-minute [[service|scheduler-service]] tick and [[service|catalog-ingestion]] batch run (up to `200` books per batch).
- **Revision-safe single-writer batching:** [[service|catalog-ingestion]] acquires PostgreSQL advisory lock `740031001` and deletes queued items only when both `book_id` and `revision` match, preventing lost updates from concurrent edits. If embedding generation returns fewer vectors than active items, the batch fails without acknowledging the queue.
- **No direct external access:** Only [[service|catalog-ingestion]] writes to `data-bookworm-snippets` and only [[service|catalog-api]] queries it.
:::warning
**Derived Index Only — Never Authoritative:** `vectordb` is strictly a derived search projection. Never treat vector payloads as canonical product data, and never return prices or availability from Qdrant without hydrating from [[container|catalog-database]]. Because the index is fully rebuildable from `catalogdb`, collection resets carry zero data-loss risk.
:::
## Operational & Resilience Notes
- **Local vs. Cloud:** Local development runs a persistent Qdrant container managed by Aspire;
cloud environments connect to an external Qdrant Cloud cluster via environment connection
strings. - **Triaging stale search results:** Inspect three signals together: pending row count
and oldest `updated_at` in `catalogdb.pending_vector_updates`, scheduled job history in
[[container|scheduler-database]], and Qdrant/Microsoft Foundry traces in OpenTelemetry.
## Architecture Visualizations
## Related Documentation
- [[service|catalog-ingestion]] — Worker generating embeddings and updating Qdrant points.
- [[service|catalog-api]] — Hybrid search query pipeline and PostgreSQL hydration.
- [[container|catalog-database]] — Relational source of truth and `pending_vector_updates` queue.
- [[container|scheduler-database]] — Schedule store driving the 5-minute vector batch trigger.
- [[adr|adr-002-hybrid-vector-search-qdrant]] — Decision adopting Qdrant for hybrid catalog search.
- [[adr|adr-003-database-queue-for-vector-indexing]] — Decision for coalesced database-queue indexing.
- [[doc|operational/005-backup-restore-and-dr]] — Platform backup, restore, and disaster recovery runbook.
---
id: chat-session-blob
name: Chat Session Blob Storage
version: 1.0.0
summary: Authoritative Azure Blob Storage container owned by the Conversational bounded context for durable AG-UI multi-turn chat session state.
owners:
- ai-capabilities-team
container_type: objectStore
badges:
- content: Object Storage
backgroundColor: teal
textColor: teal
technology: azure-storage-account
authoritative: true
access_mode: readWrite
purpose: Stores durable Chat conversation session state across container restarts.
classification: confidential
retention: indefinite
residency: eastasia
styles:
icon: /icons/database/blob.svg
---
## Purpose & Ownership Boundary
Chat Session Blob Storage (`chatting-blob`) is the authoritative Azure Blob Storage container owned exclusively by [[service|chat-api]] in the Conversational bounded context. Object storage persists durable AG-UI multi-turn conversation sessions under the `ag-ui/` prefix so chat continuity survives container restarts without introducing a relational database or Redis dependency into [[service|chat-api]].
## Data Store Profile
| Property | Value |
| :---------------------------------- | :----------------------------------------------------------------------------- |
| **Bounded Context / Owner** | Conversational — [[team\|ai-capabilities-team]] |
| **Engine / Technology** | Azure Blob Storage (Azure Storage Account in cloud; Azurite emulator locally) |
| **Store Type** | Object Storage |
| **Primary Writer(s)** | [[service\|chat-api]] |
| **Primary Reader(s)** | [[service\|chat-api]] |
| **Authoritative / Source of Truth** | Yes |
| **Data Classification** | Confidential |
| **Retention / TTL Policy** | Indefinite (no automatic lifecycle TTL configured in infrastructure templates) |
## Logical Data Layout & Key Patterns
| Container / Prefix | Stored Data | TTL / Eviction | Invalidation / Update Trigger |
| :-------------------------- | :--------------------------------------------------- | :---------------------------------------------------------------- | :------------------------------------------------------ |
| `chatting-blob` / `ag-ui/*` | Serialized AG-UI workflow conversation session state | Indefinite (verify any externally managed Azure lifecycle policy) | Updated per conversation turn by [[service\|chat-api]]. |
Conversational state is intentionally split by concern: AG-UI workflow sessions live in `chatting-blob`, long-term user reading preferences live in Microsoft Foundry memory, agent scratchpads live on local ephemeral filesystem storage, and business domain records remain in their owning service stores.
## Consistency, Isolation & Security Guardrails
- **Confidential data & PII masking:** Conversation transcripts can contain customer preferences and session context even though Presidio PII middleware masks detected PII before model calls and outputs. Public blob access is disabled (`AllowBlobPublicAccess = false`), and access is restricted to [[service|chat-api]] via Managed Identity RBAC (`StorageBlobDataContributor`).
- **Startup readiness:** [[service|chat-api]] waits for `chatting-blob` health before accepting `/ag-ui` traffic.
- **No domain state leakage:** Business entities (books, baskets, orders, reviews) are never persisted in `chatting-blob`.
:::warning
**Strict Single-Service & Shared Account Isolation:** `chatting-blob` shares the Azure Storage Account with [[container|catalog-blob]] and Azure Functions host storage. No other BookWorm service or agent may read or write `chatting-blob` directly; all conversational interactions must flow through [[service|chat-api]].
:::
## Operational & Resilience Notes
- **Local vs. Cloud:** Local development uses a persistent Azurite emulator with Azure Storage
Explorer; cloud environments use Azure Storage Account with TLS 1.2 minimum (`StandardLrs` in
Dev, `StandardZrs` in Staging, `StandardGzrs` in Production). - **Retention governance:**
Because no automatic blob lifecycle policy is declared in repository infrastructure templates,
coordinate any GDPR/retention purge policies directly at the Azure Storage Account level.
## Architecture Visualizations
## Related Documentation
- [[service|chat-api]] — Owning AG-UI server, multi-agent workflow, and Microsoft Entra ID policies.
- [[agent|book-agent]] — Primary conversational agent operating over AG-UI sessions.
- [[container|catalog-blob]] — Sibling container on the shared Azure Storage Account.
- [[doc|operational/005-backup-restore-and-dr]] — Platform backup, restore, and disaster recovery runbook.
---
id: order-cache
name: Order Cache and Distributed Locks
version: 1.0.0
summary: Redis-backed coordination and caching slice owned by the Ordering bounded context for buyer-scoped creation locks, HTTP idempotency markers, and cached order summaries.
owners:
- commerce-fulfillment-team
container_type: cache
badges:
- content: Cache
backgroundColor: orange
textColor: orange
technology: azure-managed-redis
authoritative: false
access_mode: readWrite
classification: internal
retention: transient
residency: eastasia
purpose: Coordinate concurrent Order creation, detect repeated HTTP/Kafka requests, and share cached responses across Ordering replicas.
styles:
icon: /icons/database/redis.svg
---
## Purpose & Ownership Boundary
Order Cache and Distributed Locks is the non-authoritative Redis coordination and caching slice owned exclusively by [[service|order-api]] in the Ordering bounded context. Redis was chosen to provide low-latency distributed locking for concurrent checkout serialization, atomic HTTP `SET NX` idempotency markers, and FusionCache L2 + backplane caching across service replicas.
## Data Store Profile
| Property | Value |
| :---------------------------------- | :-------------------------------------------------------------------------- |
| **Bounded Context / Owner** | Ordering — [[team\|commerce-fulfillment-team]] |
| **Engine / Technology** | Redis + FusionCache (Azure Managed Redis in cloud; Redis container locally) |
| **Store Type** | Cache |
| **Primary Writer(s)** | [[service\|order-api]] |
| **Primary Reader(s)** | [[service\|order-api]] |
| **Authoritative / Source of Truth** | Ephemeral (permanent orders live in [[container\|order-database]]) |
| **Data Classification** | Internal |
| **Retention / TTL Policy** | Transient (all keys expire by TTL or explicit release) |
## Logical Data Layout & Key Patterns
| Key Pattern | Stored Data | TTL / Eviction | Invalidation / Update Trigger |
| :-------------------------------------------- | :----------------------------------------------------------------- | :--------------------------------------------- | :------------------------------------------------------------------------------------------------------------------- |
| `order-create:{BuyerId}` (`ordering` lock) | Distributed creation lock handle | `1 minute` acquisition timeout | Released explicitly in `finally` after committing the order unit of work. |
| `{HTTP method}:{request path}:{x-request-id}` | Atomic HTTP idempotency marker (`id`, `name`, `time`) via `SET NX` | `1 hour` (`3,600 seconds`) | Retained on `2xx`/`4xx` responses; deleted immediately on unhandled exceptions or `5xx` errors so clients can retry. |
| `books:{sorted book IDs}` | Cached Catalog gRPC book/price batch responses | `30 minutes` default (`books`, `catalog` tags) | TTL expiration or tag invalidation. |
| `ordering:dashboard:v1` | Aggregated Ordering and Catalog admin dashboard metrics | `15 seconds` | Time-based TTL expiration. |
| `ordering:summary:v1:{orderId}:v{version}` | Versioned order summary projection | `30 minutes` default | Immutable per version; expires by TTL. |
| `ordering:summary:v1:{orderId}:terminal` | Terminal-state order summary view | `1 hour` (L1 & L2) | Cached only for terminal orders; expires by TTL. |
| `ordering:history:v1:{orderId}:terminal` | Terminal-state order event history | `1 hour` (L1 & L2) | Cached only for terminal orders; expires by TTL. |
| Integration idempotency keys | 24-hour Kafka message deduplication markers | `24 hours` | Automatic TTL expiration after consumer processing. |
## Consistency, Isolation & Security Guardrails
- **Buyer-scoped lock boundaries:** [[service|order-api]] reads the basket and resolves Catalog prices _before_ acquiring `order-create:{BuyerId}`, keeping the critical section scoped strictly to order creation and persistence. The lock does not replace the PostgreSQL row-version concurrency token.
- **Atomic HTTP idempotency (`POST` / `PATCH`):** Requests without a non-empty `x-request-id` header are rejected (`400 Bad Request`), and duplicate in-flight or completed requests return `409 Conflict`.
- **Non-authoritative for purchases:** Accepted orders and checkout-time prices are always committed to [[container|order-database]].
:::warning
**Shared Redis Key-Prefix & Flush Isolation:** Order Cache shares the `redis` cluster with [[container|basket-database]], [[container|catalog-cache]], [[container|rating-cache]], and Notification idempotency markers. Flushing the shared Redis instance does not delete persisted orders in `orderingdb`, but it drops active HTTP idempotency markers, releases in-flight creation locks, and erases active customer baskets in [[container|basket-database]].
:::
## Operational & Resilience Notes
- **Local vs. Cloud:** Local development runs a persistent single-container Redis instance with
RedisInsight; cloud environments run Azure Managed Redis (`BalancedB0` in Dev, `BalancedB1` with
HA in Staging, `BalancedB5` with HA in Production). - **Availability impact:** While
non-authoritative for durable order history, Redis availability directly governs concurrent
checkout serialization and duplicate-request protection across Ordering replicas.
## Architecture Visualizations
## Related Documentation
- [[service|order-api]] — Owning service endpoints, gRPC clients, and order creation flow.
- [[container|order-database]] — Authoritative PostgreSQL store for buyers, orders, and event streams.
- [[container|basket-database]] — Sibling workload on the shared Redis resource.
- [[doc|operational/005-backup-restore-and-dr]] — Platform backup, restore, and disaster recovery runbook.
---
id: order-database
name: Order Database
version: 1.0.0
summary: Authoritative PostgreSQL system of record owned by the Ordering bounded context for buyers, accepted orders, purchase-time line items, and order lifecycle event streams.
owners:
- commerce-fulfillment-team
container_type: database
badges:
- content: Database
backgroundColor: blue
textColor: blue
technology: postgresql
authoritative: true
access_mode: readWrite
classification: confidential
retention: indefinite
residency: eastasia
purpose: Persist accepted purchases and Buyer profiles alongside order lifecycle event streams, projections, and transactional outbox storage.
styles:
icon: /icons/database/postgresql.svg
---
## Purpose & Ownership Boundary
Order Database (`orderingdb`) is the authoritative PostgreSQL system of record owned exclusively by [[service|order-api]] in the Ordering bounded context. PostgreSQL was chosen to combine ACID relational persistence for buyer profiles and immutable checkout snapshots with append-only order lifecycle event streams, read projections, and a transactional outbox over a single connection.
## Data Store Profile
| Property | Value |
| :---------------------------------- | :-------------------------------------------------------------------------------- |
| **Bounded Context / Owner** | Ordering — [[team\|commerce-fulfillment-team]] |
| **Engine / Technology** | PostgreSQL 18 (Azure Database for PostgreSQL Flexible Server) |
| **Store Type** | Database |
| **Primary Writer(s)** | [[service\|order-api]] |
| **Primary Reader(s)** | [[service\|order-api]] |
| **Authoritative / Source of Truth** | Yes |
| **Data Classification** | Confidential (contains customer names and shipping addresses) |
| **Retention / TTL Policy** | Indefinite (soft-delete on orders; subject to environment data-governance policy) |
## Logical Data Layout & Key Patterns
| Table / Schema | Owned Entity | Partition / Primary Key | Purpose & Concurrency |
| :--------------------- | :--------------------- | :------------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `buyers` | [[entity\|buyer]] | `id` (`uuidv7()`) | Customer profiles including name and shipping address (`street`, `city`, `province`). |
| `orders` | [[entity\|order]] | `id` (`uuidv7()`) | Accepted orders with status (`New`, `Cancelled`, `Completed`), order note, timestamps, and soft-delete flag; optimistic concurrency via row-version token. |
| `order_items` | [[entity\|order-item]] | `id` (`uuidv7()`), unique (`book_id`, `order_id`) | Immutable checkout-time line item snapshots locking `book_id`, quantity, and unit price at purchase time. |
| Event store (`public`) | [[entity\|order]] | Stream ID (`order_id`) | Append-only order placement, completion, and cancellation events; live stream aggregation and asynchronous summary projection (`DaemonLockId = 44444`). |
| `wolverine` schema | — | Envelope ID | Transactional outbox and inbox tables sharing the domain write transaction; partitions Kafka events ([[event\|UserCheckedOutIntegrationEvent]], [[event\|OrderStatusChangedToCompleteIntegrationEvent]], [[event\|OrderStatusChangedToCancelIntegrationEvent]]) by `OrderId`. |
## Consistency, Isolation & Security Guardrails
- **Checkout price immutability:** `order_items` persists the unit price resolved at checkout so subsequent price edits in [[container|catalog-database]] never alter historical purchases.
- **Soft-delete audit preservation:** Administrative cleanup and failed basket-cleanup compensation mark orders as soft-deleted (filtered from normal reads) rather than physically erasing rows.
- **Eventually consistent summary views:** Asynchronous order summary projections can briefly lag transactional writes; `orders` remains the canonical source for order status.
- **Confidential PII posture:** Buyer names and street/city/province addresses are classified `confidential` and protected by encryption at rest, regional residency, and backup retention policies.
:::warning
**Database-per-Service Isolation:** Only [[service|order-api]] may read or write `orderingdb`. Active pre-checkout baskets live in [[container|basket-database]], temporary locks and HTTP idempotency markers live in [[container|order-cache]], and post-checkout saga state lives in [[service|order-orchestration]]. External services must never query `orderingdb` directly.
:::
## Operational & Resilience Notes
- **Local vs. Cloud:** Local development runs a persistent PostgreSQL container alongside
`catalogdb` and `schedulerdb`; cloud environments run Azure Database for PostgreSQL Flexible
Server. - **Scaling & HA:** Development uses `Standard_B1ms` (single zone, 7-day backup, 32 GB);
Staging uses `Standard_D2ds_v5` (zone-redundant HA, PgBouncer, 14-day backup, 128 GB);
Production uses `Standard_D4ds_v5` (zone-redundant HA, PgBouncer, 35-day backup, 256 GB). -
**Active messaging schema:** Treat the `wolverine` schema as the sole authoritative messaging
store; ignore any retired messaging tables from historical migrations.
## Architecture Visualizations
## Related Documentation
- [[service|order-api]] — Owning service endpoints, gRPC clients, and Kafka handlers.
- [[container|order-cache]] — Redis locks, atomic HTTP idempotency, and cached responses.
- [[service|order-orchestration]] — Saga coordinating post-checkout cleanup and notifications.
- [[adr|adr-001-postgresql-order-system-of-record]] — Decision establishing PostgreSQL as Ordering's system of record.
- [[adr|adr-002-preserve-checkout-purchase-snapshot]] — Decision locking checkout-time prices in `order_items`.
- [[doc|operational/005-backup-restore-and-dr]] — Platform backup, restore, and disaster recovery runbook.
---
id: rating-cache
name: Rating Cache
version: 1.0.0
summary: Non-authoritative FusionCache and Redis caching layer owned by the Reviews bounded context for AI-generated book feedback summaries and review lists.
owners:
- catalog-experience-team
container_type: cache
badges:
- content: Cache
backgroundColor: orange
textColor: orange
technology: azure-managed-redis
authoritative: false
access_mode: readWrite
classification: internal
retention: transient
residency: eastasia
purpose: Non-authoritative cache for per-book feedback summaries and lists returned by Rating API.
styles:
icon: /icons/database/redis.svg
---
## Purpose & Ownership Boundary
Rating Cache is the non-authoritative FusionCache L1 + Redis L2 caching tier owned exclusively by [[service|rating-api]] in the Reviews bounded context. Caching avoids repeated multi-step LLM summarization runs for identical books while keeping [[container|rating-database]] (Azure Cosmos DB) as the sole source of truth for customer feedback.
## Data Store Profile
| Property | Value |
| :---------------------------------- | :---------------------------------------------------------------------------------------------------- |
| **Bounded Context / Owner** | Reviews — [[team\|catalog-experience-team]] |
| **Engine / Technology** | Redis + FusionCache (Azure Managed Redis in cloud; Redis container locally) |
| **Store Type** | Cache |
| **Primary Writer(s)** | [[service\|rating-api]] |
| **Primary Reader(s)** | [[service\|rating-api]] |
| **Authoritative / Source of Truth** | Derived Read Model (Ephemeral) |
| **Data Classification** | Internal |
| **Retention / TTL Policy** | Transient (`6 hours` for reviewed books; `1 minute` when `reviewCount == 0`; 2-hour fail-safe window) |
## Logical Data Layout & Key Patterns
| Key Pattern | Stored Data | TTL / Eviction | Invalidation / Update Trigger |
| :------------------------------------------------ | :----------------------------------------------------------------------------------------------------------- | :------------------------------------------ | :------------------------------------------------------------------------------------------------ |
| `rating:summary:v1:{BookId}` (`reviewCount > 0`) | JSON summary payload (`summary`, `classification`, `averageRating`, `reviewCount`, `evidence`, `confidence`) | `6 hours` (L1 & L2) | Actively evicted on feedback deletions/reversions; refreshes by 6-hour TTL on additional reviews. |
| `rating:summary:v1:{BookId}` (`reviewCount == 0`) | Empty-state summary payload (avoids LLM calls) | `1 minute` (L1 & L2) | Actively evicted immediately when the first feedback is created, deleted, or reverted. |
| Feedback list keys (tagged by `BookId`) | Paginated [[entity\|feedback]] list payloads | `30 minutes` (`Caching:Expiration` default) | Actively evicted by tag on feedback creation, deletion, or reversion. |
| Integration idempotency keys | 24-hour Kafka message deduplication markers | `24 hours` | Automatic TTL expiration after consumer processing. |
## Consistency, Isolation & Security Guardrails
- **Asymmetric summary staleness window:** Deletions, reversions, and the first review on an unreviewed book evict `rating:summary:v1:{BookId}` immediately; adding another review to an already-reviewed book refreshes on the `6-hour` TTL to bound LLM summarization cost.
- **Stampede & fail-safe protection:** Distributed Redis locking ensures only one replica invokes [[agent|rating-agent]] on a cache miss, and a 2-hour fail-safe window protects availability during transient downstream issues.
- **Targeted invalidation:** To force regeneration for a single book, delete only `rating:summary:v1:{BookId}`.
:::warning
**Shared Redis Key-Prefix & Flush Isolation:** Rating Cache shares the `redis` cluster with [[container|basket-database]], [[container|catalog-cache]], [[container|order-cache]], and Notification idempotency markers. Never flush the shared Redis instance globally—doing so clears active customer baskets, distributed checkout locks, and 24-hour Kafka idempotency markers across five services.
:::
## Operational & Resilience Notes
- **Local vs. Cloud:** Local development runs a persistent single-container Redis instance with
RedisInsight; cloud environments run Azure Managed Redis (`BalancedB0` in Dev, `BalancedB1` with
HA in Staging, `BalancedB5` with HA in Production). - **Disposable state:** Every cached summary
and review list is fully rebuildable from [[container|rating-database]] and
[[agent|rating-agent]] on cache miss.
## Architecture Visualizations
## Related Documentation
- [[service|rating-api]] — Owning service REST endpoints, A2A gRPC server, and summary query.
- [[container|rating-database]] — Authoritative Azure Cosmos DB store behind this cache.
- [[agent|rating-agent]] — AI agent invoked on summary cache misses.
- [[adr|adr-004-read-only-governed-feedback-summarization]] — Decision governing read-only AI summarization.
- [[doc|operational/005-backup-restore-and-dr]] — Platform backup, restore, and disaster recovery runbook.
---
id: rating-database
name: Rating Database
version: 1.0.0
summary: Authoritative Azure Cosmos DB system of record owned by the Reviews bounded context for customer feedback documents partitioned by book ID.
owners:
- catalog-experience-team
container_type: database
badges:
- content: Database
backgroundColor: blue
textColor: blue
technology: cosmosdb
authoritative: true
access_mode: readWrite
purpose: Stores individual customer feedback records (book ID, reviewer name, comment, and rating) in the feedbacks container partitioned by /bookId.
classification: internal
retention: indefinite
residency: eastasia
---
## Purpose & Ownership Boundary
Rating Database (`ratingdb`) is the authoritative Azure Cosmos DB system of record owned exclusively by [[service|rating-api]] in the Reviews bounded context. Cosmos DB was chosen for low-latency, single-partition document reads keyed by `/bookId` when listing book reviews or running AI summarization, alongside native Wolverine Cosmos DB message persistence.
## Data Store Profile
| Property | Value |
| :---------------------------------- | :------------------------------------------------------------------------------- |
| **Bounded Context / Owner** | Reviews — [[team\|catalog-experience-team]] |
| **Engine / Technology** | Azure Cosmos DB (NoSQL API; Cosmos DB Emulator locally) |
| **Store Type** | Database |
| **Primary Writer(s)** | [[service\|rating-api]] |
| **Primary Reader(s)** | [[service\|rating-api]], [[agent\|rating-agent]] (governed read-only tool) |
| **Authoritative / Source of Truth** | Yes |
| **Data Classification** | Internal (reviewer `firstName` and `lastName` treated as PII in command logging) |
| **Retention / TTL Policy** | Indefinite |
## Logical Data Layout & Key Patterns
| Container | Owned Entity | Partition / Primary Key | Purpose & Concurrency |
| :-------------------- | :------------------- | :------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `feedbacks` | [[entity\|feedback]] | Partition key: `/bookId` (`uuid`); Document key: `id` (`uuid`) | Stores `bookId`, `firstName` (max 50), `lastName` (max 50), optional `comment` (max 1,000), `rating` (`0`–`5`), `createdAt`, `lastModifiedAt`; optimistic concurrency via `_etag`. |
| Wolverine persistence | — | Envelope ID | Durable integration message state in `ratingdb` for [[event\|FeedbackCreatedIntegrationEvent]] and [[event\|FeedbackDeletedIntegrationEvent]]. |
## Consistency, Isolation & Security Guardrails
- **ETag optimistic concurrency & conflicts:** Concurrent modifications raise ETag concurrency failures, and duplicate/conflict responses (`409 Conflict`) are surfaced cleanly at the API boundary. Note that the provisioned `feedbacks` container declares `/bookId` as its partition key without a Cosmos unique-key policy.
- **Governed read-only agent access:** [[agent|rating-agent]] reads reviews through its governed review-lookup tool (`default_action: deny`, rate-limited at `30/minute`). Generated AI summaries and classifications are never written back to `ratingdb`.
- **Eventual consistency with Catalog:** [[service|catalog-api]] never queries Cosmos DB directly; it consumes [[event|FeedbackCreatedIntegrationEvent]] and [[event|FeedbackDeletedIntegrationEvent]] to update derived `average_rating` and `total_reviews` projections in [[container|catalog-database]].
- **PII & validation:** Reviewer `firstName` and `lastName` are annotated for PII redaction in command logs, and rating bounds (`0`–`5`) are enforced at the [[service|rating-api]] boundary.
:::warning
**Database-per-Service Isolation:** Only [[service|rating-api]] may write to `ratingdb`, and [[agent|rating-agent]] is restricted to governed read-only queries. Never run PostgreSQL DDL scripts against Rating in live environments (the attached `schema.sql` is a legacy/reference relational DDL only; the active store is Azure Cosmos DB).
:::
## Operational & Resilience Notes
- **Local vs. Cloud:** Local development uses a persistent Azure Cosmos DB Emulator with Data
Explorer; Azure Development and Staging use Serverless capacity, while Production uses
provisioned throughput. - **Authentication:** Staging and Production disable local keys
(`DisableLocalAuth = true`) and enforce Microsoft Entra ID RBAC exclusively.
## Architecture Visualizations & Schema
## Related Documentation
- [[service|rating-api]] — Owning service REST endpoints, Cosmos DB wiring, and A2A gRPC server.
- [[container|rating-cache]] — FusionCache L1 + Redis L2 cache for AI feedback summaries.
- [[agent|rating-agent]] — Read-only review summarization and quality assessment agent.
- [[container|catalog-database]] — Downstream PostgreSQL store maintaining derived book rating summaries.
- [[adr|adr-001-postgresql-feedback-system-of-record]] — Decision record for feedback persistence and boundaries.
- [[doc|operational/005-backup-restore-and-dr]] — Platform backup, restore, and disaster recovery runbook.
---
id: scheduler-database
name: Scheduler Database
version: 1.0.0
summary: Authoritative PostgreSQL database owned by the Platform bounded context for Quartz.NET job definitions, cluster locks, execution history, and outbox envelopes.
owners:
- platform-engineering-team
container_type: database
badges:
- content: Database
backgroundColor: blue
textColor: blue
technology: postgresql
authoritative: true
access_mode: readWrite
classification: internal
retention: 30d history / indefinite schedules
residency: eastasia
purpose: Persist Quartz.NET schedules, cluster coordination locks, bounded execution history, and transactional outbox state.
styles:
icon: /icons/database/postgresql.svg
---
## Purpose & Ownership Boundary
Scheduler Database (`schedulerdb`) is the authoritative PostgreSQL database owned exclusively by [[service|scheduler-service]] in the Platform bounded context. PostgreSQL was chosen to back Quartz.NET's clustered ADO.NET job store with transactional locking, durable misfire tracking, and a co-located Wolverine outbox for reliable scheduled event publication.
## Data Store Profile
| Property | Value |
| :---------------------------------- | :------------------------------------------------------------------------------------------- |
| **Bounded Context / Owner** | Platform — [[team\|platform-engineering-team]] |
| **Engine / Technology** | PostgreSQL 18 (Azure Database for PostgreSQL Flexible Server) |
| **Store Type** | Database |
| **Primary Writer(s)** | [[service\|scheduler-service]] |
| **Primary Reader(s)** | [[service\|scheduler-service]] |
| **Authoritative / Source of Truth** | Yes |
| **Data Classification** | Internal |
| **Retention / TTL Policy** | Indefinite for schedules; `30 days` or `100,000` entries per scheduler for execution history |
## Logical Data Layout & Key Patterns
| Table / Schema | Owned Entity | Partition / Primary Key | Purpose & Concurrency |
| :------------------------------------------------------------------------------------------------------------------------------------------------- | :----------- | :----------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `qrtz_job_details`, `qrtz_triggers`, `qrtz_cron_triggers`, `qrtz_simple_triggers`, `qrtz_simprop_triggers`, `qrtz_blob_triggers`, `qrtz_calendars` | — | (`sched_name`, `job_name`/`trigger_name`, group) | Persistent job metadata, cron/simple triggers (including `ProcessVectorBatchJob` every 5 minutes UTC and `HeartbeatJob` every 30 seconds), and calendar constraints. |
| `qrtz_fired_triggers`, `qrtz_scheduler_state`, `qrtz_locks`, `qrtz_paused_trigger_grps`, `qrtz_paused_job_grps`, `qrtz_job_status` | — | (`sched_name`, `lock_name` / `entry_id`) | Active firing state, cluster instance heartbeats, and row-level distributed locks preventing split-brain execution. |
| `qrtz_execution_history`, `qrtz_misfire_history` | — | History entry ID | Bounded execution and misfire audit trail (`30 days` / `100,000` entries per scheduler). |
| `wolverine` schema | — | Envelope ID | Transactional outbox/inbox tables for reliable Kafka publication (such as [[event\|ProcessVectorBatchIntegrationEvent]] on `scheduler.process-vector-batch`). |
## Consistency, Isolation & Security Guardrails
- **No direct SQL mutations:** Operators must manage schedules and triggers through the Entra ID-protected Quartz Dashboard (`/quartz`, `admin` role) or declarative job configuration—direct `UPDATE`/`DELETE` statements against `qrtz_*` tables corrupt cluster lock state.
- **No sensitive data in job payloads:** Never store connection strings, credentials, authorization headers, or personal data in `job_data` (`BYTEA`), as operational tables are inspected during diagnostics.
- **Trigger vs. business completion:** A succeeded execution record confirms only that Scheduler ran the job and enqueued its outbound event; verify downstream consumers (such as [[service|catalog-ingestion]]) for end-to-end completion.
- **Graceful shutdown:** In-flight jobs are awaited before container termination to prevent partial trigger states.
:::warning
**Database-per-Service & Destructive Script Guardrail:** Only [[service|scheduler-service]] may read or write `schedulerdb`—downstream services like [[service|catalog-api]], [[service|catalog-ingestion]], and [[service|notification-api]] never access it directly. Never execute the initialization DDL script with `DropDb := 1` against a live environment, as doing so drops all 15 `qrtz_*` tables and erases all registered schedules and execution history.
:::
## Operational & Resilience Notes
- **Local vs. Cloud:** Local development runs a persistent PostgreSQL container alongside
`catalogdb` and `orderingdb` (with explicit start in the Aspire dashboard); cloud environments
run Azure Database for PostgreSQL Flexible Server. - **Scaling & HA:** Development uses
`Standard_B1ms` (single zone, 7-day backup, 32 GB); Staging uses `Standard_D2ds_v5`
(zone-redundant HA, PgBouncer, 14-day backup, 128 GB); Production uses `Standard_D4ds_v5`
(zone-redundant HA, PgBouncer, 35-day backup, 256 GB). - **Long-term audit:** Export longer-term
execution metrics to OpenTelemetry observability, as `qrtz_execution_history` is capped at `30
days` / `100,000` rows.
## Architecture Visualizations & Schema
## Related Documentation
- [[service|scheduler-service]] — Owning service configuration, dashboard authentication, and job orchestration.
- [[service|catalog-ingestion]] — Downstream consumer of `scheduler.process-vector-batch`.
- [[doc|platform/005-quartz-schema]] — Complete PostgreSQL table definitions for all Quartz entities.
- [[adr|adr-001-postgresql-quartz-persistence]] — Decision establishing PostgreSQL persistence for Quartz.NET.
- [[doc|operational/005-backup-restore-and-dr]] — Platform backup, restore, and disaster recovery runbook.
---
id: agent-orchestration
name: Chat Agent Orchestration
version: 1.0.0
summary: >-
A customer submits a conversational request through Storefront; Chat API
screens input, routes via a non-LLM classifier with optional human
disambiguation, delegates to specialist agents, and formats the response.
owners:
- ai-capabilities-team
badges:
- content: AI Agent Orchestration
backgroundColor: purple
textColor: purple
steps:
- id: CustomerSubmitsChat
title: Customer sends a chat message
summary: >-
Submits a book-discovery, review-summary, or store-policy question through
the Storefront chat interface.
actor:
name: Customer
next_step:
id: InvokeChatWorkflow
label: Send authenticated chat request
- id: InvokeChatWorkflow
title: Chat API starts conversational workflow
summary: >-
Enforces customer authentication and per-user rate limits, loads session
state, and starts the composed conversational workflow.
service:
id: chat-api
version: 1.0.0
next_steps:
- id: SessionStore
label: Load or persist conversation session
- id: InputScreening
label: Screen and normalize customer input
- id: SessionStore
title: Chat Session Blob Store
summary: Persists multi-turn conversation history in Azure Blob Storage.
container:
id: chat-session-blob
version: 1.0.0
- id: InputScreening
title: Input Safety & Length Screening
summary: >-
Trims whitespace, rejects empty messages and prompt-injection patterns,
truncates prompts over 2,000 characters, and redacts PII via Data Privacy.
service:
id: presidio-api
version: 1.0.0
next_steps:
- id: DecisionRouter
label: Accepted input
- id: RejectedBoundary
label: Empty or unsafe input rejected
- id: RejectedBoundary
title: Boundary rejection response
summary: Returns a safe rejection message without invoking routing or AI agents.
custom:
title: Input rejected
type: Outcome
icon: ExclamationTriangleIcon
color: red
- id: DecisionRouter
title: Non-LLM Intent & Scope Router
summary: >-
Evaluates English language, BookWorm scope, and target specialist using a
lightweight decision model. Low-confidence in-scope requests trigger
customer disambiguation.
custom:
title: Decision Router
type: Router
icon: AdjustmentsHorizontalIcon
color: blue
next_steps:
- id: RouteDisambiguation
label: Low-confidence in-scope route
- id: BookAgent
label: Book discovery or general reviews
- id: QAAgent
label: Store policies and support
- id: RatingAgent
label: Review summary with book ID
- id: OutOfScopeBoundary
label: Non-English or out-of-scope
- id: RouteDisambiguation
title: Customer Route Disambiguation
summary: >-
Pauses the workflow and prompts the customer to choose between Book, QA,
or Rating specialists before resuming.
actor:
name: Customer
next_steps:
- id: BookAgent
label: Selected Book Agent
- id: QAAgent
label: Selected QA Agent
- id: RatingAgent
label: Selected Rating Agent
- id: OutOfScopeBoundary
label: Unresolved or out-of-scope
- id: OutOfScopeBoundary
title: Scope boundary response
summary: >-
Returns a polite out-of-scope or language boundary message without
invoking specialist agents.
custom:
title: Out-of-scope boundary
type: Outcome
icon: CheckCircleIcon
color: gray
- id: BookAgent
title: Book Agent
summary: >-
Handles catalog search and recommendations using MCP Tools, or delegates
complex multi-part discovery to parallel sub-researchers.
agent:
id: book-agent
version: 1.0.0
next_steps:
- id: MCPTools
label: Direct catalog lookup
- id: ParallelBookResearch
label: Complex multi-part discovery
- id: RatingAgent
label: Hand off review summary
- id: QAAgent
label: Hand off store policy question
- id: MCPTools
title: MCP Server - Catalog Tools
summary: Provides read-only book, author, and category tools to Book specialists.
service:
id: mcp-server
version: 1.0.0
next_step:
id: ResponseFormatter
label: Return grounded catalog response
- id: QAAgent
title: QA Agent
summary: >-
Answers store-policy, shipping, and returns questions from grounded policy
context, directing live account requests to human support.
agent:
id: qa-agent
version: 1.0.0
next_steps:
- id: BookAgent
label: Follow-up needs book facts
- id: ResponseFormatter
label: Customer-support response ready
- id: RatingAgent
title: Rating Agent
summary: >-
Summarizes book reviews and rating signals over Agent-to-Agent gRPC in
Rating API.
agent:
id: rating-agent
version: 1.0.0
next_step:
id: ResponseFormatter
label: Return review summary
- id: ParallelBookResearch
title: Parallel Book Research
summary: Runs factual catalog lookup and preference recommendation in parallel.
custom:
title: Parallel Research Fan-Out
type: Orchestration
icon: ArrowsPointingOutIcon
color: purple
next_steps:
- id: BookCatalogResearcher
label: Book facts and metadata
- id: BookRecommendationResearcher
label: Preference-matched shortlist
- id: BookCatalogResearcher
title: Book Catalog Researcher
summary: Gathers concise facts about books, authors, categories, and publishers.
agent:
id: book-catalog-researcher
version: 1.0.0
next_step:
id: SynthesizeBookResearch
label: Return catalog findings
- id: BookRecommendationResearcher
title: Book Recommendation Researcher
summary: Curates a preference-matched shortlist with supporting facts.
agent:
id: book-recommendation-researcher
version: 1.0.0
next_step:
id: SynthesizeBookResearch
label: Return recommendation shortlist
- id: SynthesizeBookResearch
title: Book Agent synthesizes parallel research
summary: Merges findings, deduplicates titles, and composes a unified answer.
agent:
id: book-agent
version: 1.0.0
next_step:
id: ResponseFormatter
label: Format final response
- id: ResponseFormatter
title: Response Hygiene & Formatting
summary: >-
Trims assistant output, strips accidental system-prompt fragments, and
normalizes punctuation before returning to Storefront.
service:
id: chat-api
version: 1.0.0
---
## Trigger & Business Outcome
This flow is triggered when an authenticated customer sends a conversational message from the Storefront to [[service|chat-api]]. Success is confirmed when [[service|chat-api]] screens the input, routes it to the appropriate specialist ([[agent|book-agent]], [[agent|qa-agent]], or [[agent|rating-agent]]), persists session context in [[container|chat-session-blob]], and returns a formatted, read-only response without exposing transactional order or account mutations.
## Interactive Flow Visualization
## Step-by-Step Walkthrough
[[service|chat-api]] enforces customer authentication and per-user rate limits, loads multi-turn
history from [[container|chat-session-blob]], and screens input for empty prompts, prompt
injection, excessive length, and PII redaction via [[service|presidio-api]].
A lightweight non-LLM decision router checks English language, BookWorm scope, and target
specialist. Non-English or off-topic prompts short-circuit immediately; low-confidence in-scope
prompts pause for customer disambiguation.
[[agent|book-agent]] queries live catalog data through [[service|mcp-server]] or fans out
concurrently to [[agent|book-catalog-researcher]] and [[agent|book-recommendation-researcher]].
[[agent|qa-agent]] answers store-policy questions, and [[agent|rating-agent]] provides review
summaries over Agent-to-Agent gRPC.
[[service|chat-api]] strips any leaked system-prompt fragments, normalizes punctuation, saves
updated session state in [[container|chat-session-blob]], and streams the final answer to
Storefront.
## Failure, Retry & Compensation Behavior
| Failure Point | System Behavior | Compensation / Recovery |
| :----------------------------------------- | :---------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------- |
| **Prompt injection or empty input** | Input screening rejects the turn before routing | Returns a safe boundary prompt without consuming specialist LLM tokens |
| **Low-confidence in-scope route** | Workflow pauses and asks the customer to pick a specialist | Resumes immediately with the customer's chosen specialist |
| **Account or live-order mutation request** | qa-agent enforces a strict read-only boundary | Directs the customer to Commerce or human support |
:::warning
**Read-only conversational boundary:** None of the conversational agents can edit baskets, place orders, cancel orders, or submit reviews. Always route customer traffic through [[service|chat-api]] so input screening, PII redaction, and response formatting are enforced.
:::
## Participating Resources
- **Domains & Systems:** [[domain|conversational]], [[domain|reviews]], [[system|chat-system]], [[system|mcp-tools]], [[system|data-privacy]]
- **Services & Stores:** [[service|chat-api]], [[service|mcp-server]], [[service|presidio-api]], [[container|chat-session-blob]]
- **AI Agents:** [[agent|book-agent]], [[agent|book-catalog-researcher]], [[agent|book-recommendation-researcher]], [[agent|qa-agent]], [[agent|rating-agent]]
- **Related Views:** [[flow|feedback-publication]]
---
id: feedback-publication
name: Customer Feedback Publication and Projection
version: 1.0.0
summary: >-
Rating API persists customer feedback in Cosmos DB and publishes an
integration event; Catalog API updates the derived book rating summary or
emits a compensating failure event to delete orphaned feedback.
owners:
- catalog-experience-team
badges:
- content: Event-Driven
backgroundColor: purple
textColor: purple
steps:
- id: customer
title: Customer submits feedback for a book
actor:
name: Customer
next_step:
id: create-feedback
label: Submit rating and optional comment
- id: create-feedback
title: CreateFeedback command
message:
id: CreateFeedback
version: 1.0.0
next_step:
id: rating-api
label: Validate and persist feedback
- id: rating-api
title: Rating API persists new feedback
summary: >-
Validates the book ID, score, reviewer name, and comment, then commits the
authoritative feedback record to Cosmos DB.
service:
id: rating-api
version: 1.0.0
next_step:
id: rating-db
label: Save feedback document
- id: rating-db
title: Rating Database stores committed feedback
summary: >-
Stores the authoritative Feedback document partitioned by book ID and
atomically queues the integration event.
container:
id: rating-database
version: 1.0.0
next_step:
id: feedback-created
label: Publish feedback-created event
- id: feedback-created
title: FeedbackCreatedIntegrationEvent
message:
id: FeedbackCreatedIntegrationEvent
version: 1.0.0
next_step:
id: feedback-create-channel
label: Publish to rating.feedback-create
- id: feedback-create-channel
title: Feedback created channel
channel:
id: bookworm.{env}.rating.feedback-create
version: 1.0.0
next_step:
id: catalog-api
label: Deliver to Catalog API
- id: catalog-api
title: Catalog API updates derived rating summary
summary: >-
Applies a 24-hour Redis idempotency guard, looks up the book in Catalog
Database, and updates the derived average rating and review count.
service:
id: catalog-api
version: 1.0.0
next_steps:
- id: catalog-db
label: Active book found; update summary
- id: feedback-compensation
label: Missing book; trigger compensation
- id: catalog-db
title: Catalog Database stores updated rating summary
summary: >-
Persists the recalculated average rating and total review count on the
book record for storefront discovery.
container:
id: catalog-database
version: 1.0.0
- id: feedback-compensation
title: BookUpdatedRatingFailedIntegrationEvent
message:
id: BookUpdatedRatingFailedIntegrationEvent
version: 1.0.0
next_step:
id: compensation-channel
label: Publish to catalog.book-update-rating-failed
- id: compensation-channel
title: Rating update failed channel
channel:
id: bookworm.{env}.catalog.book-update-rating-failed
version: 1.0.0
next_step:
id: rating-api-cleanup
label: Deliver compensation to Rating API
- id: rating-api-cleanup
title: Rating API deletes orphaned feedback
summary: >-
Deletes the invalid feedback document from Cosmos DB so Reviews and
Catalog remain consistent without leaving orphaned data.
service:
id: rating-api
version: 1.0.0
---
## Trigger & Business Outcome
This flow starts when a customer submits [[command|CreateFeedback]] for a book through [[service|rating-api]]. Success is confirmed when [[service|rating-api]] persists the authoritative [[entity|feedback]] document in [[container|rating-database]] and [[service|catalog-api]] asynchronously updates the book's derived average rating and review count in [[container|catalog-database]]—or, if the book does not exist, compensates by deleting the orphaned feedback.
## Interactive Flow Visualization
## Step-by-Step Walkthrough
[[service|rating-api]] validates the rating score, reviewer details, and comment, commits the
[[entity|feedback]] document to [[container|rating-database]], and publishes
[[event|FeedbackCreatedIntegrationEvent]] to{" "}
`bookworm.{env}.rating.feedback-create`
.
[[service|catalog-api]] consumes [[event|FeedbackCreatedIntegrationEvent]] behind a 24-hour
Redis idempotency guard, loads the target [[entity|book]] from [[container|catalog-database]],
and updates its derived average rating and total review count without storing review text or
reviewer PII.
If [[service|catalog-api]] finds no active book for the referenced ID, it emits
[[event|BookUpdatedRatingFailedIntegrationEvent]] on{" "}
`bookworm.{env}.catalog.book-update-rating-failed`
. [[service|rating-api]] consumes this compensating event and deletes the orphaned
[[entity|feedback]] record from [[container|rating-database]].
## Failure, Retry & Compensation Behavior
| Failure Point | System Behavior | Compensation / Recovery |
| :----------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Duplicate event delivery** | Redis idempotency guard deduplicates by event ID for 24 hours | Prevents double-counting ratings during Kafka redeliveries or transient retries |
| **Referenced book does not exist** | catalog-api emits BookUpdatedRatingFailedIntegrationEvent | rating-api deletes the orphaned feedback record from rating-database |
| **Transient Catalog database error** | Worker retries with exponential backoff | Exhausted failures route to `bookworm.{env}.catalog.dead-letter-queue` for replay |
:::note
**Feedback deletion follows a separate one-way contract:** When a review is deleted, [[service|rating-api]] publishes [[event|FeedbackDeletedIntegrationEvent]] on `bookworm.{env}.rating.feedback-delete`, and [[service|catalog-api]] decrements the derived rating summary (treating a missing book as a safe no-op).
:::
## Participating Resources
- **Domains & Systems:** [[domain|reviews]], [[domain|catalog]], [[system|rating-system]], [[system|product-catalog-system]]
- **Services:** [[service|rating-api]], [[service|catalog-api]]
- **Messages:** [[command|CreateFeedback]], [[event|FeedbackCreatedIntegrationEvent]], [[event|BookUpdatedRatingFailedIntegrationEvent]], [[event|FeedbackDeletedIntegrationEvent]]
- **Channels & Stores:** `bookworm.{env}.rating.feedback-create`, `bookworm.{env}.catalog.book-update-rating-failed`, `bookworm.{env}.rating.feedback-delete`, `bookworm.{env}.catalog.dead-letter-queue`, [[container|rating-database]], [[container|catalog-database]]
- **Related Views:** [[diagram|rating-summarizer-workflow]]
---
id: notification-delivery
name: Notification Delivery
version: 1.0.0
summary: >-
Finance emits order-notification commands over Kafka; Notification API
applies Redis idempotency, renders MJML email templates, and submits MIME
messages over SMTP with bounded retries and dead-lettering.
owners:
- platform-engineering-team
badges:
- content: Platform Capability
backgroundColor: blue
textColor: blue
steps:
- id: finance
title: Finance emits order notification command
summary: >-
Publishes placement, completion, or cancellation notification commands
over Kafka without coupling order status to email delivery.
service:
id: order-orchestration
version: 1.0.0
next_steps:
- id: place-order
label: New order placed
- id: complete-order
label: Order completed
- id: cancel-order
label: Order cancelled or orchestration timed out
- id: place-order
title: PlaceOrderCommand
message:
id: PlaceOrderCommand
version: 1.0.0
next_step:
id: placement-channel
label: Publish to finance.place-order
- id: complete-order
title: CompleteOrderCommand
message:
id: CompleteOrderCommand
version: 1.0.0
next_step:
id: notification-api
label: Deliver via finance.complete-order
- id: cancel-order
title: CancelOrderCommand
message:
id: CancelOrderCommand
version: 1.0.0
next_step:
id: notification-api
label: Deliver via finance.cancel-order
- id: placement-channel
title: Finance placement channel
channel:
id: bookworm.{env}.finance.place-order
version: 1.0.0
next_step:
id: notification-api
label: Consume placement command
- id: notification-api
title: Notification API deduplicates and renders email
summary: >-
Checks a 24-hour Redis idempotency guard keyed by message ID, skips blank
recipients, and renders the order email template into a MIME message.
service:
id: notification-api
version: 1.0.0
next_steps:
- id: smtp-provider
label: Valid recipient and template rendered
- id: notification-skipped
label: Recipient email absent
- id: notification-skipped
title: Email delivery skipped
summary: >-
Returns cleanly without calling SMTP when no recipient address is present.
custom:
title: Email skipped
type: Outcome
icon: CheckCircleIcon
color: gray
- id: smtp-provider
title: SendGrid - SMTP submission
summary: >-
Submits the rendered MIME email over SMTP with MailKit resilience (Mailpit
locally, SendGrid in Azure).
service:
id: sendgrid-api
version: 1.0.0
next_steps:
- id: notification-sent
label: SMTP provider accepted message
- id: notification-failed
label: Submission failed after retries
- id: notification-sent
title: Email submitted to SMTP provider
summary: >-
Provider accepted the message for delivery. Notification emits no
delivery-result callback.
custom:
title: Email submitted
type: Outcome
icon: CheckCircleIcon
color: green
- id: notification-failed
title: Notification dead-letter queue
summary: >-
Exhausted transient failures route the command to the dead-letter queue
for operator inspection.
channel:
id: bookworm.{env}.notification.dead-letter-queue
version: 1.0.0
---
## Trigger & Business Outcome
This flow is triggered when [[service|order-orchestration]] publishes [[command|PlaceOrderCommand]], [[command|CompleteOrderCommand]], or [[command|CancelOrderCommand]] over Kafka. Success is confirmed when [[service|notification-api]] passes its Redis idempotency check, renders the MJML order template, and hands the MIME message off to [[service|sendgrid-api]] over SMTP (or Mailpit in local development) without maintaining any relational email outbox.
## Interactive Flow Visualization
## Step-by-Step Walkthrough
[[service|notification-api]] consumes [[command|PlaceOrderCommand]],
[[command|CompleteOrderCommand]], or [[command|CancelOrderCommand]] from Kafka partitioned by
Order ID.
A Redis-backed idempotency guard (24-hour TTL keyed by message ID) prevents duplicate sends on
Kafka redeliveries or worker retries. If the recipient email address is blank, processing ends
cleanly without calling SMTP.
[[service|notification-api]] renders the order email template into a MIME message and submits it
to [[service|sendgrid-api]] (or Mailpit locally) through a resilient SMTP pipeline. No
delivery-result callback is published back to [[domain|ordering]].
## Failure, Retry & Compensation Behavior
| Failure Point | System Behavior | Compensation / Recovery |
| :--------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Blank recipient email** | Handler returns immediately without calling SMTP | No error or retry; order state is unaffected |
| **Transient SMTP throttling or timeout** | MailKit resilience and worker cooldown retries execute | If retries exhaust, the command routes to `bookworm.{env}.notification.dead-letter-queue` |
| **Finance timeout reissue** | order-orchestration emits a new PlaceOrderCommand with a new message ID | Bypasses per-message-ID deduplication and may send a duplicate placement email |
:::note
**Stateless worker boundary:** [[service|notification-api]] owns no PostgreSQL database and no email outbox. SMTP acceptance confirms handoff to the mail provider, not final inbox delivery.
:::
## Participating Resources
- **Domains & Systems:** [[domain|platform]], [[domain|ordering]], [[system|notification-system]], [[system|sendgrid]]
- **Services:** [[service|order-orchestration]], [[service|notification-api]], [[service|sendgrid-api]]
- **Messages:** [[command|PlaceOrderCommand]], [[command|CompleteOrderCommand]], [[command|CancelOrderCommand]]
- **Channels:** `bookworm.{env}.finance.place-order`, `bookworm.{env}.finance.complete-order`, `bookworm.{env}.finance.cancel-order`, `bookworm.{env}.notification.dead-letter-queue`
- **Related Views:** [[flow|user-checkout]], [[flow|order-lifecycle]]
---
id: order-lifecycle
name: Order Lifecycle and Status Transitions
version: 1.0.0
summary: >-
Checkout creates a New Order owned by Ordering API, Finance coordinates
post-order cleanup and notifications, and explicit business operations move
the Order to Completed or Cancelled.
owners:
- commerce-fulfillment-team
diagrams:
- id: order-lifecycle
version: 1.0.0
badges:
- content: Business Process
backgroundColor: purple
textColor: purple
steps:
- id: customer
title: Customer submits checkout
actor:
name: Customer
next_step:
id: create-order
label: Submit basket to Ordering
- id: create-order
title: CreateOrder command
message:
id: CreateOrder
version: 1.0.0
next_step:
id: order-api
label: Validate and build New order
- id: order-api
title: Ordering API creates New order
summary: >-
Authenticates the buyer, resolves basket quantities and Catalog prices,
and writes the New order snapshot and event stream.
service:
id: order-api
version: 1.0.0
next_steps:
- id: order-db
label: Persist New order and projections
- id: finance-saga
label: Publish checkout event to Finance
- id: order-db
title: Order Database stores accepted order
summary: >-
Stores the authoritative Order record, event-sourced summary projections,
and transactional outbox messages.
container:
id: order-database
version: 1.0.0
next_steps:
- id: order-complete
label: Explicit completion transition
- id: order-cancel
label: Explicit cancellation transition
- id: finance-saga
title: Finance coordinates post-checkout work
summary: >-
Tracks post-checkout basket cleanup and awaits explicit Ordering status
events while managing bounded retry timeouts.
service:
id: order-orchestration
version: 1.0.0
next_steps:
- id: finance-complete
label: Await order completion event
- id: finance-cancel
label: Await order cancellation event
- id: order-complete
title: Order status changed to Complete
message:
id: OrderStatusChangedToCompleteIntegrationEvent
version: 1.0.0
next_step:
id: finance-complete
label: Deliver via ordering.order-status-change-to-complete
- id: order-cancel
title: Order status changed to Cancel
message:
id: OrderStatusChangedToCancelIntegrationEvent
version: 1.0.0
next_step:
id: finance-cancel
label: Deliver via ordering.order-status-change-to-cancel
- id: finance-complete
title: Finance handles order completion
summary: >-
Finalizes the orchestration and emits CompleteOrderCommand to notify the
customer.
service:
id: order-orchestration
version: 1.0.0
next_step:
id: complete-order-command
label: Publish CompleteOrderCommand
- id: complete-order-command
title: CompleteOrderCommand
message:
id: CompleteOrderCommand
version: 1.0.0
next_step:
id: notification-complete
label: Deliver via finance.complete-order
- id: finance-cancel
title: Finance handles order cancellation
summary: >-
Finalizes the orchestration and emits CancelOrderCommand to notify the
customer.
service:
id: order-orchestration
version: 1.0.0
next_step:
id: cancel-order-command
label: Publish CancelOrderCommand
- id: cancel-order-command
title: CancelOrderCommand
message:
id: CancelOrderCommand
version: 1.0.0
next_step:
id: notification-cancel
label: Deliver via finance.cancel-order
- id: notification-complete
title: Notification sends completion email
service:
id: notification-api
version: 1.0.0
- id: notification-cancel
title: Notification sends cancellation email
service:
id: notification-api
version: 1.0.0
---
## Trigger & Business Outcome
This lifecycle begins when a customer submits [[command|CreateOrder]] to create a purchase record and spans every authoritative state transition until the [[entity|order]] reaches a terminal **Completed** or **Cancelled** state. Success is confirmed when [[service|order-api]] commits the terminal status in [[container|order-database]], [[service|order-orchestration]] closes its coordination workflow, and [[service|notification-api]] delivers the corresponding status email.
## Interactive Flow Visualization
## Step-by-Step Walkthrough
[[service|order-api]] authenticates the buyer, resolves the persisted [[entity|basket]] and
[[domain|catalog]] prices, persists the **New** [[entity|order]] in
[[container|order-database]], and publishes [[event|UserCheckedOutIntegrationEvent]] via its
transactional outbox.
[[service|order-orchestration]] consumes [[event|UserCheckedOutIntegrationEvent]], coordinates
basket cleanup (detailed in [[flow|user-checkout]]), and remains active until an explicit
order-status event arrives or bounded retries exhaust.
When an authorized business operation invokes [[command|CompleteOrder]] or
[[command|CancelOrder]], [[service|order-api]] commits the irreversible terminal transition and
publishes [[event|OrderStatusChangedToCompleteIntegrationEvent]] or
[[event|OrderStatusChangedToCancelIntegrationEvent]].
[[service|order-orchestration]] consumes the status event, completes its workflow to stop any
pending timeout timers, and publishes [[command|CompleteOrderCommand]] or
[[command|CancelOrderCommand]] to [[service|notification-api]] for customer email delivery.
## Failure, Retry & Compensation Behavior
| Failure Point | System Behavior | Compensation / Recovery |
| :---------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Invalid transition on terminal order** | order-api rejects completion or cancellation once **Completed** or **Cancelled** | Terminal states are immutable; handle post-finalization exceptions through external compensating workflows |
| **Basket cleanup failure after checkout** | order-orchestration sends DeleteBasketFailedCommand | order-api soft-deletes the order record while preserving **New** business status |
| **Finance timeout exhaustion** | order-orchestration cancels its own workflow after three attempts | Sends CancelOrderCommand for email notification only; does not mutate order status in order-api |
| **Notification delivery failure** | notification-api retries with backoff, then dead-letters | Routed to `bookworm.{env}.notification.dead-letter-queue`; order status remains intact |
:::warning
**[[service|order-api]] is the sole authority for order business status.**
Neither [[service|order-orchestration]] nor [[service|notification-api]] can transition an [[entity|order]] to **Completed** or **Cancelled**. Always inspect [[diagram|order-lifecycle]] when distinguishing business cancellation from technical soft deletion or orchestration timeouts.
:::
## Participating Resources
- **Domains & Systems:** [[domain|ordering]], [[domain|shopping]], [[domain|platform]], [[system|order-system]], [[system|finance-system]], [[system|notification-system]]
- **Services:** [[service|order-api]], [[service|order-orchestration]], [[service|notification-api]]
- **Messages:** [[command|CreateOrder]], [[command|CompleteOrder]], [[command|CancelOrder]], [[event|UserCheckedOutIntegrationEvent]], [[event|OrderStatusChangedToCompleteIntegrationEvent]], [[event|OrderStatusChangedToCancelIntegrationEvent]], [[command|CompleteOrderCommand]], [[command|CancelOrderCommand]]
- **Channels & Stores:** `bookworm.{env}.ordering.order-status-change-to-complete`, `bookworm.{env}.ordering.order-status-change-to-cancel`, `bookworm.{env}.finance.complete-order`, `bookworm.{env}.finance.cancel-order`, [[container|order-database]]
- **Related Views:** [[diagram|order-lifecycle]], [[flow|user-checkout]], [[flow|notification-delivery]]
---
id: product-ingestion
name: Product Ingestion
version: 1.0.0
summary: >-
Catalog API persists product changes in PostgreSQL; Scheduler triggers Catalog
Ingestion over Kafka every five minutes to refresh or remove Qdrant vectors and
acknowledge unchanged revisions.
owners:
- catalog-experience-team
badges:
- content: Background Processing
backgroundColor: blue
textColor: blue
steps:
- id: maintain-product
title: Catalog administrator updates products
actor:
name: Catalog Administrator
next_step:
id: catalog-api
label: Create, update, or soft-delete catalog entities
- id: catalog-api
title: Catalog API validates and saves changes
summary: >-
Saves validated book, author, category, and publisher changes without
blocking API requests on AI embedding generation.
service:
id: catalog-api
version: 1.0.0
next_step:
id: persist-and-enqueue
label: Commit catalog changes
- id: persist-and-enqueue
title: Catalog Database - persist and queue revision
summary: >-
Database triggers atomically coalesce affected book IDs into the pending
vector queue with a fresh revision token. Repeated edits replace the
queued revision so only the latest state is indexed.
container:
id: catalog-database
version: 1.0.0
next_step:
id: scheduler
label: Queued work awaits scheduled batch trigger
- id: scheduler
title: Scheduler triggers periodic vector batch
summary: >-
Fires every five minutes in UTC independently of API traffic, disallowing
concurrent job runs and recovering misfires.
service:
id: scheduler-service
version: 1.0.0
next_step:
id: request-vector-batch
label: Publish batch trigger event
- id: request-vector-batch
title: ProcessVectorBatchIntegrationEvent
message:
id: ProcessVectorBatchIntegrationEvent
version: 1.0.0
next_step:
id: batch-channel
label: Publish to scheduler.process-vector-batch
- id: batch-channel
title: Vector batch trigger channel
channel:
id: scheduler.process-vector-batch
version: 1.0.0
next_step:
id: read-pending-batch
label: Trigger Catalog Ingestion worker
- id: read-pending-batch
title: Catalog Database - acquire lock and read batch
summary: >-
Attempts an exclusive PostgreSQL advisory lock and reads up to 200
queued revisions ordered by update time. Soft-deleted or missing books
yield null content for vector removal.
container:
id: catalog-database
version: 1.0.0
next_steps:
- id: process-batch
label: Lock acquired and pending work exists
- id: no-work
label: Lock busy or queue empty
- id: processing-failed
label: Database operation fails
- id: no-work
title: No batch processed
summary: >-
Exits cleanly without modifying Qdrant and releases the advisory lock if
held. A busy lock leaves pending work for the next scheduled run.
custom:
title: No work this invocation
type: Outcome
icon: CheckCircleIcon
color: gray
- id: process-batch
title: Catalog Ingestion - generate embeddings
summary: >-
Ensures the Qdrant collection exists and generates embeddings for all
active books in the batch. Incomplete embedding responses fail the batch
before any vector writes occur.
service:
id: catalog-ingestion
version: 1.0.0
next_steps:
- id: upsert-vector
label: Active books with embeddings
- id: delete-vector
label: Missing or soft-deleted books
- id: processing-failed
label: Embedding generation fails
- id: upsert-vector
title: Catalog Vector - upsert active book vectors
summary: >-
Upserts searchable book text and embeddings keyed by book UUID into
Qdrant.
container:
id: catalog-vector
version: 1.0.0
next_steps:
- id: acknowledge-batch
label: All vector operations succeed
- id: processing-failed
label: Vector upsert fails
- id: delete-vector
title: Catalog Vector - remove deleted book vectors
summary: Deletes Qdrant records keyed by missing or soft-deleted book UUIDs.
container:
id: catalog-vector
version: 1.0.0
next_steps:
- id: acknowledge-batch
label: All vector operations succeed
- id: processing-failed
label: Vector deletion fails
- id: acknowledge-batch
title: Catalog Database - acknowledge unchanged revisions
summary: >-
Deletes only pending rows whose book ID and revision token still match
the processed snapshot. Newer concurrent edits remain queued for the next
cycle.
container:
id: catalog-database
version: 1.0.0
next_steps:
- id: complete-batch
label: Revision-checked acknowledgements complete
- id: processing-failed
label: Acknowledgement fails; rows survive
- id: complete-batch
title: Catalog Ingestion - complete batch
summary: >-
Releases the advisory lock. Concurrent edits and queues exceeding 200
items await the next scheduled batch.
service:
id: catalog-ingestion
version: 1.0.0
- id: processing-failed
title: Preserve pending work after failure
summary: >-
Releases the advisory lock and leaves unacknowledged rows in PostgreSQL so
the next five-minute trigger safely retries the batch.
custom:
title: Processing failed
type: Failure
icon: ExclamationTriangleIcon
color: red
next_step:
id: scheduler
label: Retry on next scheduled invocation
---
## Trigger & Business Outcome
This workflow begins when a catalog administrator creates, updates, or soft-deletes a [[entity|book]], [[entity|author]], [[entity|category]], or [[entity|publisher]] through [[service|catalog-api]]. Success is confirmed when [[service|catalog-ingestion]] refreshes or removes the corresponding embeddings in [[container|catalog-vector]] and acknowledges only unchanged revision rows in [[container|catalog-database]], keeping semantic search eventually consistent without slowing catalog writes.
## Interactive Flow Visualization
## Step-by-Step Walkthrough
[[service|catalog-api]] commits validated catalog changes to [[container|catalog-database]]. In
the same transaction, database triggers atomically coalesce each affected book ID into the
pending vector queue with a new revision token, collapsing rapid edits into one indexing pass.
Every five minutes in UTC, [[service|scheduler-service]] publishes
[[event|ProcessVectorBatchIntegrationEvent]] via its transactional outbox to
[[channel|scheduler.process-vector-batch]].
[[service|catalog-ingestion]] acquires an exclusive PostgreSQL advisory lock so only one worker
processes the queue at a time, then reads up to 200 queued revisions with current book metadata.
[[service|catalog-ingestion]] generates batch embeddings for active books, upserts active
records into [[container|catalog-vector]], and deletes vectors for missing or soft-deleted
books.
Only after all vector operations succeed, [[service|catalog-ingestion]] deletes pending rows
whose book ID and revision token match the processed snapshot, preserving any concurrent edits
made during processing.
## Failure, Retry & Compensation Behavior
| Failure Point | System Behavior | Compensation / Recovery |
| :------------------------------------------ | :--------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Advisory lock already held** | Worker exits cleanly without touching catalog-vector | Pending rows remain intact for the next five-minute trigger |
| **Incomplete AI embedding response** | Batch aborts before any vector writes | Advisory lock is released; entire batch is retried on the next scheduled run |
| **Vector store or acknowledgement failure** | Error propagates and lock is released | Unacknowledged rows survive in catalog-database; vector writes are idempotent by book UUID |
:::note
**Eventual consistency window:** Semantic search results lag behind catalog writes by up to five minutes (plus additional cycles if the queue exceeds 200 books). Authoritative book details and prices are always hydrated from [[container|catalog-database]] at query time.
:::
## Participating Resources
- **Domains & Systems:** [[domain|catalog]], [[domain|platform]], [[system|product-catalog-system]], [[system|scheduler-system]]
- **Services:** [[service|catalog-api]], [[service|scheduler-service]], [[service|catalog-ingestion]]
- **Messages & Channels:** [[event|ProcessVectorBatchIntegrationEvent]], [[channel|scheduler.process-vector-batch]]
- **Data Stores:** [[container|catalog-database]], [[container|catalog-vector]]
---
id: user-checkout
name: User Checkout
version: 1.0.0
summary: >-
An authenticated customer checks out a persisted basket through Ordering API;
Finance coordinates asynchronous basket cleanup and Notification submits the
order email over SMTP with independent outcomes and bounded retries.
owners:
- commerce-fulfillment-team
diagrams:
- id: checkout-interaction
version: 1.0.0
badges:
- content: Business Process
backgroundColor: purple
textColor: purple
steps:
- id: customer
title: Customer starts checkout
actor:
name: Customer
next_step:
id: authenticate
label: Sign in to Storefront
- id: authenticate
title: OAuth API - Entra ID sign-in
summary: >-
Storefront authenticates the customer via Microsoft Entra ID with PKCE and
customer scopes. Protected APIs derive buyer identity, full name, and
email from verified token claims.
service:
id: oauth-api
version: 1.0.0
next_step:
id: review-basket
label: Authenticated customer reviews basket
- id: review-basket
title: Basket API - load persisted basket
summary: >-
Commerce loads the customer-scoped basket and displays items enriched
with Catalog details. Edits must be saved to affect checkout.
service:
id: basket-api
version: 1.0.0
next_step:
id: submit-checkout
label: Customer confirms checkout
- id: submit-checkout
title: Create order
summary: >-
Commerce submits the checkout command through the gateway with a unique
request key for idempotency. Ordering reads the customer's persisted
basket rather than trusting client-supplied totals.
message:
id: CreateOrder
version: 1.0.0
next_step: create-order
- id: create-order
title: Ordering API - validate and build order
summary: >-
Enforces customer authorization, per-user rate limiting, and request
idempotency before reading the persisted basket and current prices.
service:
id: order-api
version: 1.0.0
next_step: read-checkout-basket
- id: read-checkout-basket
title: Get current basket
message:
id: GetBasketGrpc
version: 1.0.0
next_step: basket-checkout-read
- id: basket-checkout-read
title: Basket API - return persisted quantities
summary: >-
Returns the authoritative item quantities stored in the basket cache.
Unsaved browser edits are not included.
service:
id: basket-api
version: 1.0.0
next_step: read-checkout-books
- id: read-checkout-books
title: Resolve current catalog books
message:
id: GetBooksGrpc
version: 1.0.0
next_step: catalog-pricing
- id: catalog-pricing
title: Catalog API - provide authoritative prices
summary: >-
Resolves each book ID and supplies the sale price when active, otherwise
the regular price. A missing book aborts order creation.
service:
id: catalog-api
version: 1.0.0
next_step: persist-order
- id: persist-order
title: Order Database - save New order snapshot
summary: >-
Under a per-buyer distributed lock, Ordering persists the New order and
item-price snapshot and atomically queues the checkout integration event
in the transactional outbox.
container:
id: order-database
version: 1.0.0
next_steps:
- id: checkout-confirmation
label: Confirm order acceptance immediately
- id: checked-out
label: Publish checkout event via outbox
- id: checkout-confirmation
title: Customer receives checkout confirmation
summary: >-
Commerce displays the confirmation page with the Order ID. This confirms
order acceptance only—not basket deletion, payment settlement, or email
delivery.
actor:
name: Customer
- id: checked-out
message:
id: UserCheckedOutIntegrationEvent
version: 1.0.0
next_step:
id: start-finance-saga
label: Deliver via ordering.user-checked-out
- id: start-finance-saga
title: Finance - start tracked orchestration
summary: >-
Starts a durable orchestration correlated by Order ID, publishes the
placement command, and schedules a 30-minute timeout. Finance coordinates
messages and does not process card payments or own order status.
service:
id: order-orchestration
version: 1.0.0
next_steps:
- id: place-order
label: Request basket cleanup and order email
- id: saga-timeout
label: Schedule 30-minute orchestration timeout
- id: place-order
message:
id: PlaceOrderCommand
version: 1.0.0
next_step: placement-channel
- id: placement-channel
title: Finance placement channel
summary: >-
Basket API and Notification consume the same command independently. Email
submission does not wait for basket cleanup, and retries can repeat both
consumers' work.
channel:
id: bookworm.{env}.finance.place-order
version: 1.0.0
next_steps:
- id: delete-basket
label: Basket cleanup consumer
- id: prepare-email
label: Order email consumer
- id: delete-basket
title: Basket API - delete submitted basket
summary: >-
Deletes the customer's basket from Redis. Returns a completion event on
success or a failure event if deletion returns false.
service:
id: basket-api
version: 1.0.0
next_steps:
- id: basket-deleted
label: Basket deleted
- id: basket-deletion-failed
label: Deletion returned false
- id: basket-deleted
message:
id: BasketDeletedCompleteIntegrationEvent
version: 1.0.0
next_step:
id: finance-cleanup-success
label: Deliver via basket.delete-complete
- id: finance-cleanup-success
title: Finance - forward cleanup completion
summary: >-
Records cleanup progress and notifies Ordering. Orchestration remains
active for explicit order completion, cancellation, or timeout.
service:
id: order-orchestration
version: 1.0.0
next_step: report-cleanup-success
- id: report-cleanup-success
message:
id: DeleteBasketCompleteCommand
version: 1.0.0
next_step:
id: ordering-cleanup-success
label: Deliver via finance.delete-basket-complete
- id: ordering-cleanup-success
title: Ordering API - log basket cleanup
summary: >-
Logs the cleanup completion for observability without changing the
order's New business status.
service:
id: order-api
version: 1.0.0
- id: basket-deletion-failed
message:
id: BasketDeletedFailedIntegrationEvent
version: 1.0.0
next_step:
id: finance-cleanup-failure
label: Deliver via basket.delete-failed
- id: finance-cleanup-failure
title: Finance - finalize failed cleanup
summary: >-
Marks the orchestration as failed, ends coordination, and instructs
Ordering to soft-delete the order. Does not request a cancellation email.
service:
id: order-orchestration
version: 1.0.0
next_step: report-cleanup-failure
- id: report-cleanup-failure
message:
id: DeleteBasketFailedCommand
version: 1.0.0
next_step:
id: ordering-cleanup-failure
label: Deliver via finance.delete-basket-failed
- id: ordering-cleanup-failure
title: Ordering API - soft-delete order
summary: >-
Marks the order as soft-deleted while preserving its New business status
and without emitting an order-cancellation event.
service:
id: order-api
version: 1.0.0
- id: prepare-email
title: Notification - check idempotency and render email
summary: >-
Applies a 24-hour Redis idempotency guard keyed by message ID, skips
blank recipient addresses, and renders the order email template.
service:
id: notification-api
version: 1.0.0
next_steps:
- id: submit-email
label: Valid recipient and template rendered
- id: skip-email
label: Missing recipient email
- id: skip-email
title: Skip email delivery
summary: >-
Returns without rendering or sending email. Does not affect the accepted
order or basket cleanup.
custom:
title: Email skipped
type: Outcome
icon: CheckCircleIcon
color: gray
- id: submit-email
title: SendGrid - SMTP submission
summary: >-
Submits the MIME message over SMTP with MailKit resilience (Mailpit in
local development, SendGrid in Azure). SMTP acceptance confirms provider
handoff, not inbox delivery.
service:
id: sendgrid-api
version: 1.0.0
next_steps:
- id: email-submitted
label: Provider accepted message
- id: email-failed
label: Submission failed after retries
- id: email-submitted
title: Email submitted to provider
summary: >-
Notification emits no delivery-result callback and never mutates order
status or Finance orchestration state.
custom:
title: Email submitted
type: Outcome
icon: CheckCircleIcon
color: green
- id: email-failed
title: Notification dead-letter queue
summary: >-
Transient errors exhaust Wolverine retries and route the command to the
notification dead-letter queue for operator inspection.
channel:
id: bookworm.{env}.notification.dead-letter-queue
version: 1.0.0
- id: saga-timeout
title: Finance - evaluate 30-minute timeout
summary: >-
Increments the retry counter while orchestration remains active. Up to
two reissues are allowed (three total attempts) before exhaustion.
service:
id: order-orchestration
version: 1.0.0
next_steps:
- id: retry-placement
label: Retry count below maximum attempts
- id: timeout-exhausted
label: Retry limit reached
- id: retry-placement
title: Finance - reissue placement command
summary: >-
Reissues the shared placement command with a new message ID and schedules
the next 30-minute timeout.
service:
id: order-orchestration
version: 1.0.0
next_steps:
- id: place-order
label: Reissue PlaceOrderCommand
- id: saga-timeout
label: Schedule next timeout
- id: timeout-exhausted
title: Finance - cancel orchestration only
summary: >-
Marks the orchestration cancelled when retries exhaust. Emits a
cancellation email command if contact details are present, without
cancelling the order in Ordering.
service:
id: order-orchestration
version: 1.0.0
next_steps:
- id: request-cancellation-email
label: Name and email present
- id: saga-ended-without-email
label: Contact details absent
- id: request-cancellation-email
message:
id: CancelOrderCommand
version: 1.0.0
next_step:
id: prepare-email
label: Deliver via finance.cancel-order
- id: saga-ended-without-email
title: Orchestration ended without email
summary: >-
Retry exhaustion ends Finance coordination without changing the order's
business status.
custom:
title: Orchestration ended
type: Outcome
icon: ExclamationTriangleIcon
color: orange
---
## Trigger & Business Outcome
This flow is triggered when an authenticated customer confirms checkout in the Commerce storefront to convert their persisted shopping basket into an immutable purchase snapshot. Success is confirmed when [[service|order-api]] persists a **New** [[entity|order]] in [[container|order-database]] and returns immediate confirmation, while [[service|order-orchestration]] asynchronously coordinates basket deletion in [[service|basket-api]] and order email submission via [[service|notification-api]].
## Interactive Flow Visualization
## Step-by-Step Walkthrough
The customer signs in with [[system|identity-provider]] ([[service|oauth-api]]) and reviews
their basket in Commerce, which loads customer-scoped items from [[service|basket-api]]. Only
saved basket quantities participate in checkout.
[[service|order-api]] handles [[command|CreateOrder]] with request-level idempotency and
per-user rate limiting. It fetches persisted quantities via [[query|GetBasketGrpc]] from
[[service|basket-api]] and authoritative prices via [[query|GetBooksGrpc]] from
[[service|catalog-api]] (preferring sale price when active). Under a per-buyer distributed lock,
it persists the **New** [[entity|order]] in [[container|order-database]], queues
[[event|UserCheckedOutIntegrationEvent]] in its transactional outbox, and confirms acceptance
immediately.
[[service|order-orchestration]] consumes [[event|UserCheckedOutIntegrationEvent]] from{" "}
`bookworm.{env}.ordering.user-checked-out`
, starts a tracked orchestration correlated by Order ID, publishes [[command|PlaceOrderCommand]]
to{" "}
`bookworm.{env}.finance.place-order`
, and schedules a 30-minute timeout.
[[service|basket-api]] and [[service|notification-api]] consume [[command|PlaceOrderCommand]] in
parallel. [[service|basket-api]] deletes the basket from [[container|basket-database]] and
reports either [[event|BasketDeletedCompleteIntegrationEvent]] or
[[event|BasketDeletedFailedIntegrationEvent]]. Meanwhile, [[service|notification-api]] applies a
24-hour Redis idempotency guard, renders the order email template, and submits it over SMTP to
[[service|sendgrid-api]] (or Mailpit locally).
While orchestration remains active, each 30-minute timeout reissues
[[command|PlaceOrderCommand]] up to two times (three total attempts). When the retry limit is
reached, [[service|order-orchestration]] cancels its own orchestration and—if contact details
are present—publishes [[command|CancelOrderCommand]] to [[service|notification-api]] without
cancelling the [[entity|order]] in [[service|order-api]].
## Failure, Retry & Compensation Behavior
| Failure Point | System Behavior | Compensation / Recovery |
| :--------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Missing catalog book or gRPC timeout** | order-api aborts order creation before committing | Customer remains on checkout; no order or outbox event is created |
| **Basket deletion returns false** | basket-api emits BasketDeletedFailedIntegrationEvent | order-orchestration finalizes as failed and sends DeleteBasketFailedCommand; order-api soft-deletes the order while preserving **New** status |
| **Basket repository exception** | Exception propagates to message-broker retries | Retried automatically; dead-lettered to `bookworm.{env}.basket.dead-letter-queue` if exhausted |
| **SMTP submission failure** | MailKit resilience and worker retries execute with backoff | Exhausted failures route to `bookworm.{env}.notification.dead-letter-queue`; order status is unaffected |
| **Orchestration timeout exhaustion** | order-orchestration reaches its three-attempt cap | Cancels orchestration only and requests a cancellation email via CancelOrderCommand if contact details exist |
:::warning
**Confirmation means order acceptance—not basket deletion, payment settlement, or email delivery.**
- Because [[service|basket-api]] and [[service|notification-api]] consume [[command|PlaceOrderCommand]] independently, a placement email may be submitted even if basket cleanup later fails.
- Reissued timeout commands carry new message IDs, which bypass per-message-ID deduplication in [[service|notification-api]] and can result in a duplicate email.
- Always inspect both order business status and soft-deletion state in [[container|order-database]] before replaying failed checkout messages.
:::
## Participating Resources
- **Domains & Systems:** [[domain|shopping]], [[domain|ordering]], [[domain|catalog]], [[domain|platform]], [[system|identity-provider]], [[system|sendgrid]]
- **Services:** [[service|oauth-api]], [[service|basket-api]], [[service|catalog-api]], [[service|order-api]], [[service|order-orchestration]], [[service|notification-api]], [[service|sendgrid-api]]
- **Messages:** [[command|CreateOrder]], [[query|GetBasketGrpc]], [[query|GetBooksGrpc]], [[event|UserCheckedOutIntegrationEvent]], [[command|PlaceOrderCommand]], [[event|BasketDeletedCompleteIntegrationEvent]], [[command|DeleteBasketCompleteCommand]], [[event|BasketDeletedFailedIntegrationEvent]], [[command|DeleteBasketFailedCommand]], [[command|CancelOrderCommand]]
- **Channels & Stores:** `bookworm.{env}.ordering.user-checked-out`, `bookworm.{env}.finance.place-order`, `bookworm.{env}.notification.dead-letter-queue`, [[container|basket-database]], [[container|order-database]]
- **Related Views:** [[diagram|checkout-interaction]], [[flow|order-lifecycle]], [[flow|notification-delivery]]
---
dictionary:
- id: Buyer
name: Buyer
summary: The named person associated with Orders.
description: A Buyer has a name, address, and collection of Orders.
icon: User
- id: Address
name: Address
summary: A Buyer's street, city, and province information.
description: An Address is the delivery location held by a Buyer.
icon: MapPin
- id: Order
name: Order
summary: A purchase record containing one or more Order items.
description: |
An Order belongs to a Buyer and moves from New to either Completed or
Cancelled.
icon: ClipboardList
- id: Order Item
name: Order Item
summary: A book identifier, quantity, and price on an Order.
description: |
An Order item has a positive quantity and non-negative price. Its line
total is price multiplied by quantity.
icon: ListOrdered
- id: Order Total
name: Order Total
summary: The sum of all Order item line totals.
description: The Order total is calculated from the items recorded on the Order.
icon: Calculator
- id: New
name: New
summary: The initial status of an Order.
description: An Order can transition to Completed or Cancelled from New.
icon: CircleDashed
- id: Completed
name: Completed
summary: A terminal status for a successfully completed Order.
description: Completed is reached from New when the Order is completed.
icon: CircleCheck
- id: Cancelled
name: Cancelled
summary: A terminal status for an Order that will not complete.
description: Cancelled is reached from New when the Order is cancelled.
icon: CircleX
---
## 1. Context & Problem
Order management touches customer identity, delivery locations, line-item pricing, financial totals, and lifecycle states. Without a shared vocabulary across business analysts, product managers, solution architects, and developers, terms like "item", "total", or "cancelled" can easily be interpreted differently across storefront, checkout, and fulfillment discussions.
This ubiquitous language defines the core concepts and lifecycle rules for BookWorm's Ordering subdomain.
## 2. Business Value
- **Aligned requirements and design**: Gives business and technical stakeholders a single, unambiguous definition for buyers, orders, line items, totals, and lifecycle states.
- **Consistent financial rules**: Makes explicit that line totals and order totals are derived strictly from positive item quantities and non-negative unit prices.
- **Clear lifecycle governance**: Establishes which order states are active versus terminal so workflows, customer communications, and reports stay consistent.
## 3. How It Works
The Ordering vocabulary is organized around customer identity, purchase structure, and lifecycle state:
- **Buyer & Address**: A **Buyer** is the named person associated with one or more orders and holds a delivery **Address** containing street, city, and province details.
- **Order, Order Item & Order Total**: An **Order** is a purchase record belonging to a buyer and containing one or more **Order Items**. Each **Order Item** captures a book reference, a positive quantity, and a non-negative price, with its line total equal to price multiplied by quantity. The **Order Total** is the sum of all order item line totals on that order.
- **Lifecycle States (New, Completed, Cancelled)**: Every order begins in **New** and transitions from **New** to either **Completed** (successfully finished) or **Cancelled** (will not complete). Both **Completed** and **Cancelled** are terminal states.
## 4. Trade-offs & Lessons Learned
- **Strict terminal states**: Treating **Completed** and **Cancelled** as final outcomes prevents ambiguous state reversals in reporting and downstream workflows, meaning any post-completion adjustments must be handled as separate processes rather than reopening a closed order.
- **Derived totals over manual overrides**: Computing **Order Total** strictly from recorded **Order Item** quantities and prices preserves arithmetic integrity, while requiring future discounts or fees to be modeled as explicit items or adjustments if introduced later.
## 5. Technical Reference
| Dictionary ID | Summary | Domain & Invariant Notes |
| ------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------- |
| `Buyer` | The named person associated with Orders. | Has a name, an `Address`, and a collection of `Order` records. |
| `Address` | A Buyer's street, city, and province information. | Delivery location held by a `Buyer`. |
| `Order` | A purchase record containing one or more Order items. | Belongs to a `Buyer`; transitions from `New` to `Completed` or `Cancelled`. |
| `Order Item` | A book identifier, quantity, and price on an Order. | Positive quantity and non-negative price; line total equals `price * quantity`. |
| `Order Total` | The sum of all Order item line totals. | Derived from the `Order Item` records on the `Order`. |
| `New` | The initial status of an Order. | Starting state; can transition to `Completed` or `Cancelled`. |
| `Completed` | A terminal status for a successfully completed Order. | Terminal state reached from `New` when the Order is completed. |
| `Cancelled` | A terminal status for an Order that will not complete. | Terminal state reached from `New` when the Order is cancelled. |
---
dictionary:
- id: Feedback
name: Feedback
summary: A customer's rating and optional comment about a Book.
description: |
Feedback is the service's individual record and contains a Book reference,
rating, optional name, and optional comment.
icon: MessageSquare
- id: Review
name: Review
summary: The customer-facing name for a Feedback submission.
description: |
Review and Feedback refer to the same individual submission. The service
model uses the name Feedback.
icon: MessageCircle
- id: Rating
name: Rating
summary: An integer score from 0 through 5 on a Feedback submission.
description: A Rating belongs to one Feedback submission.
icon: Star
- id: Comment
name: Comment
summary: Optional written text supplied with Feedback.
description: A Comment records the customer's written response about a Book.
icon: MessageSquareText
- id: Book Reference
name: Book Reference
summary: The identifier of the Book that Feedback concerns.
description: |
Reviews references a Book by identifier; Catalog owns and defines the
Book itself.
icon: BookOpen
- id: Rating Summary
name: Rating Summary
summary: Catalog's aggregate average and review count for a Book.
description: |
A Rating summary is not an individual Review. It is updated from feedback
changes for use in Catalog discovery.
icon: BarChart3
---
## 1. Context & Problem
Across product discussions, storefront design, and service implementation, teams often use words like "review," "feedback," "rating," and "rating summary" interchangeably. Without shared definitions, stakeholders can confuse an individual customer submission with a book's overall star summary, or assume Reviews owns book details that actually belong to Catalog. This glossary establishes one unambiguous vocabulary for the Reviews subdomain.
## 2. Business Value
- **Shared cross-role alignment**: Business analysts, product managers, architects, and developers speak the same language when writing requirements, designing UI screens, and reviewing domain behavior.
- **Clear domain boundaries**: Explicitly distinguishing individual submissions from Catalog-owned book definitions and rating aggregates prevents accidental cross-domain coupling.
- **Fewer requirement ambiguities**: Documenting rules up front—such as the allowed rating scale and which fields are optional—prevents costly rework later.
## 3. How It Works
The Reviews vocabulary organizes customer opinions into six connected concepts:
- **Feedback and Review**: Both terms refer to the same individual customer submission about a book. Storefront experiences typically present this to shoppers as a "Review," while the underlying Reviews domain model calls it "Feedback."
- **Rating and Comment**: Each Feedback submission contains a numeric Rating from 0 through 5 and may optionally include a reviewer name and a written Comment expressing the customer's thoughts.
- **Book Reference**: Instead of copying title, author, or price details, each Feedback entry holds only a reference to the Book managed by Catalog.
- **Rating Summary**: Separate from any individual Review, a Rating Summary is Catalog's aggregated average rating and total review count for a book, updated as feedback changes so shoppers can filter and discover titles in Catalog.
## 4. Trade-offs & Lessons Learned
- **Bridging UI and domain naming**: Rather than forcing customer-facing copy to adopt internal naming or renaming existing domain models, the glossary explicitly maps "Review" and "Feedback" as synonyms for the same concept.
- **Reference-by-identifier boundary**: Storing only a Book Reference keeps Reviews decoupled from Catalog metadata changes, though storefront displays and Catalog discovery aggregates must coordinate across service boundaries.
## 5. Technical Reference
| Term ID | Domain Owner | Required / Value Rules | Domain Notes |
| ---------------- | ------------ | ---------------------------------------- | ----------------------------------------------------------------------- |
| `Feedback` | Reviews | Individual submission record | Contains `Book Reference`, `Rating`, optional name, optional `Comment`. |
| `Review` | Reviews | Synonym for `Feedback` | Customer-facing name; service model uses `Feedback`. |
| `Rating` | Reviews | Integer from `0` through `5` | Belongs to one `Feedback` submission. |
| `Comment` | Reviews | Optional written text | Records the customer's written response about a `Book`. |
| `Book Reference` | Reviews | Book identifier referencing Catalog | Reviews references a `Book` by ID; Catalog owns and defines `Book`. |
| `Rating Summary` | Catalog | Aggregate average score and review count | Updated from feedback changes for Catalog discovery; not a `Review`. |
---
dictionary:
- id: Book
name: Book
summary: A listed title available for discovery.
description: |
A Book has a name, description, image, price, availability status,
category, publisher, and author associations.
icon: BookOpen
- id: Author
name: Author
summary: A named contributor associated with one or more Books.
description: An Author can be associated with multiple Catalog Books.
icon: UserPen
- id: Publisher
name: Publisher
summary: The publishing organization associated with a Book.
description: A Publisher is Catalog metadata for a Book.
icon: Building2
- id: Category
name: Category
summary: A classification used to group Books.
description: Categories support browsing and book discovery.
icon: Tags
- id: Price
name: Price
summary: A Book's original price and optional discount price.
description: |
A discount price cannot be negative or exceed the original price. It is
not a separate product.
icon: BadgeDollarSign
- id: Availability
name: Availability
summary: Whether a Book is in stock or out of stock.
description: |
Availability describes the Catalog listing. It is not a reservation held
by a Basket.
icon: PackageCheck
- id: Rating Summary
name: Rating Summary
summary: The average rating and review count shown for a Book.
description: |
The rating summary is an aggregate projection of Reviews feedback, not an
individual Feedback submission.
icon: Star
---
## 1. Context & Problem
In an online bookstore, teams across product management, shopping baskets, order fulfillment, and customer reviews frequently use everyday words like "book," "price," "availability," and "rating." Without shared definitions, those words quietly take on conflicting meanings—for example, treating a catalog listing's availability as a basket stock reservation, modeling a discount as a separate item, or confusing an aggregate rating summary with an individual customer review.
The Catalog ubiquitous language establishes a single, unambiguous vocabulary for Catalog concepts so business stakeholders, analysts, architects, and engineers communicate using the exact same terms and boundaries.
## 2. Business Value
- **Cross-functional clarity:** Product managers, business analysts, architects, and developers align on one shared meaning when writing requirements, designing journeys, and reviewing domain boundaries.
- **Fewer domain misunderstandings:** Explicit distinctions prevent costly defects such as invalid discount pricing, conflating browsing availability with checkout holds, or duplicating review ownership.
- **Safer team autonomy:** Neighboring domains can rely on Catalog concepts confidently without leaking internal assumptions across domain borders.
- **Faster onboarding:** New contributors can immediately see what Catalog owns and how its terms relate to adjacent business areas.
## 3. How It Works
The Catalog vocabulary groups its core terms around three business responsibilities:
- **Product identity and classification:** A **Book** is the listed title available for discovery, described by its name, description, image, and associations with **Author** (a named contributor who may be linked to multiple books), **Publisher** (the publishing organization), and **Category** (classifications used for browsing and discovery).
- **Commercial proposition:** **Price** represents a book's original price alongside an optional discount price—never as a separate product, and always constrained so a discount cannot be negative or exceed the original price. **Availability** indicates whether a catalog listing is in stock or out of stock, explicitly separate from any reservation held in a customer's shopping basket.
- **Reputation display:** **Rating Summary** captures the average rating and review count shown for a book. It is an aggregated summary derived from customer reviews rather than an individual feedback submission.
Teams apply these exact definitions in workshops, acceptance criteria, and cross-domain conversations whenever Catalog concepts are referenced.
## 4. Trade-offs & Lessons Learned
- **Precision over informal shorthand:** Separating **Availability** from basket reservations and **Rating Summary** from individual feedback introduces stricter wording, but eliminates subtle ambiguities during checkout and review integrations.
- **Discounts as part of Price:** Keeping an optional discount price inside **Price** rather than creating separate promotional products simplifies catalog browsing, while requiring strict validation to block negative or inflated discount values.
- **Ongoing glossary stewardship:** Domain terms only stay useful when kept current; whenever a Catalog business rule evolves, the shared dictionary must be updated alongside it.
## 5. Technical Reference
### Catalog Dictionary Terms
The YAML `dictionary` frontmatter above defines the authoritative Catalog glossary entries rendered by EventCatalog:
| Term (`id`) | Summary | Domain Rules & Boundaries | Icon |
| ---------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------- | ----------------- |
| `Book` | A listed title available for discovery. | Has name, description, image, price, availability status, category, publisher, and author associations. | `BookOpen` |
| `Author` | A named contributor associated with one or more Books. | An Author can be associated with multiple Catalog Books. | `UserPen` |
| `Publisher` | The publishing organization associated with a Book. | Catalog metadata for a Book. | `Building2` |
| `Category` | A classification used to group Books. | Supports browsing and book discovery. | `Tags` |
| `Price` | A Book's original price and optional discount price. | Discount price cannot be negative or exceed the original price; not a separate product. | `BadgeDollarSign` |
| `Availability` | Whether a Book is in stock or out of stock. | Describes the Catalog listing; not a reservation held by a Basket. | `PackageCheck` |
| `Rating Summary` | The average rating and review count shown for a Book. | Aggregate projection of Reviews feedback, not an individual Feedback submission. | `Star` |
---
dictionary:
- id: Book
name: Book
summary: A title represented in the bookstore catalog.
description: |
A Book has descriptive, pricing, availability, and classification data.
Catalog owns the Book, while other contexts refer to it by identifier.
icon: BookOpen
- id: Basket
name: Basket
summary: A customer's changeable collection of books before purchase.
description: |
A Basket contains book identifiers and quantities. It is mutable shopping
intent and is not an Order or an inventory reservation.
icon: ShoppingBasket
- id: Buyer
name: Buyer
summary: The person associated with an Order in Ordering.
description: |
A Buyer has a name and delivery address. A Buyer is not automatically the
same identifier used to address a customer's Basket.
icon: User
- id: Order
name: Order
summary: The durable purchase record managed by Ordering.
description: |
An Order contains Order items and has a lifecycle status. It is distinct
from the mutable Basket that precedes it.
icon: ClipboardList
- id: Order Item
name: Order Item
summary: One book, quantity, and price recorded on an Order.
description: |
An Order item records the book identifier, quantity, and price used for
that purchase line. It is not a live copy of the current Catalog price.
icon: ListOrdered
- id: Feedback
name: Feedback
summary: A customer's rating and optional comment about a Book.
description: |
Reviews owns individual Feedback submissions. Catalog maintains an
aggregate rating summary rather than the individual Feedback records.
icon: MessageSquare
- id: Checkout
name: Checkout
summary: The cross-context process that starts order placement.
description: |
Checkout coordinates the transition from a checked-out Basket into the
order workflow. It is a process, not another name for an Order.
icon: CreditCard
- id: Chat Request
name: Chat Request
summary: A customer question handled by Conversational agents.
description: |
Conversational agents route or answer a request. The request may discuss
a Book or Order, but those records remain owned by their contexts.
icon: MessageCircle
- id: Idempotency Guard
name: Idempotency Guard
summary: Time-bounded deduplication guard for incoming notification commands.
description: |
Platform tracks processed notification message identifiers for 24 hours so
duplicate deliveries do not trigger duplicate customer emails.
icon: ShieldCheck
- id: Dead-Letter Queue
name: Dead-Letter Queue
summary: Message channel holding commands that exhausted delivery retries.
description: |
Exhausted message failures route to a service's dead-letter queue
for operator inspection and replay.
icon: AlertTriangle
- id: Email Template
name: Email Template
summary: Responsive email markup compiled to HTML at runtime for order emails.
description: |
Platform compiles responsive email templates into HTML messages before
submitting them through the external email relay.
icon: FileCode
- id: Vector Batch Job
name: Vector Batch Job
summary: Scheduled work that asks Catalog ingestion to refresh vector search data.
description: |
Platform triggers a recurring vector-batch job on a five-minute cadence
to request search index refreshes without owning book records.
icon: Database
---
## 1. Context & Problem
BookWorm spans catalog management, pre-purchase shopping, order fulfillment, customer reviews, conversational discovery, and platform messaging. When product managers, business analysts, solution architects, and developers use everyday words like "book", "basket", "buyer", "order", or "checkout" differently across subdomains, requirements drift and service boundaries blur.
This domain-level ubiquitous language establishes one shared set of core concepts and ownership rules across the entire BookWorm domain.
## 2. Business Value
- **Shared cross-team vocabulary:** Aligns business stakeholders and engineering teams on the exact meaning of BookWorm's core domain concepts.
- **Protected service ownership:** Makes explicit which subdomain owns each record—such as books in Catalog, baskets in Shopping, orders in Ordering, and feedback in Reviews—preventing accidental data duplication.
- **Reliable business semantics:** Distinguishes mutable shopping intent from durable purchase records, live catalog prices from recorded order prices, and checkout initiation from completed orders.
## 3. How It Works
The BookWorm domain vocabulary connects six core capability areas:
- **Catalog & Reviews (`Book`, `Feedback`):** A **Book** is a title represented in the bookstore catalog with descriptive, pricing, availability, and classification details owned by Catalog, while other contexts reference it only by identifier. **Feedback** captures a customer's rating and optional comment about a book; Reviews owns individual submissions, whereas Catalog maintains only an aggregate rating summary.
- **Shopping (`Basket`):** A **Basket** is a customer's changeable collection of book references and quantities before purchase, representing mutable shopping intent rather than an order or an inventory reservation.
- **Checkout & Ordering (`Checkout`, `Buyer`, `Order`, `Order Item`):** **Checkout** is the cross-context process that coordinates transitioning a checked-out basket into the order workflow—it is a process, not another name for an order. A **Buyer** is the person associated with an order in Ordering (holding a name and delivery address, and not automatically sharing the same identifier used for a shopping basket). An **Order** is the durable purchase record with a lifecycle status, composed of **Order Items** that record the book identifier, quantity, and price used for that purchase rather than live catalog pricing.
- **Conversational Support & Platform (`Chat Request`, `Idempotency Guard`, `Dead-Letter Queue`, `Email Template`, `Vector Batch Job`):** A **Chat Request** is a customer question routed or answered by conversational agents that may discuss a book or order without taking ownership of those records. Platform executes stateless notifications using **Email Template** rendering, **Idempotency Guard** deduplication, and **Dead-Letter Queue** routing on exhausted retries, while **Vector Batch Job** triggers periodic Catalog vector indexing.
## 4. Trade-offs & Lessons Learned
- **Identifier references over duplicated entities:** Having other contexts reference a **Book** by identifier instead of copying full catalog data keeps Catalog as the single source of truth, while requiring targeted lookups or read projections when enriched details are needed.
- **Recorded order prices vs. live catalog prices:** Storing the agreed purchase price on each **Order Item** guarantees historical financial accuracy when catalog prices change, whereas a **Basket** remains transient and reflects current catalog state until checkout.
- **Aggregated ratings vs. individual reviews:** Keeping detailed **Feedback** records in Reviews while storing only an aggregate summary in Catalog avoids tight runtime coupling between browsing and reviews, at the cost of eventual consistency for rating totals.
## 5. Technical Reference
### BookWorm Domain Dictionary Terms
The YAML `dictionary` frontmatter above defines the authoritative domain-wide glossary entries rendered by EventCatalog:
| Dictionary ID | Summary | Ownership & Boundary Notes | Icon |
| ------------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ---------------- |
| `Book` | A title represented in the bookstore catalog. | Owned by Catalog (descriptive, pricing, availability, classification); referenced by ID. | `BookOpen` |
| `Basket` | A customer's changeable collection of books before purchase. | Mutable shopping intent (book IDs + quantities); not an `Order` or inventory reservation. | `ShoppingBasket` |
| `Buyer` | The person associated with an Order in Ordering. | Holds name and delivery address; identifier is not automatically the Basket customer ID. | `User` |
| `Order` | The durable purchase record managed by Ordering. | Contains `Order Item` records and lifecycle status; distinct from a preceding `Basket`. | `ClipboardList` |
| `Order Item` | One book, quantity, and price recorded on an Order. | Captures purchase-time book ID, quantity, and price; not a live Catalog price copy. | `ListOrdered` |
| `Feedback` | A customer's rating and optional comment about a Book. | Individual records owned by Reviews; Catalog maintains an aggregate rating summary. | `MessageSquare` |
| `Checkout` | The cross-context process that starts order placement. | Coordinates transition from a checked-out `Basket` to the order workflow; not an `Order`. | `CreditCard` |
| `Chat Request` | A customer question handled by Conversational agents. | May discuss a `Book` or `Order`, but those records remain owned by their contexts. | `MessageCircle` |
| `Idempotency Guard` | Time-bounded deduplication guard for incoming notification commands. | 24-hour TTL deduplicating repeated notification deliveries. | `ShieldCheck` |
| `Dead-Letter Queue` | Message channel holding commands that exhausted delivery retries. | Routes exhausted failures for operator inspection and replay. | `AlertTriangle` |
| `Email Template` | Responsive email markup compiled to HTML at runtime for order emails. | Compiles responsive templates into HTML messages for external relay delivery. | `FileCode` |
| `Vector Batch Job` | Scheduled work that asks Catalog ingestion to refresh vector search data. | Emits periodic refresh triggers without owning book data. | `Database` |
---
dictionary:
- id: Customer Request
name: Customer Request
summary: A BookWorm-related message being handled by the agents.
description: |
A request is the interaction being routed or answered. Books, Baskets,
and Orders mentioned in it remain owned by their respective contexts.
icon: MessageCircle
- id: Decision Router
name: Decision Router
summary: Evaluates safety, language, scope, and target specialist for a customer request.
description: |
The Decision Router checks safety, English language compliance, and BookWorm
domain scope, then selects Book Agent, QA Agent, or Rating Agent in a single
pass before invoking any generative specialist.
icon: Route
- id: Book Agent
name: Book Agent
summary: Helps customers search for books and receive recommendations.
description: |
The Book Agent uses Catalog capabilities and research sub-agents for search,
details, categories, authors, and recommendations, while inferring
conversational sentiment inline. Catalog remains the source of book data.
icon: Search
- id: Book Catalog Researcher
name: Book Catalog Researcher
summary: Sub-agent that performs deep catalog lookups for the Book Agent.
description: |
The Book Catalog Researcher queries read-only Catalog tools for book details,
categories, authors, and publishers on behalf of Book Agent.
icon: BookSearch
- id: Book Recommendation Researcher
name: Book Recommendation Researcher
summary: Sub-agent that generates tailored book recommendations for the Book Agent.
description: |
The Book Recommendation Researcher synthesizes personalized reading
suggestions using catalog metadata and rating summaries.
icon: Sparkles
- id: QA Agent
name: QA Agent
summary: Answers general questions about bookstore policies and services.
description: |
The QA Agent handles shipping, returns, account, order, billing, and
store-policy questions without changing business records.
icon: CircleHelp
- id: Rating Agent
name: Rating Agent
summary: Summarizes customer book ratings and feedback in Reviews.
description: |
The Rating Agent provides read-only rating and review insights
from the Reviews context via agent-to-agent delegation.
icon: Star
- id: Handoff
name: Handoff
summary: Transfer of a request between specialist agents.
description: |
A handoff routes a request from QA Agent to Book Agent or from Book Agent
to Rating Agent. It is not a business process such as placing an Order.
icon: Forward
---
## 1. Context & Problem
Conversational AI systems introduce terms—such as request routing, specialist agents, sub-researchers, and handoffs—that can easily overlap with core e-commerce concepts like orders, baskets, or customer reviews. Without an agreed vocabulary across product, business analysis, architecture, and engineering teams, requirements can blur what an AI assistant actually owns versus what belongs to transactional business domains.
This ubiquitous language defines the exact domain terms for BookWorm's Conversational subdomain and draws clear boundaries around data ownership.
## 2. Business Value
- **Shared clarity across roles:** Gives architects, product managers, business analysts, and developers one consistent vocabulary for conversational workflows.
- **Clear ownership boundaries:** Makes explicit that books, baskets, orders, and reviews remain owned by their core contexts even when discussed in chat.
- **Safer feature design:** Prevents policy-answering or routing components from being mistaken for transactional workflows that modify business records.
## 3. How It Works
Each term captures a distinct responsibility in handling customer conversations:
- **Customer Request:** The incoming BookWorm-related message being routed or answered. Referencing a book, basket, or order inside a message does not move ownership of those records into the conversational system.
- **Decision Router:** The entry gatekeeper that verifies whether a request is in English and within BookWorm's scope, then selects the right specialist (`book-agent`, `qa-agent`, or `rating-agent`) without needing a full generative AI conversation step.
- **Book Agent:** The specialist (`book-agent`) that helps customers search for titles and receive recommendations using Catalog data and inline sentiment inference, while Catalog remains the authoritative source of book information.
- **Book Catalog Researcher:** The sub-researcher (`book-catalog-researcher`) that executes structured Catalog MCP lookups on behalf of `book-agent`.
- **Book Recommendation Researcher:** The sub-researcher (`book-recommendation-researcher`) that builds tailored reading recommendations for `book-agent`.
- **QA Agent:** The specialist (`qa-agent`) that answers store-policy and service questions (shipping, returns, accounts, orders, billing) strictly as read-only guidance without changing any business records.
- **Rating Agent:** The specialist (`rating-agent`) in Reviews that summarizes book ratings and feedback without altering persisted reviews.
- **Handoff:** A conversational transfer between specialists—either from the QA Agent to the Book Agent, or from the Book Agent to the Rating Agent. A handoff moves dialogue control only; it does not execute a business process such as placing an order.
## 4. Trade-offs & Lessons Learned
- **Strict read-only separation vs. conversational convenience:** Keeping specialist agents out of transactional mutations protects business integrity, though future capabilities that initiate actions must cross explicit domain boundaries rather than hiding inside conversational handoffs.
- **Non-LLM routing efficiency:** Screening language, scope, and target specialist before engaging a generative specialist avoids unnecessary model cost and latency, at the trade-off of maintaining explicit routing rules alongside agent capabilities.
## 5. Technical Reference
| Dictionary ID | Summary | Technical & Boundary Notes |
| -------------------------------- | -------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `Customer Request` | BookWorm-related message being handled by agents. | Interaction only; Books, Baskets, and Orders mentioned remain owned by their respective contexts. |
| `Decision Router` | Evaluates safety, language, scope, and target specialist for a customer request. | Single-pass gatekeeper selecting Book Agent, QA Agent, or Rating Agent. |
| `Book Agent` | Helps customers search for books and receive recommendations. | Agent `book-agent`; delegates to `book-catalog-researcher` and `book-recommendation-researcher` and handles emotional tone inline. |
| `Book Catalog Researcher` | Sub-agent that performs deep catalog lookups for the Book Agent. | Agent `book-catalog-researcher`; queries Catalog MCP tools without owning catalog data. |
| `Book Recommendation Researcher` | Sub-agent that generates tailored book recommendations. | Agent `book-recommendation-researcher`; synthesizes suggestions from catalog metadata and ratings. |
| `QA Agent` | Answers general questions about bookstore policies and services. | Agent `qa-agent`; handles shipping, returns, account, order, billing, and store-policy questions without changing business records. |
| `Rating Agent` | Summarizes customer book ratings and feedback in Reviews. | Agent `rating-agent`; provides read-only review summaries via A2A delegation. |
| `Handoff` | Transfer of a request between specialist agents. | Routes `qa-agent` -> `book-agent` or `book-agent` -> `rating-agent`; conversational routing, not a business process like Order placement. |
---
dictionary:
- id: Idempotency Guard
name: Idempotency Guard
summary: Time-bounded deduplication guard for incoming notification commands.
description: |
The Idempotency Guard tracks processed message identifiers for 24 hours
so duplicate deliveries do not send duplicate customer emails.
icon: ShieldCheck
- id: Dead-Letter Queue
name: Dead-Letter Queue
summary: Message channel holding commands that exhausted delivery retries.
description: |
When transient delivery or rendering retries are exhausted, failed
notification commands route to a dead-letter queue for operator
inspection and replay.
icon: AlertTriangle
- id: Email Template
name: Email Template
summary: Responsive email markup compiled to HTML at runtime for order emails.
description: |
Platform compiles responsive email templates into HTML messages before
submitting them through the external email relay.
icon: FileCode
- id: Vector Batch Job
name: Vector Batch Job
summary: Scheduled work that asks Catalog ingestion to refresh vector search data.
description: |
The Vector Batch Job runs on a five-minute schedule and emits a trigger
for Catalog ingestion without owning book information.
icon: Database
---
## 1. Context & Problem
Platform provides shared background scheduling and stateless email notification capabilities used across BookWorm without owning customer orders, books, baskets, or reviews. Without a shared vocabulary, operational terms like "idempotency," "dead-letter queue," "template," or "batch job" can be misunderstood—for instance, assuming Notification persists an email outbox table or that a scheduled job owns the business data it triggers.
The Platform ubiquitous language establishes one consistent set of definitions for stateless notification delivery and scheduled operational jobs across the subdomain.
## 2. Business Value
- **Shared operational clarity:** Gives product, operations, architecture, and engineering teams a single language for stateless email delivery and recurring platform jobs.
- **Clear domain boundaries:** Makes explicit that scheduled jobs coordinate work (such as catalog vector ingestion) without taking ownership of business data like books or orders.
- **Predictable reliability:** Defines how Redis message-ID deduplication, MJML rendering, MailKit SMTP resilience, and Kafka dead-letter queues work together without a relational email outbox.
- **Faster troubleshooting and onboarding:** Helps new contributors and support staff immediately understand where delivery state lives and how exhausted failures are handled.
## 3. How It Works
The Platform vocabulary is organized into two closely linked areas:
- **Stateless Notification Delivery:**
- **Idempotency Guard:** Time-bounded deduplication keyed by message and handler identity with a 24-hour TTL so duplicate deliveries are safely skipped.
- **Email Template:** Responsive email markup compiled into HTML at runtime before message delivery.
- **Dead-Letter Queue:** Dedicated message channel where failed commands route after transient delivery retries are exhausted.
- **Scheduled Platform Jobs:**
- **Vector Batch Job:** Scheduled work that emits a refresh trigger for Catalog ingestion, supporting search indexing without owning book information.
## 4. Trade-offs & Lessons Learned
- **Stateless delivery over a relational email outbox:** Using **Idempotency Guard** deduplication, **Email Template** rendering in memory, transient retries, and the **Dead-Letter Queue** eliminates a relational database and sweep jobs, at the trade-off of relying on dead-letter tooling for replaying exhausted failures.
- **Coordination without data ownership:** Defining **Vector Batch Job** strictly as a trigger for catalog ingestion preserves clean domain boundaries, requiring downstream systems to remain responsible for validating and maintaining their own data.
## 5. Technical Reference
### Platform Dictionary Terms
The YAML `dictionary` frontmatter above defines the authoritative Platform glossary entries rendered by EventCatalog:
| Dictionary ID | Summary | Operational & Boundary Notes | Icon |
| ------------------- | ------------------------------------------------------------------------- | -------------------------------------------------------------------- | --------------- |
| `Idempotency Guard` | Time-bounded deduplication guard for incoming notification commands. | 24-hour TTL deduplicating repeated notification deliveries. | `ShieldCheck` |
| `Dead-Letter Queue` | Message channel holding commands that exhausted delivery retries. | Routes exhausted failures for operator triage and replay. | `AlertTriangle` |
| `Email Template` | Responsive email markup compiled to HTML at runtime for order emails. | Compiles responsive templates into HTML messages for email delivery. | `FileCode` |
| `Vector Batch Job` | Scheduled work that asks Catalog ingestion to refresh vector search data. | Emits periodic refresh triggers without owning book data. | `Database` |
---
dictionary:
- id: Basket
name: Basket
summary: A customer's current collection of items before purchase.
description: |
The Basket is mutable shopping intent. It is not an Order, an inventory
reservation, or a copy of the Catalog.
icon: ShoppingBasket
- id: Basket Item
name: Basket Item
summary: A book identifier and positive quantity in a Basket.
description: A Basket item does not contain the Catalog Book or an Order price.
icon: Package
- id: Customer Identifier
name: Customer Identifier
summary: The identifier used to address a customer's Basket.
description: |
A Customer identifier is not automatically the Buyer identifier used by
Ordering.
icon: Fingerprint
- id: Checkout
name: Checkout
summary: The action that starts order placement for a Basket.
description: |
Checkout begins coordination across Shopping, Ordering, and the order
workflow. It is not synonymous with completing or cancelling an Order.
icon: CreditCard
- id: Checked-out Event
name: Checked-out Event
summary: An integration message that coordinates checkout.
description: |
The event carries order and basket identifiers, buyer contact details,
and total money to the cross-context order workflow.
icon: Send
---
## 1. Context & Problem
The Shopping subdomain captures what a customer intends to purchase before an order is formally placed. Without a shared vocabulary across business analysts, product managers, solution architects, and developers, pre-order terms such as "basket", "item", "customer", and "checkout" are easily confused with confirmed orders, catalog records, or inventory holds.
This ubiquitous language defines the authoritative meanings and boundaries for Shopping concepts across BookWorm.
## 2. Business Value
- **Clear pre-order boundaries:** Keeps teams from treating a mutable shopping basket as a committed order, an inventory reservation, or a copy of the product catalog.
- **Unambiguous identity handoff:** Clarifies that the customer identifier used to address a basket is distinct from the buyer identifier managed during ordering.
- **Aligned checkout expectations:** Establishes that checkout starts cross-team order coordination rather than immediately completing or cancelling an order.
## 3. How It Works
The Shopping vocabulary is organized around pre-purchase state, customer addressing, and checkout initiation:
- **Basket & Basket Item:** A **Basket** is a customer's current, changeable collection of items before purchase—representing shopping intent rather than an order, inventory reservation, or catalog copy. Each **Basket Item** holds a book identifier and a positive quantity, without embedding the catalog book record or an order price.
- **Customer Identifier:** The **Customer Identifier** addresses a customer's basket within Shopping and is not automatically identical to the buyer identifier used by Ordering.
- **Checkout & Checked-out Event:** **Checkout** is the action that initiates order placement for a basket, starting coordination across Shopping, Ordering, and the order workflow rather than completing or cancelling an order directly. The **Checked-out Event** is the integration message that carries order and basket identifiers, buyer contact details, and total money into that cross-context workflow.
## 4. Trade-offs & Lessons Learned
- **Slim basket items:** Excluding catalog book details and locked order prices from **Basket Item** keeps shopping intent lightweight and prevents stale catalog data, while requiring live catalog enrichment for display and explicit price recording during order creation.
- **Decoupled customer and buyer identities:** Separating **Customer Identifier** from Ordering's buyer identity protects bounded-context autonomy, requiring explicit identity mapping when checkout begins.
- **Checkout as workflow initiation:** Treating **Checkout** and **Checked-out Event** as the start of coordination—rather than a synchronous completion guarantee—allows downstream workflows to run independently and handle failures or retries explicitly.
## 5. Technical Reference
### Shopping Dictionary Terms
The YAML `dictionary` frontmatter above defines the authoritative Shopping glossary entries rendered by EventCatalog:
| Dictionary ID | Summary | Domain & Boundary Notes | Icon |
| --------------------- | --------------------------------------------------------- | --------------------------------------------------------------------------------------------- | ---------------- |
| `Basket` | A customer's current collection of items before purchase. | Mutable shopping intent; not an `Order`, inventory reservation, or copy of Catalog. | `ShoppingBasket` |
| `Basket Item` | A book identifier and positive quantity in a Basket. | Does not store the Catalog `Book` or an `Order` price. | `Package` |
| `Customer Identifier` | The identifier used to address a customer's Basket. | Not automatically the `Buyer` identifier used by Ordering. | `Fingerprint` |
| `Checkout` | The action that starts order placement for a Basket. | Begins coordination across Shopping, Ordering, and the order workflow; not order completion. | `CreditCard` |
| `Checked-out Event` | An integration message that coordinates checkout. | Carries order and basket identifiers, buyer contact details, and total money to the workflow. | `Send` |
---
title: "BookWorm documentation"
summary: "Navigate BookWorm tutorials, how-to guides, technical references, and architecture docs by role across .NET 11, Aspire 17, and Next.js 16."
owners:
- architecture-enabling-team
---
BookWorm is an open-source, cloud-native bookstore reference application built with .NET 11, Aspire 17, Domain-Driven Design, Vertical Slice Architecture, Wolverine over Kafka, Next.js 16 microfrontends, and Microsoft Foundry AI agents. Use this home page to jump directly to the guide that matches your role and task.
:::warning
BookWorm is a reference and demonstration application. It is not hardened for production use out of the box—see [[doc|operational/004-security-hardening-checklist]] before deploying to a live environment.
:::
## Start by role
| Role | Primary goal | Start here |
| :-------------------- | :---------------------------------------------------------------------------- | :------------------------------------------------------------------------------ |
| **Local developer** | Run BookWorm locally and verify the full stack in under 15 minutes | [[doc\|development/000-local-quickstart]] |
| **Contributor** | Set up a fork, follow coding standards, run tests, and open a pull request | [[doc\|development/002-getting-started]] |
| **Architect** | Understand bounded contexts, architecture views, event flows, and ADRs | [[doc\|development/001-developer-onboarding]] and [[doc\|arc42/00-c4-overview]] |
| **Operator / DevOps** | Deploy to Azure Container Apps, observe telemetry, and run incident playbooks | [[doc\|operational/001-azure-deployment-guide]] |
## Documentation map
BookWorm documentation is organized into four Diátaxis quadrants so every page serves one clear purpose:
### Tutorials (learning-oriented)
- [[doc|development/000-local-quickstart]] — End-to-end guided walkthrough from cloning the repo to running Aspire AppHost, exploring the Storefront, and verifying APIs.
### How-to guides (task-oriented)
- **Development:**
- [[doc|development/002-getting-started]] — Fork, install tools with `mise`, configure Git hooks, and install frontend/docs workspaces.
- [[doc|development/003-development-workflow]] — Branching, formatting, pre-commit hooks, and repository skills.
- [[doc|development/005-testing]] — Run TUnit, ArchUnit, Pact consumer/provider verification, and EventCatalog checks.
- [[doc|development/006-pull-request-process]] — Conventional Commit titles, PR checklist, CI workflows, and maintainer review.
- [[doc|development/007-troubleshoot-local-dev]] — Fix common Docker, Aspire, Entra ID, Kafka, Qdrant, Redis, and Bun errors.
- **Frontend:**
- [[doc|frontend/009-add-customer-page]] — Add routes across Storefront and Commerce microfrontends.
- [[doc|frontend/004-testing-and-quality-gates]] — Run Turborepo boundary, type, lint, Vitest, and Playwright BDD checks.
- [[doc|frontend/005-accessibility]] — Run WCAG 2.1 AA checks with `axe-core` and ESLint `jsx-a11y`.
- **Operations:**
- [[doc|operational/001-azure-deployment-guide]] — Publish BookWorm to Azure Container Apps with `aspire deploy`.
- [[doc|operational/002-observability-and-diagnostics]] — Inspect Aspire Dashboard telemetry, Log Analytics KQL queries, and Application Insights.
- [[doc|operational/003-incident-response-and-runbooks]] — Symptom-first triage for Container Apps, Entra ID RBAC, Finance sagas, vector lag, and AI chat.
- [[doc|operational/004-security-hardening-checklist]] — Security, networking, scaling, and operational readiness checklist.
### Reference (information-oriented)
- **Core standards & governance:**
- [[doc|development/004-engineering-standards]] — C# 15, DDD/VSA, integration events, Protocol Buffers, and frontend rules.
- [[doc|development/008-testing-matrix]] — Complete backend, frontend, and documentation test inventory and frameworks.
- [[team|architecture-enabling-team]] — Logical ownership roles, repository mappings, and maintainer channels.
- [[doc|arc42/12-glossary]] — Canonical BookWorm business and architecture vocabulary.
- **Platform & cloud:**
- [[doc|platform/001-platform-overview]] — Subscription deployment model, shared backbone, and single-gateway ingress.
- [[doc|platform/002-compute-and-container-apps]] — Complete compute inventory including Storefront, Commerce, Backoffice, APIs, workers, and Presidio.
- [[doc|platform/003-data-ai-and-messaging-resources]] — PostgreSQL, Cosmos DB, Redis, Blob Storage, Qdrant, Kafka, Durable Task Scheduler, and Microsoft Foundry.
- [[doc|platform/004-identity-and-rbac-matrix]] — Microsoft Entra ID app registrations, Entra Agent Identities, and managed-identity RBAC.
- **Frontend & APIs:**
- [[doc|frontend/001-monorepo-architecture]] — Four-tier Turborepo monorepo and 16 `@workspace/*` packages.
- [[doc|frontend/002-applications-and-routing]] — Storefront, Commerce, and Backoffice route maps and gateway prefixes.
- [[doc|frontend/003-data-fetching-and-state]] — Typed API clients, TanStack Query factories, ETag concurrency, and AG-UI streaming.
- [[doc|platform/006-api-and-contracts]] — Consolidated HTTP, gRPC, and Kafka contracts across all services.
### Explanation and architecture (understanding-oriented)
- [[doc|development/001-developer-onboarding]] — Bounded contexts, system shape, and architectural principles.
- [[doc|arc42/00-c4-overview]] — Single-page overview of system context and containers.
- [[doc|frontend/006-microfrontend-architecture]] — Why Storefront and Commerce split into multi-zone Next.js apps behind API Gateway.
- [[doc|frontend/007-architecture-and-state-design]] — Monorepo tiers, thin routes, feature slices, and caching design.
- [[doc|frontend/008-accessibility-principles]] — WCAG 2.1 AA strategy and inclusive design practices.
- [[doc|misc/001-ms-decisions-model-use-case-and-lessons-learned]] — Single-pass chat routing, safety gating, and dynamic tool selection with `Microsoft-Decision-1`.
- [[doc|arc42/09-architecture-decisions]] — Whole-system and system-level architectural decisions.
---
title: arc42 Architecture Overview
summary: Entry point to BookWorm's architecture, key boundaries, and supporting documentation.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
Use this page to navigate BookWorm's architecture and find the view that answers your question. BookWorm is organized around six business capabilities, a customer and staff edge, and a shared technical foundation; the chapters describe their boundaries, interactions, deployment, and quality requirements.
:::tip
For a visual orientation to the system boundary and its internal building blocks, start with the [[doc|arc42/00-c4-overview]].
:::
## Architectural orientation
BookWorm groups business rules and authoritative data by capability rather than by technical layer. Capabilities collaborate through explicit interfaces and events, keeping ownership visible while allowing independently owned parts to evolve.
The view below summarizes the capability boundaries and selected interactions. Use the context, building-block, runtime, and deployment chapters for the corresponding details.
| Boundary rule | Architectural consequence |
| :------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------------------------- |
| **Capability-owned state** | Each business capability is authoritative for its records; other capabilities use its contracts instead of accessing its stores directly. |
| **Explicit integration** | Synchronous calls serve interactions that need an immediate result; asynchronous events coordinate work that can complete later. |
| **Separate business and delivery outcomes** | Order status belongs to Ordering. A failed job or email attempt does not, by itself, reverse an accepted order. |
| **Derived data can lag** | Search indexes and rating summaries are projections of authoritative data, so updates may become visible after the source change. |
| **Read-only conversational assistance** | Discovery and chat can use catalog and review information, but do not change baskets or orders. |
These rules are reflected in the prioritized goals in [[doc|arc42/01-introduction-and-goals/003-quality-goals]], the solution strategy in [[doc|arc42/04-solution-strategy]], and the runtime scenarios in [[doc|arc42/06-runtime-view]].
## arc42 chapter map
Choose a chapter by the question you need to answer. The overview and context chapters establish the system purpose and boundaries; the remaining chapters explain its design, behavior, operation, and terminology.
| Chapter | Primary question answered | Intended readers |
| :------------------------------- | :------------------------------------------------------------------------------------------ | :--------------------------------------------- |
| **1. Introduction and goals** | What business purpose, requirements, quality goals, and stakeholders shape BookWorm? | Product stakeholders, architects, contributors |
| **2. Architecture constraints** | Which technical and organizational constraints limit design choices? | Architects, contributors |
| **3. Context and scope** | Which people and external systems interact across the BookWorm boundary? | Product stakeholders, architects, operators |
| **4. Solution strategy** | Which architectural approaches address the primary goals and constraints? | Architects, contributors |
| **5. Building block view** | How is BookWorm decomposed into capabilities, services, and supporting elements? | Architects, contributors |
| **6. Runtime view** | How do representative checkout, discovery, feedback, and delivery scenarios execute? | Architects, contributors, operators |
| **7. Deployment view** | Where do applications and supporting infrastructure run in each environment? | Operators, architects |
| **8. Crosscutting concepts** | How are shared concerns such as security, messaging, observability, and testing handled? | Contributors, operators |
| **9. Architecture decisions** | Why were significant platform and system choices made, and which decisions were superseded? | Architects, contributors |
| **10. Quality requirements** | Which measurable scenarios define and verify required system qualities? | Architects, operators |
| **11. Risks and technical debt** | Which known exposures and compromises need mitigation or remediation? | Architects, operators |
| **12. Glossary** | What do domain and architecture terms mean in this documentation? | All readers |
## Related architecture documentation
- [[doc|arc42/00-c4-overview]] — System boundary and container views.
- [[doc|arc42/01-introduction-and-goals]] — Business purpose, requirements, stakeholders, and quality goals.
- [[doc|arc42/09-architecture-decisions]] — Decision records and their rationale.
- [[doc|arc42/10-quality-requirements]] — Quality attributes and measurable scenarios.
- [[doc|arc42/11-risks-and-technical-debt]] — Prioritized risks and known technical debt.
- [[doc|arc42/12-glossary]] — Canonical domain and technical terminology.
---
title: "Architecture overview"
summary: "System context, container structure, and capability ownership for the BookWorm platform."
owners:
- architecture-enabling-team
---
BookWorm is an online bookstore for customers and store staff. This page summarizes the system boundary, deployable building blocks, and ownership rules; detailed context, runtime behavior, and hosting are described in the corresponding arc42 chapters.
## Scope and reading the views
The platform includes customer and staff web experiences, business capabilities, background processing, and the shared foundation that supports them. Identity, AI inference, messaging, email delivery, and managed infrastructure are external dependencies where they are provided by other systems.
The views move from the whole system to its internal building blocks. The system context view focuses on users and external neighbors. The container views show the platform's applications and services grouped by responsibility; they do not replace the detailed static, runtime, or deployment views.
## System context
This view places BookWorm between the people who use the bookstore and the external services it depends on.
## Container views
The following views group the deployable parts of BookWorm by capability. Together, they cover the customer-facing edge, commerce, discovery, reviews, ordering, and platform operations.
### Edge and commerce capabilities
This view follows customer and staff traffic through the public entry point and into the storefront, basket, catalog, and ordering capabilities.
### Discovery and platform capabilities
This view shows how conversational discovery, customer feedback, privacy support, scheduled work, and notification delivery relate to their supporting services and data.
### Ordering and operations
This view focuses on order ownership, post-checkout coordination, and the operational services that support these workflows.
## Capability ownership
Each capability owns its business rules and authoritative records. The table summarizes those boundaries; the Building Block View provides the full static decomposition.
| Building block | Responsibility | Main elements | Ownership boundary |
| :--------------------- | :------------------------------------------------------------------------------------------- | :-------------------------------------------- | :------------------------------------------------------------------------------------------------------------ |
| **Edge and frontends** | Provides the public entry point and customer and staff journeys. | API Gateway, Storefront, Commerce, Backoffice | Routes requests to capability owners; does not own authoritative catalog, basket, order, or feedback records. |
| **Catalog** | Owns book information, pricing, and discovery. | Catalog API, Catalog Ingestion | Catalog records are authoritative here; search indexes and rating summaries are derived data. |
| **Shopping** | Manages customer baskets before checkout. | Basket API | Owns active basket state until checkout transfers purchase intent to Ordering. |
| **Ordering** | Records accepted orders, purchase-time details, and official order status. | Ordering API, Finance | Ordering owns business outcomes; Finance tracks post-checkout workflow progress separately. |
| **Reviews** | Manages customer feedback and makes review information available to other capabilities. | Rating API | Owns individual feedback; other capabilities may maintain derived summaries. |
| **Conversational** | Supports guided discovery and customer questions using bookstore information. | Chat API, MCP Tools | Reads catalog and review information; does not create or change baskets or orders. |
| **Platform** | Supports scheduled work and transactional email delivery. | Scheduler, Notification | Delivery and job outcomes do not replace the business outcome recorded by an owning capability. |
| **Shared foundation** | Provides common hosting, identity integration, diagnostics, resilience, and privacy support. | Shared platform capabilities | Supports the business capabilities without becoming a shared owner of their domain records. |
## Architectural boundaries
- **Owned data and contracts:** Each capability remains authoritative for its records. Other capabilities integrate through explicit HTTP, gRPC, or event contracts instead of reading another capability's stores.
- **Synchronous and asynchronous work:** Request-response calls support interactions that need an immediate result. Kafka events coordinate work across capabilities; projections and external side effects may complete later and require recovery handling.
- **Order state and workflow state:** Ordering is the source of truth for accepted orders and their official status. Finance coordinates post-checkout work without redefining whether an order succeeded.
- **Read-only assistance:** Conversational features use catalog and review information to provide guidance, but do not mutate commerce transactions.
- **External dependencies:** Identity, AI inference, messaging, email delivery, and managed infrastructure can affect availability or behavior. Their interfaces and operational assumptions are detailed in the context and deployment chapters.
## Related architecture documentation
- [[doc|arc42]] — Navigate all arc42 chapters.
- [[doc|arc42/03-context-and-scope]] — Actors, external systems, and boundary exchanges.
- [[doc|arc42/05-building-block-view]] — Static decomposition and capability responsibilities.
- [[doc|arc42/06-runtime-view]] — Representative cross-capability runtime scenarios.
- [[doc|arc42/07-deployment-view]] — Hosting environments and infrastructure placement.
- [[doc|arc42/08-crosscutting-concepts]] — Shared contracts, security, resilience, and operating practices.
---
title: Introduction and Goals
summary: BookWorm's business purpose, essential requirements, priority quality scenarios, and stakeholder concerns.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
This chapter defines the strategic baseline for BookWorm: its business purpose, essential requirements, priority quality goals, and key stakeholders. Use it to align product, engineering, architecture, and operations decisions.
## Scope and architectural baseline
- **System scope:** BookWorm includes the customer storefront, commerce workflows, back-office management, and shared platform capabilities.
- **Architectural priority order:** (1) **Correctness**, (2) **Interoperability**, (3) **Deployability**, (4) **Modifiability**, and (5) **Operability**.
- **Baseline boundaries:** This chapter summarizes the current architecture. It does not replace a stakeholder-approved product backlog or formal service targets.
## Chapter map
| Section | Focus | Audience |
| :----------------------------------------------------------------- | :------------------------------------------------------------------ | :--------------------------------------- |
| [[doc\|arc42/01-introduction-and-goals/001-introduction]] | Business purpose, six areas, external boundaries, and primary users | Architects, contributors, stakeholders |
| [[doc\|arc42/01-introduction-and-goals/002-requirements-overview]] | Essential system requirements and capability ownership | Architects, contributors, product owners |
| [[doc\|arc42/01-introduction-and-goals/003-quality-goals]] | Prioritized quality goals and success scenarios | Architects, contributors, operators |
| [[doc\|arc42/01-introduction-and-goals/004-stakeholders]] | Stakeholder roles, expectations, and documentation routes | All audiences |
## Key principles established in this chapter
- **Single owner for each domain record:** Catalog owns products and pricing; Shopping owns baskets; Ordering owns accepted orders; Reviews owns feedback; Conversational provides guided discovery; Platform supplies shared capabilities.
- **Explicit gaps over implied commitments:** Where numerical latency, availability, or recovery budgets and named approver contacts are not yet formally signed off, this chapter labels them as proposed rather than claiming operational guarantees.
## Related architecture documentation
- [[doc|arc42/00-c4-overview]] — Single-page C4 Context and Container view of BookWorm.
- [[doc|arc42/02-architecture-constraints]] — Technical, organizational, and convention guardrails.
- [[doc|arc42/03-context-and-scope]] — Whole-platform business and technical boundaries.
- [[doc|arc42/04-solution-strategy]] — Core architectural approaches addressing these quality goals.
- [[doc|arc42/09-architecture-decisions]] — Platform and system ADRs governing design choices.
- [[doc|arc42/12-glossary]] — Canonical definitions for BookWorm domain and platform terms.
---
title: Introduction
summary: BookWorm's business purpose, architectural scope, and intended audience.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
BookWorm is an online bookstore platform. It helps customers find books, maintain a basket, place and track orders, share reviews, and receive AI-assisted guidance. Store teams use it to manage catalog and customer information.
The platform separates its responsibilities into six areas so that each area can grow and change without taking ownership of another area's information.
## Business purpose and user roles
BookWorm serves two primary user groups:
- **Customers:** Find and compare books, ask for recommendations, maintain a basket, place checkout requests, track orders, and publish reviews.
- **Store administrators and business users:** Manage books, authors, categories, publishers, customer orders, buyer information, and review moderation.
## Platform scope and bounded contexts
Each area owns its business rules and records. Services share information only through clearly defined interfaces.
| Bounded context | Deployable services | Authoritative responsibility |
| :----------------- | :------------------------------------------------------------ | :------------------------------------------------------------------------------------------------ |
| **Catalog** | [[service\|catalog-api]], [[service\|catalog-ingestion]] | Book details, authors, categories, publishers, prices, cover images, search, and rating summaries |
| **Shopping** | [[service\|basket-api]] | Baskets and customer selections before checkout |
| **Ordering** | [[service\|order-api]], [[service\|order-orchestration]] | Accepted orders, purchase details, order status, and post-checkout coordination |
| **Reviews** | [[service\|rating-api]] | Customer feedback and review summaries |
| **Conversational** | [[service\|chat-api]], [[service\|mcp-server]] | Guided book discovery and assistance based on catalog and review information |
| **Platform** | [[service\|notification-api]], [[service\|scheduler-service]] | Shared notifications and scheduled work, without owning a business area |
## System boundary and external dependencies
The diagram shows the BookWorm platform boundary, its users, its six internal areas, and its external services.
### Verified vs. unimplemented external boundaries
- **Implemented external integrations:** Identity and access services authenticate users and control access for customers, administrators, and business users. AI model services provide conversational, decision-support, and search capabilities. Email services send messages in local and cloud environments. Messaging distributes work between services, while vector storage enables semantic search. Internal privacy services detect and remove sensitive personal information.
- **Out-of-scope conceptual boundaries:** Payment providers and shipping providers are not implemented. Post-checkout coordination manages basket cleanup and notifications; it does not accept or settle payments.
## Architectural scope trade-offs
- **Separate areas over a shared model:** Keeping domain data separate prevents hidden dependencies and protects checkout accuracy. It requires clear interfaces between areas.
- **Shared services vs. business ownership:** Keeping notification and scheduled work separate prevents shared infrastructure from taking over commerce responsibilities.
- **Specialist services:** Using established identity, AI, email, messaging, and search services lets the team focus on bookstore capabilities.
## Related architecture documentation
- [[doc|arc42/01-introduction-and-goals/002-requirements-overview]] — Essential functional and architectural requirements.
- [[doc|arc42/01-introduction-and-goals/003-quality-goals]] — Top five prioritized quality goals and acceptance evidence.
- [[doc|arc42/01-introduction-and-goals/004-stakeholders]] — Stakeholder roles and their documentation needs.
- [[doc|arc42/02-architecture-constraints]] — Technical, organizational, and coding constraints.
- [[doc|arc42/03-context-and-scope]] — Detailed business and technical context views.
- [[doc|arc42/00-c4-overview]] — Visual C4 Context and Container diagrams.
---
title: Requirements Overview
summary: Essential BookWorm capabilities and architectural requirements synthesized from the current catalog.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
This page summarizes the main capabilities and boundaries that BookWorm must provide. The `BW-R` identifiers are architecture references, not formal product backlog items.
## Essential requirements
Checkout is the main point where the catalog, basket, and order areas work together. Before an order is accepted, the basket is checked against current catalog information.
| ID | Capability or driver | Requirement | Owning context and realization |
| :-------- | :------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------- |
| **BW-R1** | Book discovery and catalog management | Customers find books using current product, price, and availability information. Store staff maintain books and their related information. | **Catalog** |
| **BW-R2** | Basket and checkout | Customers maintain a saved basket. Checkout verifies its items against current catalog information and rejects unavailable products. | **Shopping** and **Ordering** |
| **BW-R3** | Order lifecycle | A valid checkout creates one accepted order. Ordering owns the order status and post-checkout work. | **Ordering** |
| **BW-R4** | Customer feedback | Customers submit feedback and staff moderate it. Review records remain separate from catalog records. | **Reviews** and **Catalog** |
| **BW-R5** | Conversational assistance | AI-assisted guidance uses catalog and review information. It must not imply access to basket or order information that it cannot use. | **Conversational** |
| **BW-R6** | Shared platform capabilities | Scheduled work and transactional email support business operations without becoming owners of business records. | **Platform** |
| **BW-R7** | Independent capability evolution | Each area owns its behavior and records. A change in one area should not require unrelated areas to change or release together. | All bounded contexts |
| **BW-R8** | Explicit integration contracts | Areas communicate through documented interfaces that remain compatible as they evolve. | All bounded contexts |
## Requirement traceability view
The diagram maps the main capabilities and boundaries to the areas responsible for them.
## Key design trade-offs and open gaps
- **Explicit contracts vs. ad-hoc coupling:** Independent ownership (`BW-R7`) and compatibility-checked integrations (`BW-R8`) require clear interface design and verification, but prevent silent downstream breakages.
- **Scoped AI assistance over broad data access:** AI assistance should use only approved catalog, policy, and review information. It should not expose live basket or order information.
- **Unresolved formal commitments:** Product backlog ownership and formally approved service targets are not yet defined.
## Related architecture documentation
- [[doc|arc42/01-introduction-and-goals/001-introduction]] — Business purpose and external boundaries.
- [[doc|arc42/01-introduction-and-goals/003-quality-goals]] — Prioritized quality scenarios and acceptance evidence.
- [[doc|arc42/02-architecture-constraints]] — Technical and organizational rules backing `BW-R7` and `BW-R8`.
- [[doc|arc42/03-context-and-scope]] — Whole-platform business and technical boundaries.
- [[doc|arc42/04-solution-strategy]] — Core architectural responses to these requirements.
- [[doc|arc42/10-quality-requirements/002-quality-scenarios]] — Detailed measurable scenarios (`QS-01`-`QS-17`).
---
title: Quality Goals
summary: Prioritized, scenario-based quality goals for BookWorm and the current status of their acceptance targets.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
BookWorm prioritizes **correctness**, **interoperability**, **deployability**, **modifiability**, and **operability**. These goals guide decisions across the platform.
:::note
The priorities describe the current architectural baseline. Numerical service targets require formal stakeholder approval.
:::
## Prioritized quality goals
| Priority | Quality goal | Scenario and expected response | What it protects | Verification evidence and mechanisms | Detailed scenarios |
| :------- | :------------------- | :--------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------- | :---------------------------------------------------- | :----------------- |
| **1** | **Correctness** | Checkout verifies basket items against current catalog information. Missing or unavailable books block order creation. | Accurate purchases and one clear owner for accepted orders | Automated checkout tests and purchase-detail checks | `QS-01`, `QS-02` |
| **2** | **Interoperability** | One area communicates with another through a documented, compatible interface. | Clear responsibility and safe independent changes | Contract tests and compatibility checks | `QS-03` |
| **3** | **Deployability** | A compatible change can be released without unnecessarily releasing unrelated areas. | Independent releases and lower coordination cost | Automated builds, tests, and deployment checks | `QS-04` |
| **4** | **Modifiability** | A business rule changes within its owning area without changing another area's records or rules. | Localized changes and bounded responsibility | Data separation and architecture checks | `QS-05`, `QS-17` |
| **5** | **Operability** | Failed work is traceable to the responsible area and does not appear to reverse accepted business results. | Faster diagnosis and clear incident ownership | Execution history, traces, and failed-message records | `QS-06` |
## Governing trade-offs
- **Correctness over convenience:** Checkout never trusts client-supplied book prices or bypasses **Catalog** validation to reduce latency.
- **Explicit contracts over shared state:** Separate persistence across **Catalog**, **Shopping**, **Ordering**, **Reviews**, **Conversational**, and **Platform** adds contract maintenance overhead, but keeps dependencies visible and independently testable.
- **Delivery state is not business completion:** A failed scheduled job or email does not, by itself, change an accepted order.
- **Current verification gap:** Unit, contract, architecture, and frontend checks exist. Backend integration test coverage is still incomplete.
## Related architecture documentation
- [[doc|arc42/01-introduction-and-goals/002-requirements-overview]] — Essential requirements (`BW-R1`-`BW-R8`) aligned to these goals.
- [[doc|arc42/02-architecture-constraints]] — Engineering and boundary rules enforcing these goals.
- [[doc|arc42/04-solution-strategy]] — Architectural approaches addressing Priorities 1-5.
- [[doc|arc42/10-quality-requirements]] — Quality attributes and 17 measurable scenarios (`QS-01`-`QS-17`).
- [[doc|arc42/11-risks-and-technical-debt]] — Open exposures and missing verification evidence.
---
title: Stakeholders
summary: Roles affected by BookWorm's architecture, what they expect from it, and how this documentation supports them.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
This page documents the stakeholder roles that rely on BookWorm's architecture, what each group expects from the system, and where each group finds answers in the documentation. Because BookWorm is an open-source reference platform whose maintainers evolve over time, this register tracks **roles** rather than named individuals.
## Stakeholder roles and documentation routing
| Stakeholder role | Expectations and concerns | Primary architecture views |
| :------------------------------------------ | :-------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Customers** | Discover books, manage a basket, complete checkouts, track orders, submit reviews, and receive grounded AI assistance. | [[doc\|arc42/01-introduction-and-goals/001-introduction]], [[doc\|arc42/03-context-and-scope/002-business-context]] |
| **Store administrators and business users** | Manage catalog entries, process order changes, review feedback, and monitor scheduled work with appropriate access control. | [[doc\|arc42/01-introduction-and-goals/002-requirements-overview]], [[doc\|arc42/08-crosscutting-concepts/001-security-and-privacy]] |
| **Product and business stakeholders** | Understand which capabilities drive business outcomes, where new features belong, and which quality trade-offs take priority. | [[doc\|arc42/01-introduction-and-goals/002-requirements-overview]], [[doc\|arc42/01-introduction-and-goals/003-quality-goals]], [[doc\|arc42/10-quality-requirements/001-quality-requirements-overview]] |
| **Domain and service engineers** | Build and evolve services inside clear boundaries without creating hidden dependencies or breaking consumer integrations. | [[doc\|arc42/00-c4-overview]], [[doc\|arc42/02-architecture-constraints]], [[doc\|arc42/04-solution-strategy]], [[doc\|arc42/05-building-block-view]] |
| **Platform and infrastructure engineers** | Operate shared infrastructure without absorbing business rules. | [[doc\|arc42/03-context-and-scope/003-technical-context]], [[doc\|arc42/07-deployment-view]], [[doc\|arc42/08-crosscutting-concepts]] |
| **Operations and support teams** | Diagnose failed jobs and messages and route incidents to the responsible area. | [[doc\|arc42/06-runtime-view]], [[doc\|arc42/08-crosscutting-concepts/004-observability]], [[doc\|arc42/11-risks-and-technical-debt]] |
| **Architecture and engineering leadership** | Evaluate whether service decomposition, contract governance, AI safeguards, and technical debt remain coherent as BookWorm grows. | [[doc\|arc42/09-architecture-decisions]], [[doc\|arc42/10-quality-requirements/002-quality-scenarios]], [[doc\|arc42/11-risks-and-technical-debt]] |
## Governance boundaries
- **Role catalog vs. formal approver directory:** Documenting roles keeps this architecture baseline durable across contributor changes, but it does not assign named decision-makers or formal SLA sign-off authority.
- **Logical team ownership:** Repository ownership conventions are documented in [[team|architecture-enabling-team]].
## Related architecture documentation
- [[doc|arc42/01-introduction-and-goals/001-introduction]] — Platform business purpose and bounded contexts.
- [[doc|arc42/01-introduction-and-goals/002-requirements-overview]] — Essential requirements (`BW-R1`-`BW-R8`).
- [[doc|arc42/01-introduction-and-goals/003-quality-goals]] — Top five prioritized quality goals.
- [[doc|arc42/02-architecture-constraints]] — Rules governing team and service boundaries.
- [[doc|arc42/03-context-and-scope]] — Whole-platform business and technical context.
- [[doc|arc42/04-solution-strategy]] — Core architectural strategies.
---
title: Architecture Constraints
summary: Mandatory technical, organizational, and engineering guardrails for BookWorm.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
This chapter defines the guardrails for decisions that shape BookWorm across .NET 11 services, Next.js 16 microfrontends, and Aspire 17 orchestration. It separates mandatory constraints from engineering conventions and open commitments: constraints limit options, while principles guide choices and exceptions.
The catalog distinguishes:
- **Mandatory constraints:** changes require an approved exception or an architecture decision record (ADR).
- **Engineering conventions:** repository standards that automated checks or review should enforce.
- **Open commitments:** targets or controls that are not yet signed off and must not be presented as guarantees.
## Executive summary
- Preserve bounded-context ownership and explicit interoperability.
- Resolve breaking changes through impact and migration planning.
- Name an owner and approver for every material exception.
- Enforce platform standards and evidence-based architecture changes.
- Avoid uncontrolled technology, compliance, vendor, or operational commitments.
BookWorm is an open-source reference architecture. It does not, by itself, establish organization-specific procurement mandates, staffing models, regulatory certification, approved service levels, or named production approvers.
## Architecture constraint principles
These principles translate architecture governance into practical BookWorm rules.
1. **Domain ownership is explicit.** One bounded context owns one domain and its authoritative data.
2. **Contracts are products.** Consumers depend on stable, versioned interfaces owned and evolved by a producer.
3. **Standards reduce variance.** Approved runtimes, frameworks, protocols, and verification tools take precedence over local alternatives.
4. **Independent deployment follows compatibility.** Deployment autonomy is earned through validated contracts and operational readiness.
5. **Infrastructure is supportive.** Shared platform components must not become hidden domain owners or transaction coordinators.
6. **Decisions must be traceable.** Material changes include an ADR, updated documentation, and recorded evidence.
7. **Gaps remain visible.** Proposed targets remain proposals until scope, owners, budgets, and acceptance evidence are approved.
## Technical constraints
| ID | Mandatory constraint | Business and architectural impact | Primary evidence |
| :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------- |
| **TC1** | **Preserve bounded-context data ownership.** Each bounded context owns its domain behavior and persistence. Services do not query another service's database directly. | Limits change blast radius, protects domain invariants, and requires explicit cross-boundary contracts. | Service boundaries and persistence configuration; `BookWorm.ArchTests` |
| **TC2** | **Integrate through owned, explicit contracts.** Cross-service communication uses versioned HTTP (`ApiVersions.V1`), Protocol Buffers gRPC, or CloudEvents JSON over Kafka through Wolverine. | Gives producers and consumers a stable interoperability surface and makes compatibility a release gate. | Contract definitions; Pact and Protocol Buffer verification |
| **TC3** | **Evolve Protocol Buffer contracts compatibly.** Lint `.proto` definitions (`edition = "2023"`) and verify backward compatibility against the committed baseline. Breaking changes require consumer coordination and a migration plan. | Prevents incompatible gRPC clients and avoids unplanned rollout coupling. | `.proto` lint and compatibility jobs |
| **TC4** | **Use the approved backend stack.** Target `net11.0`, C# 15, `BookWorm.slnx`, `Mediator.SourceGenerator` for CQRS, Wolverine and Kafka, Microsoft Entra ID, Aspire 17, and TUnit on Microsoft.Testing.Platform. | Standardizes runtime behavior, tooling, observability, identity, and delivery pipelines. | `Directory.Packages.props`, solution projects, CI workflows |
| **TC5** | **Use the approved frontend stack.** Use Bun, Turborepo, Next.js 16, React 19, TypeScript, and Better Auth integrated with Microsoft Entra ID across Storefront, Commerce, and Backoffice. | Prevents lockfile and dependency-layer drift while preserving consistent identity and delivery behavior. | Bun lockfile, Turbo boundaries, frontend CI |
| **TC6** | **Make independent deployability a compatibility property.** A service may deploy independently only when the intended contract and behavior remain compatible with consumers. | Supports faster, lower-risk releases; breaking changes require a coordinated migration or compatibility period. | Contract tests, deployment pipelines, release evidence |
| **TC7** | **Keep shared infrastructure domain-neutral.** Notification, Scheduler, API Gateway, and BuildingBlocks must not own commerce domain state or enforce commerce business rules. | Prevents shared infrastructure from becoming an implicit coupling point or hidden source of truth. | Architecture tests, code ownership, service boundaries |
| **TC8** | **Apply security controls at platform and endpoint boundaries.** Authenticate and authorize external requests, protect secrets, and apply PII and AI governance controls where sensitive data or agents are used. | Reduces exposure from identity, privacy, and model-integration failures. | Endpoint policies, secret configuration, Presidio and AI governance settings |
## Organizational constraints
| ID | Mandatory constraint | Enforcement and governance |
| :------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- |
| **OC1** | **Assign bounded-context ownership.** Every service, contract, and cross-context flow has an explicit owner and escalation path before production adoption or boundary change. | Architecture review confirms ownership; the owning team maintains implementation and contract evolution. |
| **OC2** | **Keep architecture artifacts synchronized.** Behavior, contract, persistence, or boundary changes update the relevant architecture views and ADR set. | Pull-request review and documentation/architecture fitness checks identify drift. |
| **OC3** | **Protect credentials and toolchain baselines.** Secrets remain outside source control. SDK and package-feed configuration changes require explicit approval. | GitHub Actions or Azure OIDC, user secrets, or environment variables contain credentials; `global.json` and `NuGet.config` remain protected. |
| **OC4** | **Record material architecture decisions.** Non-reversible or cross-team decisions require an ADR describing context, options, consequences, and ownership. | Accepted ADRs are reviewed and linked to implementation, roadmap, and operational runbooks. |
| **OC5** | **Use evidence for production commitments.** Availability, recovery, latency, privacy, security, and AI safeguards require frozen test conditions and recorded evidence. | Service owners report evidence; designated review forums grant production status. |
## Engineering conventions
| ID | Convention | Repository and CI enforcement |
| :----- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------- |
| **C1** | Use `mise` tasks for restore, build, test, format, and workspace preparation. | Repository task definitions and pre-commit checks provide a repeatable workflow. |
| **C2** | Keep C# types, async flows, namespaces, and dependencies consistent. Endpoints, handlers, `DbContext` types, and tests are sealed by default; `CancellationToken` is propagated; namespaces are file-scoped; package versions are centrally managed. | `.editorconfig`, analyzers, Central Package Management, and `BookWorm.ArchTests` enforce and detect violations. |
| **C3** | Use `snake_case` PostgreSQL identifiers and explicit API versioning. Authorization is applied at endpoint boundaries. | Naming conventions, migrations, OpenAPI metadata, and endpoint tests preserve consistency. |
| **C4** | Preserve integration-event naming and routing metadata. Shared contracts live in `BookWorm.Contracts`; events follow owned naming and identity conventions. | Wolverine routing, contract tests, and EventCatalog fitness checks validate interoperability. |
| **C5** | Validate boundaries continuously. Combine unit, contract, architecture, frontend, and documentation checks. | TUnit, PactNet, ArchUnitNET, Vitest, Playwright BDD, Turbo boundaries, and documentation checks form the change-safety gate. |
## Architecture governance
Architecture governance should make constraints visible, proportionate, and reviewable before implementation.
| Governance stage | Required output | Decision authority |
| :-------------------------- | :----------------------------------------------------------------------------------------------------- | :---------------------------------------- |
| **Architecture principles** | Confirm that the proposal follows the principles in this chapter | Architecture review |
| **Baseline and target** | Compare current and target business, application, data, and technology states | Product and architecture review |
| **Impact assessment** | Identify affected bounded contexts, consumers, data, security, operations, cost, and rollout risk | Domain owners and delivery management |
| **Decision and roadmap** | Record an ADR and sequence migrations, compatibility periods, and verification | Delegated architecture authority |
| **Implementation review** | Demonstrate contract compatibility, automated checks, operational readiness, and documentation updates | Engineering leads and governance forum |
| **Benefit and risk review** | Record outcomes and unresolved risks against the approved target | Executive sponsor and architecture review |
### Exception process
An exception is a documented, time-bound deviation; it is not an informal bypass.
1. Identify the constraint or convention, affected systems, and the reason the baseline is unsuitable.
2. Assess user, security, compliance, delivery, cost, operability, and migration impacts.
3. Define compensating controls, an expiry or exit condition, and a named accountable owner.
4. Obtain approval from the authority appropriate to the risk.
5. Record the exception in an ADR or governed exception register.
6. Review the exception before expiry and remove or renew it with evidence.
## Open commitments and scope limits
The following items require formal approval and are intentionally not represented as current guarantees:
- Numerical latency, availability, throughput, freshness, recovery, and retention budgets.
- Named production SLAs, RTO/RPO targets, and contractual compliance obligations.
- Organization-specific regulatory scope, security certification, vendor procurement, and staffing requirements.
- End-to-end operational evidence for all proposed quality scenarios.
Unresolved numerical budgets belong in the quality requirements and decisions records rather than this constraint catalog.
## Related architecture documentation
- [[doc|development/004-engineering-standards]] — Detailed backend and frontend coding standards.
- [[doc|arc42/04-solution-strategy]] — How BookWorm satisfies quality goals within these constraints.
- [[doc|arc42/08-crosscutting-concepts/002-contracts-and-messaging]] — Detailed gRPC, REST, and Kafka contract rules.
- [[doc|arc42/08-crosscutting-concepts/006-testing-and-change-safety]] — Verification layers enforcing compatibility and boundary rules.
- [[doc|arc42/09-architecture-decisions]] — Formal decisions behind these constraints.
- [[doc|arc42/10-quality-requirements]] — Proposed quality targets and measurable scenarios.
---
title: Context and Scope
summary: Business and technical boundary of the complete BookWorm platform.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
This chapter defines the BookWorm system boundary: which people and external systems interact with it and what information or value crosses the boundary. It treats the complete platform as one black box.
BookWorm is responsible for the complete customer and administration experience of an online bookstore. External providers supply identity, AI, email transport, and managed infrastructure capabilities; they do not become part of the BookWorm system boundary.
## Overview
The subject system is the whole BookWorm platform, including all capabilities exposed to customers and store staff. It owns the domain information and business outcomes needed to operate the bookstore, while the following kinds of actors and neighbors remain outside:
- Customers and store administrators who use the platform.
- Identity services that authenticate users and establish roles.
- AI services that provide language, routing, and embedding capabilities.
- Email delivery services that transport transactional messages.
- Managed infrastructure services that support messaging and search.
Internal applications, bounded contexts, databases, queues, and modules are outside the scope of this chapter. They are described in the [[doc|arc42/05-building-block-view]] and the [[doc|arc42/07-deployment-view]].
The system boundary is illustrated below:
## Business Context
The Business Context describes the domain-level relationships between BookWorm and its communication partners. It covers:
- The actors and external neighbors that exchange information or receive business outcomes.
- The purpose and value of each exchange.
- The information sent into and out of the BookWorm boundary.
- Any relevant business assumptions or interface exclusions.
The business view must not contain protocols, API routes, deployment components, or infrastructure product names.
See [[doc|arc42/03-context-and-scope/002-business-context]].
## Technical Context
The Technical Context describes how each business relationship is realized across the boundary. It identifies:
- Human and machine communication channels.
- Protocols, formats, authentication mechanisms, and interaction directions.
- External systems and the interfaces through which they are reached.
- Open network or infrastructure assumptions that are not yet formally resolved.
The technical view must map every communication partner in the Business Context to one or more concrete technical channels. Internal implementation detail remains in the deployment and building-block views.
See [[doc|arc42/03-context-and-scope/003-technical-context]].
## Chapter map
| Section | Focus | Primary audience |
| :-------------------------------------------------------- | :-------------------------------------------------------------------- | :------------------------------------------ |
| [[doc\|arc42/03-context-and-scope/001-overview]] | Subject system, boundary responsibilities, and scope exclusions | Product stakeholders, architects, engineers |
| [[doc\|arc42/03-context-and-scope/002-business-context]] | Black-box actors, external neighbors, and business data exchanges | Product stakeholders, analysts, architects |
| [[doc\|arc42/03-context-and-scope/003-technical-context]] | Boundary channels, protocols, formats, and external technical systems | Architects, contributors, operators |
## Related architecture documentation
- [[doc|arc42/00-c4-overview]] — C4 context and container diagrams.
- [[doc|arc42/01-introduction-and-goals]] — Business purpose, requirements, and prioritized quality goals.
- [[doc|arc42/02-architecture-constraints]] — Technical and organizational constraints.
- [[doc|arc42/05-building-block-view]] — Whitebox decomposition inside the BookWorm boundary.
- [[doc|arc42/07-deployment-view]] — Runtime and infrastructure topology.
---
title: Context and Scope Overview
summary: High-level system boundary for the BookWorm online bookstore.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
## System Boundary Summary
BookWorm is the online bookstore system responsible for helping customers discover books and complete and track purchases. It owns the related catalog, basket, order, review, and administrative workflows. Customers and store staff interact with these capabilities through the platform, while external service providers supply supporting capabilities across the boundary. Payment authorization, physical fulfillment, identity assurance, and message transport are therefore separate responsibilities rather than parts of the bookstore platform itself.
## System Context Diagram (Level 1)
This System Context diagram illustrates the actors (`Customer`, `Back-office user`) interacting with the BookWorm system and the external cloud and infrastructure providers across its boundary.
## In Scope
- Book discovery, search, product details, and AI-assisted recommendations.
- Customer baskets, checkout requests, order history, and order status.
- Customer reviews and store review-management workflows.
- Catalog and customer-administration workflows for store staff.
- Transactional order outcomes and business notifications.
## Out of Scope
- Payment authorization and settlement are owned by external payment providers.
- Warehouse operations and physical shipment delivery are owned by fulfillment and shipping providers.
- User identity verification and account authentication are owned by the external identity provider.
- Final email delivery is owned by the external email transport provider.
---
title: Business Context
summary: Domain actors and information exchanged across the BookWorm system boundary.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
This view describes BookWorm as one system and identifies the people and external providers that exchange domain information or business value with it.
## System Boundary
## Communication Partners Table
| Communication Partner | Type (User / System) | Inputs (to System) | Outputs (from System) | Business Purpose |
| :-------------------------- | :------------------- | :----------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------- |
| **Customers** | User | Book searches, basket changes, checkout requests, questions, and reviews | Catalog and pricing information, basket status, order confirmation and history, recommendations, and review listings | Discover books, purchase selected books, and engage with the store |
| **Store Administrators** | User | Catalog changes, order decisions, and review moderation | Catalog worklists, order status, and review queues | Operate and maintain the bookstore |
| **Identity Provider** | System | Identity confirmation and user roles | Sign-in and access confirmation requests | Verify customers and staff before protected bookstore activities |
| **AI Service** | System | Recommendations, conversation responses, and review summaries | Book and feedback context for guidance | Improve discovery and provide informed customer and review assistance |
| **Email Delivery Provider** | System | Delivery status and delivery failures | Order, account, and notification email content | Inform customers about accepted purchases and account or store events |
## Risks & External Influences
- Identity, role, and profile information must be accurate and protected because incorrect or outdated information can deny access or expose customer activity.
- AI-generated guidance depends on the quality and currency of book and feedback context; unsuitable or inaccurate output can affect purchasing decisions.
- Email delivery depends on an external provider, so acceptance by the provider does not guarantee that a customer receives or reads a message.
---
title: Technical Context
summary: External-facing channels and protocols that realize the BookWorm business context.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
This view describes only the interfaces exposed across the BookWorm system boundary. It does not show internal communication, implementation components, or infrastructure topology.
## Technical Context and Channel Diagram
## Business-to-Technical Mapping Table
| External Partner | Business Input/Output | Technical Channel & Protocol | Data Format | Auth / Security | Notes / SLA |
| :-------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------ | :----------------------------------- | :--------------------------------------------------------- | :-------------------------------------------------------------------------------------------- |
| **Customers** | Submit searches, basket changes, checkout requests, questions, and reviews; receive catalog, basket, order, recommendation, and review information | HTTPS web channel, bidirectional | HTML pages and JSON application data | Identity-provider authentication; secure sessions | Proposed: `99.9%` availability; p95 up to `500 ms` for browse/basket and `2 s` for checkout |
| **Store Administrators** | Submit catalog, order, and review decisions; receive worklists and status information | HTTPS web channel, bidirectional | HTML pages and JSON application data | Authenticated administrative session with role checks | Uses the customer interface capacity targets; no separate administrative SLA |
| **Identity Provider** | Receives sign-in requests and provides identity confirmation and user roles | OAuth 2.0 / OpenID Connect over HTTPS | OIDC redirects and signed tokens | Issuer, audience, signature, expiry, and role validation | Provider availability and token lifetime follow the identity-provider tenant SLA |
| **AI Service** | Receives book and feedback context; provides recommendations, conversation responses, and summaries | HTTPS request-response | JSON | Credential or workload authentication; encrypted transport | Proposed timeout `30 s`; `3` attempts with capped backoff; output quality is not signed off |
| **Email Delivery Provider** | Receives order, account, and notification email content; may report delivery failures | SMTP over TLS | MIME email message | SMTP credentials or equivalent provider authentication | Relay timeout `45 s`; transient submissions retry `3` times; inbox delivery SLA is unverified |
## Key Interface Notes
### Web channels
- Customer operations target p95 browse/basket latency of `500 ms`, checkout latency of `2 s`, p99 at most `2x` p95, and unexpected errors below `1%`.
- Apply load protection of `100` concurrent requests and `30 requests/minute per IP`; reject additional load with a clear retry message.
- Administrative activity shares the web channel but has no separate measured SLA.
### Identity and AI
- **Identity:** Microsoft Entra ID is the provider. Validate issuer, audience, signature, expiry, and role claims; allow `10 s` for sign-in or token validation. Provider downtime and token lifetime follow the provider's tenant policy.
- **AI:** Microsoft Foundry is the provider. Allow `30 s` per request, use at most `3` attempts with capped backoff, and limit requests to `20/minute per IP` and `10` requests per `30 s` per user. Unsuitable or unavailable model output must use an explicit degraded result.
### Email
- SendGrid is used in cloud environments and Mailpit in local environments.
- A relay submission times out after `45 s`; retry transient failures up to `3` times with `1 s` exponential backoff.
- Relay acceptance does not prove inbox delivery. Bounce handling and final delivery status remain unverified.
### Other channels
- No file drops, webhooks, hardware interfaces, or external message-broker integrations are defined for the current business context.
---
title: Solution Strategy
summary: Executive summary of the architectural decisions that satisfy BookWorm's quality goals and constraints.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
BookWorm uses a modular, contract-driven architecture to support correct commerce, independent change, reliable operation, and governed use of identity and AI services. The strategy separates authoritative business responsibilities, favors explicit interfaces over shared state, and verifies architecture continuously.
## Technology Decisions
- Use a consistent .NET runtime and application framework for backend capabilities, with an approved frontend platform for customer and administration experiences. This supports **Modifiability**, **Interoperability**, and **Operability** and implements technical constraints TC4 and TC5.
- Use explicit, versioned interfaces for cross-area communication. Stable contracts allow producers and consumers to evolve independently, satisfying **Interoperability** and **Deployability** and implementing TC2, TC3, and TC6.
- Use a common orchestration and observability baseline for local development and deployment. This reduces environment drift and provides consistent diagnostics for **Deployability** and **Operability**.
- Match persistence to each area's consistency and access needs while keeping one authoritative owner for each domain record. This supports **Correctness** and **Modifiability** and implements TC1.
- Use managed identity, least-privilege authorization, and governed AI integrations. This protects customer and staff boundaries and sensitive information, supporting **Correctness** and **Operability** and implementing TC8.
## Top-Level Decomposition
BookWorm is divided into six business areas:
- **Catalog:** Book data, pricing, discovery, and catalog search.
- **Shopping:** Customer baskets before checkout.
- **Ordering:** Accepted orders, purchase details, lifecycle, and post-checkout coordination.
- **Reviews:** Customer feedback and review information.
- **Conversational:** Guided discovery and store assistance.
- **Platform:** Shared notification and scheduled-work capabilities.
Shared infrastructure supplies identity, messaging, deployment, observability, and operating support. It does not own commerce state or business rules.
## Quality Goal Mapping
| Priority | Quality Goal | Fundamental Strategy | Primary Constraints or Verification |
| :------- | :------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------ |
| **1** | **Correctness** | Keep domain ownership separate, validate purchase information against authoritative data, and distinguish accepted orders from delivery or coordination outcomes | TC1, TC7, TC8; checkout and correctness scenarios |
| **2** | **Interoperability** | Use owned, versioned contracts and compatibility checks between business areas | TC2, TC3; contract and compatibility verification |
| **3** | **Deployability** | Deploy compatible areas independently and require contract compatibility before release | TC6; mixed-version and rollback verification |
| **4** | **Modifiability** | Organize change around bounded areas and enforce architecture boundaries continuously | TC1, TC6, TC7; architecture and change-safety checks |
| **5** | **Operability** | Trace failed work to its owner, preserve actionable execution state, and use common diagnostics | TC8, OC1, OC2, OC5; tracing, failed-work inspection, and restore evidence |
The governing quality goals and detailed scenarios are in [[doc|arc42/01-introduction-and-goals/003-quality-goals]] and [[doc|arc42/10-quality-requirements]].
## Organizational and Process Decisions
- Assign an explicit owner to each business area and contract.
- Require architecture review and documented ADRs for cross-area or non-reversible decisions.
- Synchronize architecture documentation with behavior, contract, and deployment changes.
- Enforce compatibility, security, privacy, and evidence-based production claims before release.
- Keep unresolved service levels as proposals until scope, owners, budgets, and acceptance evidence are approved.
## Key Trade-offs
- Bounded ownership and explicit contracts add integration and migration effort but reduce hidden coupling and release risk.
- Asynchronous delivery and derived views improve isolation but require visible recovery, duplication, and freshness handling.
- Independent deployment is permitted only where compatibility and operational readiness have been verified.
## Related Architecture Documentation
- [[doc|arc42/02-architecture-constraints]] — Mandatory technical and organizational constraints.
- [[doc|arc42/03-context-and-scope]] — System boundary and external communication channels.
- [[doc|arc42/05-building-block-view]] — Top-level and detailed static decomposition.
- [[doc|arc42/09-architecture-decisions]] — Rationale and alternatives for material decisions.
---
title: Building Block View
summary: Static decomposition of BookWorm into owned business capabilities, services, and shared foundations.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
This chapter documents BookWorm's static structure from the whole platform down to service internals and checkout orchestration. It aligns with C4 Container and Component views and isolates ownership boundaries from runtime message sequences and Azure deployment placement.
## Decomposition hierarchy
BookWorm uses three progressive zoom levels so you inspect only the depth required for your task.
This diagram shows how each Building Block View level zooms into the next level of static structure.
| Zoom level | Document | Abstraction level | Scope |
| :---------- | :---------------------------------------------------------------- | :-------------------------- | :------------------------------------------------------------------------------------------------------------------------------------- |
| **Level 1** | [[doc\|arc42/05-building-block-view/001-whitebox-overall-system]] | System / Container overview | Edge tier (`API Gateway`, `Storefront`, `Commerce`, `Backoffice`), six backend bounded contexts, shared foundation, and boundary rules |
| **Level 2** | [[doc\|arc42/05-building-block-view/002-level-2]] | Container / Service detail | Internal services, dedicated data stores (PostgreSQL, Cosmos DB, Redis, Qdrant, Azure Blob, Durable Task Scheduler), and source paths |
| **Level 3** | [[doc\|arc42/05-building-block-view/003-level-3]] | Component detail | Selective deep dive into `Finance` (`BookWorm.Finance`) Azure Durable Functions orchestration components and contracts |
## Selective refinement rationale
- **Capability-first decomposition:** BookWorm groups code by business ownership ([[domain|catalog]], [[domain|shopping]], [[domain|ordering]], [[domain|reviews]], [[domain|conversational]], [[domain|platform]]) rather than technical tiers, preventing a shared business middle layer.
- **Selective Level 3 zoom:** Only [[service|order-orchestration]] expands to Level 3 because it coordinates multi-step checkout outcomes across [[domain|ordering]], [[domain|shopping]], and [[domain|platform]].
- **Separation of concerns:** External neighbors appear in [[doc|arc42/03-context-and-scope/003-technical-context]], step-by-step message sequences appear in [[doc|arc42/06-runtime-view]], and cloud hosting appears in [[doc|arc42/07-deployment-view]].
## Related architecture decisions
| ADR | Decision summary | Status |
| :---------------------------------------------------------- | :---------------------------------------------------------------------------------- | :------- |
| [[adr\|adr-bw-001-capability-aligned-boundaries]] | Decompose BookWorm by bounded context and business ownership | Proposed |
| [[adr\|adr-bw-003-aspire-shared-service-defaults]] | Centralize hosting, observability, and resilience in shared platform infrastructure | Proposed |
| [[adr\|adr-bw-006-service-owned-business-state]] | Keep authoritative persistence inside the owning capability | Proposed |
| [[adr\|adr-005-finance-separate-workflow-and-order-status]] | Keep Finance workflow outcomes separate from authoritative Ordering status | Accepted |
---
title: Whitebox Overall System
summary: Level-1 decomposition of BookWorm into its top-level business capabilities and shared foundation.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
## Overview Diagram
The white-box view groups BookWorm's applications and capability services into eight Level-1 building blocks and shows their principal dependencies. User interactions remain in the system context view; detailed internal relationships are covered at Level 2 and Level 3. The table below lists each building block and links to its catalog resources.
## Motivation
BookWorm is decomposed by business capability so each area can own its rules and authoritative data while collaborating through explicit contracts. The edge, shared foundation, and grouped supporting resources provide common entry and operational capabilities without becoming a shared business layer.
## Contained Building Blocks
| Building Block | Responsibility (Blackbox) | Key Interfaces / Exposed APIs |
| :----------------------------- | :----------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Edge and Frontends** | Provides the customer and staff experiences and the system's public entry point. | Customer and staff web experiences; routes requests to capability APIs. |
| **[[domain\|catalog]]** | Owns book, author, category, publisher, and pricing information and makes books discoverable. | [[service\|catalog-api]] for catalog operations; [[service\|catalog-ingestion]] for catalog search updates; [[container\|catalog-database]], [[container\|catalog-cache]], [[container\|catalog-blob]], and [[container\|catalog-vector]]. |
| **[[domain\|shopping]]** | Owns customer baskets before checkout and provides basket information to the purchase journey. | [[service\|basket-api]]; [[container\|basket-database]]. |
| **[[domain\|ordering]]** | Owns accepted orders, purchase details, and official order status. | [[service\|order-api]]; checkout coordination with [[service\|order-orchestration]]; [[container\|order-database]]. |
| **[[domain\|reviews]]** | Owns customer feedback and provides review information for bookstore experiences. | [[service\|rating-api]]; [[container\|rating-database]]. |
| **[[domain\|conversational]]** | Provides guided book discovery and store assistance using catalog and review information. | [[service\|chat-api]] and [[service\|mcp-server]]; [[container\|chat-session-blob]]. |
| **[[domain\|platform]]** | Provides scheduled work and transactional email capabilities for the bookstore. | [[service\|scheduler-service]] and [[service\|notification-api]]; [[container\|scheduler-database]]. |
| **Shared Foundation** | Supplies shared hosting, diagnostics, resilience, and integration capabilities without owning business data. | Shared libraries and hosting integrations used by the capability blocks. |
## Important Interfaces
- Capability blocks exchange information through owned, versioned HTTP and gRPC contracts or asynchronous event contracts; compatibility is verified before changes are released.
- Each capability remains authoritative for its own business data. Other blocks obtain information through its interfaces rather than accessing its stores directly.
- See [[doc\|arc42/08-crosscutting-concepts/002-contracts-and-messaging]] for contract and messaging conventions, and [[doc\|arc42/06-runtime-view]] for interaction sequences.
## Related Views
- [[doc\|arc42/05-building-block-view/002-level-2]] — Internal services and stores within each capability.
- [[doc\|arc42/05-building-block-view/003-level-3]] — Detailed decomposition of checkout orchestration.
- [[doc\|arc42/07-deployment-view]] — Deployment and infrastructure placement.
---
title: Building Block View Level 2
summary: Static responsibilities, interfaces, and data ownership within BookWorm's major capabilities.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
This view opens the Level-1 capability blocks into their applications, services, and owned data stores. It describes static responsibilities and interfaces without detailing internal classes or code layers.
## Overview
Related components are grouped by the capability or concern they support, with people and external dependencies kept outside those groups. The tables below provide the complete building-block inventory.
### Commerce and Data Ownership
### Discovery and Reviews
### Ordering and Operations
## Motivation
The system groups applications, services, and stores by the business capability that owns their behavior and data. This keeps changes and scaling needs localized while contracts make cross-capability dependencies explicit.
## Contained Building Blocks
| Building Block | Responsibility (Blackbox) | Key Interfaces / Exposed APIs |
| :----------------------------- | :------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Edge and Frontends** | Provides the public entry point and the customer and staff experiences. | Gateway routes browser requests to storefront, commerce, back-office, and capability APIs. |
| **[[domain\|catalog]]** | Owns book, author, category, publisher, and pricing information and makes books discoverable. | [[service\|catalog-api]] exposes versioned HTTP and book gRPC interfaces; [[service\|catalog-ingestion]] maintains the derived search index. Owned data: [[container\|catalog-database]], [[container\|catalog-cache]], [[container\|catalog-blob]], [[container\|catalog-vector]]. |
| **[[domain\|shopping]]** | Owns customer baskets before checkout and provides basket information to Ordering. | [[service\|basket-api]] exposes versioned HTTP and basket gRPC interfaces. Owned data: [[container\|basket-database]]. |
| **[[domain\|ordering]]** | Owns accepted orders, purchase details, and official order status; coordinates post-checkout work separately from order status. | [[service\|order-api]] exposes order and staff operations; [[service\|order-orchestration]] coordinates post-checkout outcomes. Owned data: [[container\|order-database]] and [[container\|order-cache]]. |
| **[[domain\|reviews]]** | Owns customer feedback and makes review information available to bookstore experiences. | [[service\|rating-api]] exposes feedback operations and an agent interface. Owned data: [[container\|rating-database]] and [[container\|rating-cache]]. |
| **[[domain\|conversational]]** | Provides guided book discovery and store assistance using catalog and review information. | [[service\|chat-api]] provides the customer conversation interface; [[service\|mcp-server]] provides read-only catalog tools. Conversation data is held in [[container\|chat-session-blob]]. |
| **[[domain\|platform]]** | Provides scheduled work and transactional email delivery for the bookstore. | [[service\|scheduler-service]] initiates scheduled work; [[service\|notification-api]] submits customer email. Owned state includes [[container\|scheduler-database]] and the order workflow's durable state. |
| **Shared Foundation** | Provides common hosting, identity integration, diagnostics, resilience, and privacy capabilities without owning business data. | Shared technical libraries and hosting integrations used by applications and services. |
## Important Interfaces
- Synchronous cross-capability calls use owned, versioned HTTP or gRPC contracts; asynchronous work uses owned event and command contracts.
- Each capability remains authoritative for its own business data. Other capabilities use its interfaces rather than reading its stores directly.
- Search vectors and catalog rating summaries are derived data and may lag behind authoritative catalog and review updates.
- AI-assisted discovery and review summaries are advisory; they do not create or change baskets or orders.
## Related Views
- [[doc\|arc42/05-building-block-view/001-whitebox-overall-system]] — Level-1 capability overview.
- [[doc\|arc42/05-building-block-view/003-level-3]] — Detailed decomposition of checkout orchestration.
- [[doc\|arc42/06-runtime-view]] — Runtime interactions between building blocks.
- [[doc\|arc42/07-deployment-view]] — Deployment and infrastructure placement.
---
title: Building Block View Level 3
summary: Level-3 view of Finance workflow coordination.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
Finance merits a deeper view because its post-checkout workflow must reconcile asynchronous basket deletion, authoritative order completion or cancellation, timeout retries, and compensating actions. Correctness depends on legal terminal-state transitions and safe recovery when a side effect succeeds but its confirmation is delayed.
## Structure
The first view captures stable domain and workflow relationships; the second locates those responsibilities within Finance and its external partners.
## Core Elements
| Class / Interface | Role & Invariants | Extension / Modification Point |
| :-------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------- |
| **`Order`** | Workflow-local aggregate for basket, customer contact, total, retry count, and coordination status. Identifiers must be non-empty, the retry limit positive, and terminal states cannot transition again. Ordering remains authoritative for official order status. | Route lifecycle changes through `OrderLifecycleDecider`; keep Finance coordination status distinct from Ordering's business status. |
| **`OrderLifecycleDecider` / `OrderStatus`** | Enforces legal state transitions, prevents duplicate basket-deletion completion, and bounds retry-driven cancellation. | Add lifecycle actions and terminal-state rules here so every transition follows the same invariant checks. |
| **`OrderOrchestrator`** | Starts placement, waits for external outcomes, delegates each outcome to a workflow step, and ends on a terminal result or exhausted retry limit. | Change sequencing and timeout policy here; keep orchestration replay-safe and domain rules in the aggregate and decider. |
| **`IOrderWorkflowStep` / `OrderStepContext`** | Provides the strategy boundary for handling a winning event or timer with access to the current workflow state and recovery actions. The timeout step is the fallback and must not shadow specific event handlers. | Add a focused step for a new outcome and preserve dispatch precedence, especially the fallback timeout behavior. |
| **`OrderSagaCompensations`** | Registers recovery actions before forward side effects and executes them in reverse order when coordination fails. A failed compensation is logged without preventing remaining actions. | Pair each new reversible side effect with its recovery action; preserve completion semantics for normal, exhausted-retry, and failure paths. |
| **`Money` / `CustomerContact`** | `Money` rejects negative totals. Notifications are eligible only when both a customer name and email are available. | Keep amount and contact eligibility rules in these value objects rather than scattering them through workflow steps. |
## Related Resources
- [[service\|order-orchestration]] — Finance ownership and integration boundary.
- [[event\|UserCheckedOutIntegrationEvent]], [[event\|BasketDeletedCompleteIntegrationEvent]], [[event\|BasketDeletedFailedIntegrationEvent]], [[event\|OrderStatusChangedToCompleteIntegrationEvent]], and [[event\|OrderStatusChangedToCancelIntegrationEvent]] — workflow inputs.
- [[adr\|adr-005-finance-separate-workflow-and-order-status]] — separates Finance coordination outcomes from authoritative Ordering status.
- [[doc\|arc42/06-runtime-view/001-checkout-and-order-coordination]] — checkout coordination sequence.
---
title: Runtime View
summary: Representative BookWorm runtime scenarios across commerce, discovery, customer feedback, and platform operations.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
BookWorm combines synchronous request-response interactions for browsing and commands with asynchronous event-driven coordination for post-commit work. Bounded contexts own their state and publish facts or commands across Kafka; derived views and external side effects may therefore lag while retries, idempotency, and compensation preserve eventual consistency.
## Runtime Overview
The overview distinguishes direct web and service calls from broker-mediated coordination and scheduled work.
## Scenario Index
These scenarios cover the highest-risk runtime boundaries: cross-service checkout, derived catalog state, review compensation, AI orchestration, and external delivery. They expose both state-changing transactions and independently retryable work.
| Scenario | Trigger | Key Building Blocks | Primary Quality Goal |
| :----------------------------------------------------------------------- | :----------------------------------------------------------- | :---------------------------------------------------------------------------------- | :---------------------------------------------------------------- |
| [[doc\|arc42/06-runtime-view/001-checkout-and-order-coordination]] | Customer submits checkout | Commerce, API Gateway, Ordering API, Basket API, Catalog API, Finance, Notification | Consistent order creation with bounded post-checkout coordination |
| [[doc\|arc42/06-runtime-view/002-catalog-search-index-maintenance]] | Catalog write or scheduled batch trigger | Catalog API, PostgreSQL, Scheduler, Catalog Ingestion, Microsoft Foundry, Qdrant | Fresh and concurrency-safe search data |
| [[doc\|arc42/06-runtime-view/003-feedback-and-rating-projection]] | Feedback is created or deleted | Rating API, Catalog API, Kafka Broker | Accurate derived ratings with recoverable invalid references |
| [[doc\|arc42/06-runtime-view/004-conversational-book-discovery]] | Customer submits a chat turn | Storefront, Chat API, Microsoft Foundry, Presidio, MCP Tools, Rating API | Safe, grounded, low-latency guidance |
| [[doc\|arc42/06-runtime-view/005-notification-delivery-and-maintenance]] | Finance publishes an email command or a scheduled job starts | Finance, Notification, Scheduler, Catalog Ingestion, Kafka Broker | Reliable delivery attempts and predictable maintenance |
---
title: Checkout and Order Coordination
summary: Checkout creation and asynchronous basket and email coordination.
owners:
- commerce-fulfillment-team
badges:
- content: Runtime Scenario
backgroundColor: purple
textColor: purple
---
Checkout converts a mutable basket into an authoritative purchase-time order, then delegates basket cleanup and email delivery to asynchronous coordination. The synchronous portion establishes the order before the customer receives the order identifier.
## Purpose & Trigger
The flow creates an order with immutable item and price snapshots while keeping external cleanup outside the ordering transaction. It starts when an authenticated customer submits a checkout request.
## Visual References
_Checkout and Order Coordination_
## Step-by-Step Walkthrough
1. Commerce sends the checkout request through API Gateway, including the caller's idempotency identity.
2. Ordering API synchronously reads current basket quantities from Basket API and authoritative book and price data from Catalog API.
3. Ordering API records the order and purchase-time snapshots, commits the state, and returns the order identifier. This synchronous response does not mean basket cleanup or email delivery has completed.
4. Ordering API publishes a checkout fact asynchronously. Finance starts a workflow correlated by the order identifier.
5. Finance publishes basket cleanup and email commands independently. Basket API and Notification consume the commands in separate paths.
6. Basket API deletes the basket and reports success or failure asynchronously.
7. Notification applies idempotency and submits the email independently of basket cleanup.
8. Finance records the basket outcome and reconciles the workflow. A timeout or repeated failure triggers bounded compensation rather than a distributed transaction.
## Error Handling & Edge Cases
- Repeated checkout requests use the same idempotency identity and must not create a second order.
- Basket or catalog read failures leave checkout uncommitted and allow a caller retry.
- Kafka retries may duplicate downstream commands; basket deletion and email delivery must remain repeatable safely.
- A missing basket outcome is bounded by a workflow timeout and retry limit.
- Timeout compensation may notify the customer, but it does not by itself change the authoritative order status.
## Quality & Consistency Notes
- Checkout latency depends on basket and catalog reads, plus the synchronous order commit; slow email delivery is outside this critical path.
- The order preserves purchase-time prices and remains independent of later catalog changes.
- Basket cleanup, email delivery, and workflow completion are eventually consistent with the committed order.
---
title: Catalog Search Index Maintenance
summary: Maintaining the derived semantic search index after catalog changes.
owners:
- catalog-experience-team
badges:
- content: Runtime Scenario
backgroundColor: purple
textColor: purple
---
Catalog API records revisions to authoritative book data, while scheduled work refreshes the derived search index in bounded batches. The search index may lag catalog changes but must never overwrite a newer revision.
## Purpose & Trigger
The flow keeps the semantic search index aligned with book creations, updates, and removals. It starts from a catalog data change or a scheduled batch trigger.
## Visual References
_Catalog Search Index Refresh_
## Step-by-Step Walkthrough
1. Catalog API commits a book change synchronously and records a pending revision for indexing.
2. PostgreSQL stores the pending work with the latest revision for the affected book.
3. Scheduler periodically publishes an asynchronous batch trigger to Kafka.
4. Catalog Ingestion receives the trigger and attempts exclusive access to the catalog batch.
5. If another run owns the batch or no work is pending, the run exits without changing data.
6. Otherwise, Catalog Ingestion reads at most 200 revisions and synchronously requests embeddings from Microsoft Foundry for active books.
7. Catalog Ingestion upserts active vectors and removes vectors for deleted or missing books in Qdrant.
8. It acknowledges a revision only when it still matches the revision processed, preserving later edits for the next batch.
## Error Handling & Edge Cases
- Lock contention and an empty queue are successful no-op outcomes.
- An embedding or search-index failure leaves pending revisions unchanged and releases exclusive access.
- The acknowledgement is revision-safe, so an edit made during processing is not lost.
- Kafka redelivery may start another batch, but the exclusive lock prevents overlapping processing.
## Quality & Consistency Notes
- Catalog state is authoritative; Qdrant is derived and may lag by up to one scheduled interval plus processing time.
- Batch size and scheduling bound the amount of concurrent embedding and search-index work.
- Revision matching provides eventual consistency without overwriting a newer catalog change.
---
title: Feedback and Rating Projection
summary: Propagating review changes to catalog ratings and compensating invalid references.
owners:
- catalog-experience-team
badges:
- content: Runtime Scenario
backgroundColor: purple
textColor: purple
---
Rating API owns individual feedback records, while Catalog API owns the derived average rating and review count. Feedback changes are published asynchronously so catalog reads remain independent of the review store.
## Purpose & Trigger
The flow creates or deletes a review and updates the corresponding catalog summary. It starts when a customer or administrator submits a feedback write.
## Visual References
_Feedback and Rating Projection_
## Step-by-Step Walkthrough
1. The caller submits feedback through API Gateway; Rating API validates and commits the change synchronously.
2. Rating API publishes a feedback-created or feedback-deleted fact asynchronously to Kafka.
3. Catalog API receives the event through its durable inbox and checks idempotency before processing it.
4. For an existing book, Catalog API recalculates the derived summary and updates the catalog record.
5. For a missing or deleted book, Catalog API publishes a failed-projection fact.
6. Rating API consumes the failure and deletes the invalid feedback record as compensation.
7. A feedback deletion follows the same event path and removes the review's contribution from the catalog summary.
## Error Handling & Edge Cases
- Duplicate events are ignored through durable inbox and idempotency guards.
- Temporary database or broker failures retry before exhausted events move to a dead-letter queue.
- Invalid book references trigger explicit compensation instead of a distributed transaction.
- Projection retries must be safe to repeat, especially when recalculating aggregate values.
## Quality & Consistency Notes
- Individual feedback is immediately available in Rating API; the catalog summary is eventually consistent.
- Catalog API can serve rating summaries without synchronously querying Rating API.
- Compensation preserves strict ownership when a review is no longer valid.
---
title: Conversational Book Discovery
summary: Routing, grounding, privacy, and response generation for a chat turn.
owners:
- ai-capabilities-team
badges:
- content: Runtime Scenario
backgroundColor: purple
textColor: purple
---
Chat API coordinates a synchronous, streaming conversation turn across routing, privacy, specialist agents, and read-only knowledge sources. It never mutates baskets or orders.
## Purpose & Trigger
The flow helps a customer discover books, answer store questions, or summarize ratings. It starts when Storefront sends an authenticated chat turn.
## Visual References
_Conversational Book Discovery_
## Step-by-Step Walkthrough
1. Storefront sends the turn through API Gateway. Chat API validates the caller and rate limit, loads session state, and rejects unsafe or oversized input.
2. Microsoft Foundry routing determines whether the request concerns a book, store policy, or rating and whether disambiguation is needed.
3. When intent is unclear, Chat API pauses and asks Storefront to collect a clarification. Execution resumes after the customer chooses an intended route.
4. For book or policy work, Chat API anonymizes outbound PII through Presidio and invokes the appropriate specialist and model.
5. Book specialists synchronously query MCP Tools for read-only catalog facts. The tools return grounded data from Catalog API.
6. Rating requests invoke the remote Rating API specialist synchronously over the agent interface.
7. Chat API checks tool permissions and applies response safeguards, formats the result, and persists the updated session.
8. The final response streams to Storefront over the conversation channel.
## Error Handling & Edge Cases
- Prompt validation and routing rejection short-circuit unsafe or out-of-scope turns.
- A stalled disambiguation remains bounded by workflow timeouts and conversation limits.
- MCP Tools or Rating API failures return a bounded workflow error rather than a mutation or fallback write.
- Model and tool outputs are checked for privacy and policy compliance before delivery.
## Quality & Consistency Notes
- Session data and conversation state are persisted separately from catalog and review state.
- Catalog and rating answers reflect live read boundaries at the time of the tool call.
- The flow is advisory: it cannot reserve inventory, change prices, or create commerce state.
---
title: Notification Delivery and Maintenance
summary: Email delivery attempts and scheduled platform maintenance.
owners:
- platform-engineering-team
badges:
- content: Runtime Scenario
backgroundColor: purple
textColor: purple
---
Notification delivers transactional email commands independently of order state, while Scheduler initiates recurring catalog and liveness work. Kafka redelivery and external SMTP acceptance are distinct reliability boundaries.
## Purpose & Trigger
The flow sends order email when Finance publishes a command and executes platform maintenance on schedule. Email and scheduled work are independent processes.
## Visual References
_Transactional Email Delivery_
_Scheduled Platform Maintenance_
## Step-by-Step Walkthrough
1. Finance publishes an order email command asynchronously and associates it with the order.
2. Kafka delivers the command to Notification. Notification claims a 24-hour idempotency key before processing.
3. A duplicate event identifier exits without rendering or sending email.
4. For a new identifier with a usable recipient, Notification renders the email and submits it through the protected SMTP path.
5. The SMTP relay's acceptance is a handoff result, not proof of mailbox delivery.
6. Scheduler persists scheduled jobs and starts them independently on their cron intervals.
7. The catalog batch job publishes an asynchronous trigger for Catalog Ingestion.
8. The heartbeat job records liveness independently of email delivery.
## Error Handling & Edge Cases
- Missing recipient addresses skip rendering and delivery.
- SMTP failures retry within a bounded resilience policy and release idempotency after an exhausted attempt.
- Kafka retries then route exhausted commands to the notification dead-letter queue.
- A newly reissued command with a new identifier may create a duplicate because broker delivery and Finance reissue semantics differ.
- Scheduler failure and email worker failure are observed independently.
## Quality & Consistency Notes
- Email delivery is at-least-once when failures or broker redeliveries occur.
- The idempotency key prevents exact redelivery duplicates for 24 hours.
- Scheduled work and inbox delivery may be healthy while search freshness or mailbox delivery is degraded.
---
title: Deployment View
summary: Hosting environments, infrastructure boundaries, and workload placement.
owners:
- platform-engineering-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
BookWorm is cloud-hosted in Azure, with external managed providers for messaging, vector search, and email; local development uses containerized services and emulators instead of most cloud dependencies. Development, Staging, and Production retain the same logical workload placement while varying capacity and resilience settings. This model supports independent application scaling, managed stateful services, identity-based access, and a lower-cost local workflow; it is not an on-premises or hybrid deployment.
## Chapter Contents
| View | Focus |
| :----------------------------------------------------------- | :------------------------------------------------------------------------- |
| [[doc\|arc42/07-deployment-view/001-infrastructure-level-1]] | Environment boundaries and placement of Section 5 building blocks |
| [[doc\|arc42/07-deployment-view/002-infrastructure-level-2]] | Selective detail of application ingress, compute, and operating boundaries |
---
title: Infrastructure Level 1
summary: Cloud environments, trust boundaries, and building-block placement.
owners:
- platform-engineering-team
badges:
- content: Deployment View
backgroundColor: blue
textColor: blue
---
## Overview and Motivation
Azure deployments place application workloads in Azure Container Apps and stateful dependencies in Azure-managed services, with Confluent Cloud, Qdrant Cloud, SendGrid, and Microsoft Entra ID as separate service boundaries. Local development substitutes persistent containers and emulators for most managed resources. The environments preserve logical topology but use different capacity and resilience settings, balancing operability and security with development cost.
## Production Infrastructure Topology
The view emphasizes environment and service boundaries. The mapping below provides the per-building-block placement, scaling, and security detail.
## Building Block to Infrastructure Mapping
| Infrastructure Node | Hosted Building Blocks (from Sec 5) | Scaling & Availability | Key Security / Network Boundary |
| :---------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------- |
| Azure Container Apps public ingress | API Gateway; Scheduler's Quartz Dashboard | Gateway and dashboard are separate apps; the published baseline declares a minimum of one replica but no maximum or application-specific scale rules; deployed values are unverified | HTTPS from the public network; dashboard access is protected by Microsoft Entra ID and the `admin` role |
| Azure Container Apps internal workloads | Storefront, Commerce, Backoffice; Catalog API, Catalog Ingestion, Basket API, Ordering API, Finance, Rating API, Chat API, MCP Tools, Notification, Scheduler; Presidio supports Chat API and Rating API | Consumption profile; workload limits and capacity targets remain to be defined; no multi-region application deployment is established | Internal app ingress is not public ingress; it does not imply a VNet or private endpoint boundary |
| Azure PostgreSQL Flexible Server | Catalog API, Ordering API, Scheduler | Development uses a smaller tier without zone redundancy; Staging and Production use zone-redundant HA with 14- and 35-day backups respectively | Service-scoped identity and encrypted connections; production geo-redundant backup is enabled |
| Azure Managed Redis and Azure Cosmos DB | Redis: Catalog API, Basket API, Ordering API, Rating API, Notification; Cosmos DB: Rating API | Redis HA is enabled in Staging and Production; Cosmos DB is serverless in Development and Staging, provisioned in Production | Azure workload identity and role-based access; Cosmos local authentication is disabled outside Development |
| Azure Storage and Durable Task Scheduler | Storage: Catalog API, Catalog Ingestion, Chat API, Finance; Durable Task Scheduler: Finance | Storage redundancy increases from locally redundant in Development to zone-redundant in Staging and geo-zone-redundant in Production; task scheduler uses Consumption tier | Private data is not publicly anonymous; access uses scoped identity roles. Private endpoints are not currently declared |
| Microsoft Foundry | Catalog API, Catalog Ingestion, Chat API, Rating API | Model capacity and regional availability depend on provider deployment quotas | Azure role-based access from workload identities; model endpoints remain a managed-service boundary |
| External providers: Confluent Cloud, Qdrant Cloud, SendGrid | Kafka integrations across Catalog, Shopping, Ordering, Reviews, and Platform; Qdrant for Catalog; SMTP for Notification | Provider availability and quotas are external dependencies; recovery and failover are provider-specific | Separate provider trust boundary; encrypted connections and protected connection credentials |
| Azure Container Registry and Log Analytics | Images and operational telemetry for the hosted Section 5 building blocks | Log retention is 30 days in non-Production and 90 days in Production; registry and workspace service limits apply | Azure control-plane access and scoped workload permissions |
| Microsoft Entra ID | User authentication for customer and staff applications; managed identities and agent identities for service access | Identity availability and token lifetimes follow tenant configuration | Tenant and token-validation boundary; OIDC for users and workload identity for Azure resource access |
## Quality and Operational Characteristics
- API Gateway is the customer-facing application entry point. Quartz Dashboard is a separate externally reachable administrative endpoint protected by Microsoft Entra ID; other application ingress is internal to the Container Apps environment.
- User authentication uses Microsoft Entra ID. Workloads use managed identities and scoped roles for Azure resources; external provider connections use encrypted transport and protected credentials.
- PostgreSQL has zone-redundant HA in Staging and Production, with 14- and 35-day backup retention; Production enables geo-redundant backups. Redis HA is enabled in those environments. Multi-region application recovery is not established.
- The published Container Apps baseline does not define workload-specific maximum replicas or scale triggers. Capacity limits, traffic targets, and recovery objectives must be established before production commitments, and deployed settings must be verified.
- Internal ingress describes application routing, not network isolation: no VNet or private endpoints are currently declared for managed dependencies.
## Related Views
- [[doc\|arc42/05-building-block-view]] — Static ownership of the hosted building blocks.
- [[doc\|arc42/06-runtime-view]] — Interactions between building blocks.
- [[doc\|arc42/07-deployment-view/002-infrastructure-level-2]] — Selective compute and ingress detail.
---
title: Infrastructure Level 2
summary: Selective detail of application hosting, ingress, and operational boundaries.
owners:
- platform-engineering-team
badges:
- content: Deployment View
backgroundColor: blue
textColor: blue
---
## Scope and Rationale
The Azure Container Apps environment hosts the public gateway, the internal application tier, and event-triggered workers, making its ingress and scaling boundaries significant to availability and security. This view distinguishes external endpoints from internal app routing and managed dependencies without implying private network isolation that is not configured.
## Application Runtime Environment
The view highlights the public gateway and administrative endpoint, representative internal services and workers, and their primary data, identity, search, and messaging dependencies. The table maps all hosted workloads and protocols, including those omitted from the visual for legibility.
## Internal Infrastructure Elements
| Node / Component | Role | Hosted Artifacts / Workloads | Networking / Ports / Protocols |
| :------------------------------- | :----------------------------------------------------------------- | :---------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------- |
| Azure Container Apps environment | Runs application workloads on the Consumption profile | API Gateway, frontends, APIs, workers, and privacy services | Managed container ingress; inter-app HTTP and gRPC as required by service contracts |
| External application ingress | Accepts customer and administrative traffic | API Gateway; Scheduler's Quartz Dashboard | HTTPS from the public network; published gateway target port is 5000 (deployed value unverified); dashboard uses OIDC and the `admin` role |
| Internal web applications | Hosts customer and staff experiences behind the gateway | Storefront, Commerce, Backoffice | Internal HTTP; application target port 3000 |
| Internal capability APIs | Serves capability endpoints and service-to-service contracts | Catalog API, Basket API, Ordering API, Rating API, Chat API | Internal HTTP and gRPC; no public ingress |
| Internal tool endpoint | Provides catalog tools to authorized internal callers | MCP Tools | Internal HTTP at `/mcp`; not routed through API Gateway; origin policy is enforced separately |
| Function and worker applications | Runs asynchronous, scheduled, and triggered work | Finance, Catalog Ingestion, Notification, Scheduler | Kafka, storage, and durable-task connections as applicable; no public business endpoint |
| Privacy services | Provides PII detection and anonymization to dependent applications | Presidio analyzer and anonymizer | Internal HTTP on port 3000 |
| Environment support services | Supplies image distribution and centralized diagnostics | Azure Container Registry; Log Analytics workspace | Azure service endpoints; telemetry retention is 30 days outside Production and 90 days in Production |
| Identity boundary | Authenticates users and grants scoped Azure resource access | Microsoft Entra ID, managed identities, agent identities | OIDC for user sign-in; workload identity and role-based access for Azure resources |
## Resilience and Operational Notes
- **Autoscaling:** The published baseline specifies a minimum of one replica but does not define workload-specific maximum replicas or scaling triggers. Confirm deployed values and establish limits and scale signals from HTTP load, CPU, and broker lag before production capacity commitments.
- **Health checks:** Workloads expose health or liveness endpoints where applicable. Verify readiness probes and promotion criteria per app; endpoint availability alone does not establish deployment health.
- **Rollouts:** The published baseline describes single-revision mode and defines no canary or blue/green traffic-splitting strategy. Verify deployed revision behavior; do not assume zero-downtime releases without validated rollout and rollback procedures.
- **Failure isolation:** Separate apps isolate process failures, but they share an environment and Azure region. Managed databases, messaging, AI, and external providers remain independent availability dependencies.
- **Network boundary:** Gateway and admin UI are externally reachable; business workloads use internal ingress. Internal ingress is not a private subnet, and private endpoints or a VNet perimeter are not currently declared.
---
title: Crosscutting Concepts
summary: Shared security, integration, resilience, observability, AI governance, and verification practices across BookWorm.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
These concepts establish conceptual integrity and uniform rules across every building block. They define the minimum trust, compatibility, failure, diagnostic, and delivery expectations that domain-specific designs and runtime scenarios must satisfy.
## Concept Index
| Concept | Core Rule / Principle | Affected Building Blocks | Related ADRs / Quality Goals |
| :--------------------------------------------------------------------------- | :---------------------------------------------------------------------------------- | :------------------------------------------------------------ | :------------------------------------------ |
| [[doc\|arc42/08-crosscutting-concepts/001-security-and-privacy]] | Authenticate every trust boundary; authorize explicitly; minimize and protect data. | Edge and frontends, capability APIs, AI workflows, operations | Identity, data protection, confidentiality |
| [[doc\|arc42/08-crosscutting-concepts/002-contracts-and-messaging]] | Communicate through owned, versioned contracts and tolerate at-least-once delivery. | Every capability, integration edge, messaging infrastructure | Interoperability, evolvability, reliability |
| [[doc\|arc42/08-crosscutting-concepts/003-validation-errors-and-resilience]] | Reject invalid work at boundaries and bound all retryable operations. | Public APIs, workers, external integrations | Robustness, availability, recoverability |
| [[doc\|arc42/08-crosscutting-concepts/004-observability]] | Produce correlated telemetry and prove health from signals, not assumptions. | Frontends, APIs, workers, AI and data pipelines | Traceability, operability, diagnosability |
| [[doc\|arc42/08-crosscutting-concepts/005-ai-governance]] | Apply privacy, policy, identity, and human decision controls before AI actions. | Conversational discovery, review intelligence, tool catalog | Responsible AI, privacy, human oversight |
| [[doc\|arc42/08-crosscutting-concepts/006-testing-and-change-safety]] | Require evidence from every change and make releases reversible. | Shared foundations, every capability, frontends | Testability, deployability, change safety |
Shared mechanisms are defaults, not implicit guarantees. A team must explicitly register and
verify every control on the host or boundary that uses it.
## Conceptual Integrity Rules
1. **Preserve domain ownership.** A shared library may provide technical primitives, but it must not own business data or replace an authoritative capability.
2. **Separate acknowledgment from completion.** A successful network call or broker acceptance proves only that the handoff occurred, not that downstream work finished correctly.
3. **Design for explicit opt-in.** Identity, resilience, privacy, and governance behavior must be visible in service configuration and tested at the relevant boundary.
4. **Prefer reversible evolution.** Additive contract changes, staged rollouts, and retained observability reduce the cost of a correction.
## Related Views
- [[doc|arc42/05-building-block-view]] — Building-block ownership and boundaries.
- [[doc|arc42/06-runtime-view]] — End-to-end interactions governed by these concepts.
- [[doc|arc42/09-architecture-decisions]] — Decisions that constrain these policies.
---
title: Security and Privacy
summary: Identity, authorization, and sensitive-data protections at BookWorm's API, AI, and logging boundaries.
owners:
- platform-engineering-team
badges:
- content: Cross-cutting Concept
backgroundColor: purple
textColor: purple
---
## Purpose and Scope
Security and privacy govern every entry point, delegated identity, internal service call, and external model or tool integration. These rules protect customer, staff, operational, and AI-processing data while allowing independent teams to own and evolve their capabilities.
## Visual Reference
**Security and Trust Boundaries**
## Core Rules and Standards
1. **Use one identity authority.** Human users authenticate through the approved identity provider, and public APIs validate signed access tokens before authorization.
2. **Authorize at every protected boundary.** Combine authenticated identity, required roles, and operation-specific permissions; do not rely on network placement as authorization.
3. **Apply least privilege.** Grant the smallest role, scope, data access, model capability, and tool permission needed for a declared purpose.
4. **Propagate identity safely.** Forward verified claims only through explicit security and trace metadata; never copy identity values into application authorization decisions by themselves.
5. **Keep secrets out of code and logs.** Use managed identities or short-lived credentials for hosted integrations, and prohibit credentials and raw customer payloads in telemetry.
6. **Minimize and classify sensitive data.** Collect only required PII, apply classification consistently, and anonymize or redact it before model, log, support, or export boundaries.
7. **Deny unsafe AI actions by default.** AI agents may call only explicitly allowed tools and may not substitute conversational confidence for authorization.
The presence of a shared authentication or redaction helper is not evidence that a service enabled
it. Each host and endpoint must register and verify the controls required for its trust boundary.
## Mechanism / How It Works
| Boundary | Standard Pattern | Expected Outcome |
| :--------------------------- | :--------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------ |
| Public user ingress | Authenticate the user, validate issuer and audience, then evaluate role and operation policy | Unauthenticated callers receive a denied response; authorized callers receive only permitted operations |
| API-to-API calls | Propagate verified caller context and use least-privilege service identity for infrastructure access | Internal calls remain attributable and cannot bypass endpoint policy |
| Agent-to-agent calls | Use federated workload identity and claims-based isolation | Each agent acts only for the authorized workload and user context |
| Sensitive field handling | Classify data, redact structured logs, and avoid serializing raw command or response values | Support and telemetry remain useful without exposing customer secrets |
| AI model and tool boundaries | Screen input, anonymize PII, isolate untrusted content, and enforce deny-by-default policies | Unsafe prompts, tools, or data are rejected before side effects occur |
## Threat Considerations
| Concern | Required Mitigation |
| :----------------------------- | :--------------------------------------------------------------------------------------------------- |
| Spoofing or stolen credentials | Validate signatures, issuer, audience, lifetime, and required claims; prefer short-lived credentials |
| Payload or prompt tampering | Validate inputs, separate instruction data from untrusted content, and verify tool schemas |
| Unauthorized actions | Enforce endpoint and tool policies independently of UI state |
| Data disclosure | Minimize PII, redact logs, mask model prompts and results, and restrict storage or exports |
| Abuse and denial of service | Apply per-source and per-user limits to expensive endpoints and model workflows |
| Agent privilege escalation | Bind sessions to caller claims and require explicit allow rules for tools and mutations |
## Verification and Governance
- Review the role, scope, resource, and secret requirements for every new endpoint, worker, model, or agent.
- Exercise unauthorized, expired, malformed, and over-privileged requests in automated tests.
- Audit secret, PII, and prompt handling; verify managed credentials and log redaction in deployed environments.
- Treat a control as compliant only after runtime registration and an effective policy decision are demonstrated.
## Related Documentation
- [[doc|arc42/08-crosscutting-concepts/005-ai-governance]] — AI screening, policy, and human-oversight controls.
- [[doc|platform/004-identity-and-rbac-matrix]] — Identity and infrastructure permission assignments.
- [[doc|operational/004-security-hardening-checklist]] — Production security verification.
---
title: Contracts and Messaging
summary: Owned APIs and events connect independently maintained BookWorm capabilities without sharing business state.
owners:
- platform-engineering-team
badges:
- content: Cross-cutting Concept
backgroundColor: purple
textColor: purple
---
## Purpose and Scope
Contracts and messaging preserve service autonomy by preventing cross-service data access and making every interaction explicit. They govern synchronous APIs, AI and tool protocols, integration events, and the durability assumptions of asynchronous delivery across all capabilities.
## Visual Reference
**Contract and Delivery Pipeline**
## Core Rules and Standards
1. **Keep data ownership local.** No capability reads or writes another capability's authoritative store.
2. **Use the owned contract.** REST, gRPC, AI tool, agent, or event schemas belong to the owner and must describe stable externally visible behavior.
3. **Version compatibility explicitly.** Prefer additive evolution and backward-compatible defaults; treat renaming or removing fields and changing semantics as breaking changes.
4. **Carry meaningful envelope metadata.** Include message identity, event type and version, source, correlation, trace context, and causation where applicable.
5. **Treat delivery as at least once.** Consumers must tolerate duplicates, retries, restart recovery, and out-of-order work unless a documented protocol provides stronger guarantees.
6. **Make side effects idempotent.** Use stable operation or event identifiers to detect duplicate execution and verify authoritative state before compensating.
7. **Route exhausted work safely.** Retry only bounded, classified failures and isolate poison or permanently invalid records for review.
Schema compatibility is necessary but not sufficient. A field-compatible change can still break a
consumer if names, units, meaning, ordering, or ownership semantics change.
## Mechanism / How It Works
| Contract Type | Standard | Evolution Rule |
| :----------------------- | :------------------------------------------------------------------------------------ | :----------------------------------------------------------------------------------------- |
| HTTP | Versioned resources and explicit media behavior | Add optional fields and endpoints; retire old behavior through a published transition |
| gRPC | Stable typed schemas and validated operations | Use schema compatibility checks and avoid renaming or repurposing fields |
| Agent and tool protocols | Authenticated, least-privilege operations with machine-readable schemas | Change permissions or tool behavior only through reviewed policy and consumer updates |
| Integration events | Immutable intent, stable event identity, and self-contained enough data for consumers | Add fields without changing existing meaning; publish new event types for semantic changes |
## Messaging Pipeline
| Stage | Responsibility |
| :-------- | :-------------------------------------------------------------------------------------------------------------- |
| Publish | Validate and serialize from the owner; assign message identity and correlation |
| Transport | Preserve envelope metadata and delivery acknowledgement |
| Persist | Select outbox, inbox, or idempotency storage according to durability and duplicate needs |
| Consume | Validate compatibility, enforce authorization, execute idempotently, and commit state atomically where possible |
| Fail | Classify transient, permanent, and poison failures; retry transient work; route exhausted work for inspection |
## Verification and Governance
- Run consumer and provider contract checks before merging contract changes.
- Verify additive and breaking schema changes against published baselines.
- Test duplicate delivery, replay, missing metadata, partial commit, and exhausted retries.
- Confirm production partitioning, retention, access, and replay ownership with the broker operator.
- Document event semantics and business effects, not only payload shape.
## Related Documentation
- [[doc|platform/006-api-and-contracts]] — Contract inventory.
- [[doc|arc42/08-crosscutting-concepts/006-testing-and-change-safety]] — Contract and compatibility gates.
- [[doc|arc42/08-crosscutting-concepts/003-validation-errors-and-resilience]] — Failure and retry standards.
---
title: Validation, Errors, and Resilience
summary: Shared request validation, HTTP error mapping, and capability-specific retry and duplicate-request behavior.
owners:
- platform-engineering-team
badges:
- content: Cross-cutting Concept
backgroundColor: purple
textColor: purple
---
## Purpose and Scope
Validation, error handling, and resilience protect public and internal boundaries from malformed work, overload, partial failure, and repeated delivery. These rules apply to HTTP and RPC endpoints, message consumers, external calls, schedulers, and workflows across every building block.
## Visual Reference
**Request Validation and Recovery**
## Core Rules and Standards
1. **Validate at the trust boundary.** Reject malformed shape, ranges, identities, required fields, and authorization state before domain execution.
2. **Use a stable error contract.** Return machine-readable problem details with type, status, title, detail, instance, and correlation without exposing stack traces or secrets.
3. **Separate expected and unexpected failures.** Validation and not-found conditions are caller errors; conflicts represent state; unhandled faults indicate incidents.
4. **Bound overload controls.** Limit concurrency and request rate per source or user and shed work with a retry hint where appropriate.
5. **Make mutations retry-safe.** Require an operation identifier for duplicate-sensitive writes and retain intent until the authoritative outcome is known.
6. **Classify retries.** Retry only bounded transient faults; never retry validation, authorization, permanent deserialization, or destructive ambiguous work automatically.
7. **Compensate or confirm.** After a timeout or partial failure, verify authoritative state or execute an explicitly approved compensating action.
A retry, acknowledgement, or successful transport call does not prove business completion.
Consumers and callers must verify final state or receive a durable outcome.
## Mechanism / How It Works
| Condition | Standard Response |
| :------------------------------------ | :------------------------------------------------------------------------------------- |
| Invalid input | Return 400 with field-level or operation-level problem details |
| Unauthenticated or forbidden | Return 401 or 403 without leaking protected resource details |
| Missing resource | Return 404 unless availability concealment is an explicit policy |
| State conflict or duplicate operation | Return 409 or the standard precondition response and preserve the existing state |
| Preconditions not met | Return 412 and direct the caller to refresh the authoritative version |
| Capacity exceeded | Return 429 with retry guidance |
| Unexpected fault | Return 500 or 503 with correlation; log full diagnostics only inside protected systems |
## Resilience Pattern
| Step | Rule |
| :---------- | :----------------------------------------------------------------------------------- |
| Admission | Enforce transport limits and request or user quotas |
| Idempotency | Create or confirm the operation key before executing side effects |
| Validation | Run schema and domain preconditions before persistence |
| Execution | Apply operation-specific timeouts and cancellation |
| Retry | Use bounded attempts, jitter, and backoff for classified transient faults |
| Containment | Use circuit-breaking or fail-fast behavior to protect downstream dependencies |
| Recovery | Reconcile, replay, compensate, or escalate according to the capability's state model |
## Verification and Governance
- Test invalid, unauthorized, duplicate, concurrent, timed-out, and unavailable-dependency cases.
- Verify that 429 responses include retry guidance and that retries do not amplify load.
- Confirm idempotency keys are removed or released only after a safe retry outcome.
- Require a final-state check or compensation test for every distributed mutation.
## Related Documentation
- [[doc|arc42/08-crosscutting-concepts/002-contracts-and-messaging]] — Delivery guarantees and envelope handling.
- [[doc|arc42/08-crosscutting-concepts/004-observability]] — Trace and error correlation.
- [[doc|arc42/06-runtime-view]] — End-to-end exception and compensation scenarios.
---
title: Observability
summary: Shared structured logging, OpenTelemetry signals, and health checks support diagnosis across BookWorm services.
owners:
- platform-engineering-team
badges:
- content: Cross-cutting Concept
backgroundColor: purple
textColor: purple
---
## Purpose and Scope
Observability provides a consistent evidence model for diagnosing frontends, APIs, workers, data pipelines, and external dependencies. It governs signal names, correlation, privacy, health semantics, and retention across all deployed building blocks.
## Visual Reference
**Observability Pipeline**
## Core Rules and Standards
1. **Propagate one correlation chain.** Carry trace, request, and operation identifiers across HTTP, RPC, events, and scheduled work.
2. **Emit structured data.** Use stable field names and structured attributes; avoid embedding sensitive or variable narrative into identifiers.
3. **Capture the three signals.** Distributed traces explain causality, logs explain local events, and metrics quantify behavior and failure rates.
4. **Protect telemetry data.** Apply PII and secret redaction before export; do not place payloads or credentials into trace attributes.
5. **Instrument dependencies consistently.** Cover inbound, outbound, database, broker, cache, external AI, and health interactions according to the capability boundary.
6. **Separate liveness and readiness.** Liveness identifies an unusable process; readiness identifies whether the process can serve required work.
7. **Use health as a contract.** Every probe must test a meaningful dependency or process state and avoid cascading load into external systems.
Telemetry proves that an operation or step occurred. It does not prove that an asynchronous
business outcome completed; final state must be reconciled through the owning capability.
## Mechanism / How It Works
| Signal | Minimum Convention |
| :----- | :-------------------------------------------------------------------------------------------------------------------- |
| Trace | One request or operation ID chain across synchronous and asynchronous hops; include outcome and dependency attributes |
| Log | Timestamp, severity, component, trace and correlation IDs, event reason, and redacted operation context |
| Metric | Stable service and operation names; success, failure, latency, saturation, and retry or queue indicators |
| Health | Explicit liveness and readiness checks, environment-aware probe endpoints, and dependency timeout bounds |
## Correlation and Privacy
- Generate or preserve a correlation identifier at the external ingress boundary.
- Forward that identifier in downstream calls and integration envelopes.
- Include the same identifier in user-visible error details only when safe to do so.
- Record entity identifiers and operation names when useful, but do not log raw prompts, secrets, payment details, or full customer payloads.
- Route sensitive or high-volume diagnostic context through the same redaction and retention controls as other telemetry.
## Verification and Governance
- Test that end-to-end traces survive frontend, gateway, API, worker, and broker hops.
- Verify metric cardinality and ensure untrusted values cannot create unbounded label sets.
- Alert on symptom indicators such as error rate and latency, then diagnose with correlated traces and logs.
- Review probe behavior and telemetry retention for each environment before release.
## Related Documentation
- [[doc|operational/002-observability-and-diagnostics]] — Operational dashboards and diagnostic procedures.
- [[doc|arc42/08-crosscutting-concepts/001-security-and-privacy]] — Redaction and PII boundaries.
- [[doc|arc42/08-crosscutting-concepts/003-validation-errors-and-resilience]] — Error and retry behavior.
---
title: AI Governance
summary: Input screening, privacy middleware, policy enforcement, and tool boundaries for BookWorm's AI workflows.
owners:
- ai-capabilities-team
badges:
- content: Cross-cutting Concept
backgroundColor: purple
textColor: purple
---
## Purpose and Scope
AI governance constrains prompts, models, agents, tool calls, and generated results across conversational discovery, review intelligence, and tool catalog capabilities. It applies wherever user text or external content crosses a model boundary or can trigger a state-changing action.
## Visual Reference
**AI Governance Guardrails**
## Core Rules and Standards
1. **Screen before routing.** Validate prompt shape, length, language, domain scope, and known injection patterns before invoking a specialist agent or tool.
2. **Protect PII at model boundaries.** Anonymize sensitive data before external model calls and remove or redact sensitive content in returned results.
3. **Isolate untrusted content.** Treat prompts, retrieved passages, tool output, and external documents as untrusted data rather than instructions.
4. **Apply deny-by-default policies.** Every agent and tool must declare an allow rule; mutations and destructive operations require a specific policy grant.
5. **Bind actions to identity.** Session state and tool authorization must remain tied to authenticated caller claims and approved workload identity.
6. **Require human review for ambiguity.** Low-confidence or out-of-domain requests pause for clarification instead of guessing or escalating privilege.
7. **Record consequential decisions.** Preserve policy outcome, model and tool identifiers, correlation, redaction status, and human disposition for auditable events.
Prompt screening and PII detection reduce risk but do not guarantee safety. Novel prompt attacks,
detector bypasses, or policy gaps require a human review and rapid rollback mechanism.
## Mechanism / How It Works
| Governance Stage | Required Behavior |
| :---------------- | :------------------------------------------------------------------------------------ |
| Input admission | Reject malformed, oversized, unsafe, or out-of-scope requests |
| Context isolation | Mark external text and tool output as data, never instructions |
| Privacy | Anonymize PII and minimize retained conversation and prompt content |
| Routing | Classify purpose and domain before selecting an agent or model |
| Policy | Evaluate tool and operation permissions with deny-overrides semantics |
| Execution | Use least-privilege tools, bounded retries, and session isolation |
| Review | Escalate ambiguity, policy conflicts, or consequential actions to a responsible human |
## Evaluation and Fallback
- Evaluate prompt safety, domain classification, PII detection, tool authorization, output quality, and refusal behavior.
- Use deterministic tests for policy allow/deny decisions and adversarial tests for prompt and tool poisoning patterns.
- Fall back to a safe clarification or human handoff when routing confidence is low or policy state is uncertain.
- Disallow silent retries that change policy scope or expand tool permissions.
- Maintain an approved model, prompt, policy, and tool baseline for every release.
## Verification and Governance
- Test allow, deny, rate-limit, prompt-injection, PII, circuit-breaker, and human-handoff cases for every agent or tool change.
- Review policy coverage when a model or integration gains new data or mutation access.
- Verify that policy files and identity bindings load at runtime, not only during development.
- Define rollback criteria for quality regressions, privacy incidents, elevated false refusal rates, or unexpected tool use.
## Related Documentation
- [[doc|arc42/08-crosscutting-concepts/001-security-and-privacy]] — Identity and PII boundaries.
- [[doc|arc42/06-runtime-view/004-conversational-book-discovery]] — Conversational decision and tool flow.
- [[doc|misc/001-ms-decisions-model-use-case-and-lessons-learned]] — Model-routing rationale.
---
title: Testing and Change Safety
summary: Layered tests and schema checks protect BookWorm behavior, service boundaries, and contract compatibility.
owners:
- architecture-enabling-team
badges:
- content: Cross-cutting Concept
backgroundColor: purple
textColor: purple
---
## Purpose and Scope
Testing and change safety establish evidence that code, contracts, policies, data effects, and user journeys remain acceptable from development through release. These rules apply to shared foundations and every frontend, API, worker, event, integration, and AI boundary.
## Visual Reference
**Verification and Release Gates**
## Core Rules and Standards
1. **Test at the lowest useful boundary.** Use fast unit and component tests for local behavior and raise the test level only for interaction or deployment evidence.
2. **Verify contracts independently.** Providers and consumers must prove compatibility for APIs and event schemas before deployment.
3. **Protect architectural boundaries.** Automated checks must prevent forbidden dependencies and preserve capability ownership.
4. **Test behavior, not implementation.** Assert domain outcomes, observable API effects, access decisions, and recoverable failure behavior.
5. **Require quality gates.** Formatting, static analysis, tests, security checks, contract checks, and documentation checks must pass before promotion.
6. **Make releases reversible.** Deploy behind feature or traffic controls when rollback or staged observation is useful.
7. **Use explicit rollback criteria.** A release halts or rolls back for health, error, latency, security, privacy, contract, or business-signal breaches agreed by the owner.
A green build proves only the evidence it exercises. Critical compatibility, privacy, migration,
and rollout risks require targeted tests or a documented human release gate.
## Mechanism / How It Works
| Layer | Primary Evidence |
| :----------- | :----------------------------------------------------------------------------------------------- |
| Unit | Domain rules, validation, state transitions, pure transformations, and failure classification |
| Component | UI behavior, endpoint behavior, handler behavior, policy decisions, and data access boundaries |
| Integration | Real interactions among a host and its database, broker, cache, identity, or external dependency |
| Contract | Consumer/provider compatibility for HTTP, RPC, events, AI tools, and message envelopes |
| End-to-end | Critical journeys across frontends, gateways, capabilities, and asynchronous completion |
| Architecture | Dependency direction, domain isolation, forbidden references, and infrastructure conventions |
## Verification and Release Gates
Run focused tests and formatting or static checks while code is still under development.
Run the relevant unit, contract, architecture, integration, and user-flow checks for the changed
boundary.
Require security, privacy, schema, coverage, migration, and quality checks to pass before
deployment.
Deploy incrementally, observe health and business signals, and retain the previous reversible
artifact.
Promote when agreed criteria hold; halt or roll back when a breach is detected or the outcome
cannot be verified.
## Rollout and Rollback Criteria
| Concern | Promote When | Roll Back or Halt When |
| :------------------- | :------------------------------------------------------------- | :------------------------------------------------------------------------ |
| Availability | Readiness and liveness remain stable at the approved threshold | Health probes fail or traffic sheds unexpectedly |
| Latency and errors | Error and latency budgets remain within release limits | Sustained breaches correlate with the change |
| Contracts | Consumers pass compatibility checks and replay remains safe | Additive or breaking incompatibility appears |
| Privacy and security | Policy tests pass and no secrets or PII leak is detected | Unauthorized access, PII exposure, or policy bypass occurs |
| Business outcome | Authoritative state and key journeys complete correctly | Reconciliation gaps, duplicate side effects, or incorrect outcomes appear |
## Verification and Governance
- Map each shared library or boundary change to its owning test layer and contract.
- Keep known gaps explicit and prioritize them with release risk.
- Review failed, flaky, or skipped tests as release evidence, not merely CI noise.
- Retain rollback evidence and operational criteria with every promoted release.
## Related Documentation
- [[doc|development/005-testing]] — Test commands and focused execution.
- [[doc|development/008-testing-matrix]] — Framework and coverage details.
- [[doc|development/006-pull-request-process]] — Pull-request and review requirements.
---
title: Architecture Decisions
summary: Navigable register of whole-system and capability-specific architecture decisions.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
This chapter is the navigation index for BookWorm's Architecture Decision Records (ADRs). It links to each decision's canonical record so readers can review its context, alternatives, outcome, consequences, and current status without duplicating that rationale here.
The status and rationale in each linked ADR are authoritative. Treat a decision marked
**Superseded** as historical and follow its replacement when one is identified by the record.
## Governance
- **Whole-system decisions** establish principles that apply across multiple capabilities.
- **Capability-specific decisions** describe choices owned by a particular system or integration.
- **Preserve decision history.** When a material decision changes, record the new context and outcome and link it to the decision it replaces; do not silently rewrite the earlier rationale.
- **Keep rationale canonical.** This index provides navigation and scope, while each ADR remains the source of its own details and lifecycle status.
- **Review compatibility.** Before applying a decision, check its scope, status, related decisions, and stated consequences.
## Whole-System Decisions
| ADR | Decision | Primary consideration |
| :-------------------------------------------------------- | :----------------------------------------------------------------------- | :-------------------------------------------------------------------------- |
| [[adr\|adr-bw-001-capability-aligned-boundaries]] | Organize the system around business capabilities and bounded contexts. | Clear ownership and independent change versus cross-capability coordination |
| [[adr\|adr-bw-002-dotnet-platform-foundation]] | Establish a consistent backend platform foundation. | Ecosystem consistency versus coordinated upgrades |
| [[adr\|adr-bw-003-aspire-shared-service-defaults]] | Standardize hosting and shared service defaults. | Consistent operations versus shared-change impact |
| [[adr\|adr-bw-004-explicit-http-and-grpc-contracts]] | Use explicit, versioned synchronous service contracts. | Interoperability versus contract maintenance |
| [[adr\|adr-bw-005-kafka-integration-backbone]] | Use asynchronous event exchange for decoupled collaboration. | Reduced coupling versus broker operations and eventual consistency |
| [[adr\|adr-bw-006-service-owned-business-state]] | Keep authoritative business data with its owning capability. | Data autonomy versus cross-boundary composition |
| [[adr\|adr-bw-007-derived-eventually-consistent-views]] | Build derived read models separately from authoritative state. | Read scalability versus propagation delay |
| [[adr\|adr-bw-008-durable-message-handoffs]] | Select durable handoff and duplicate-control mechanisms by need. | Recoverable delivery versus operational complexity |
| [[adr\|adr-bw-009-local-cqrs-building-blocks]] | Use local request and handler patterns within capability boundaries. | Explicit flow and consistency versus additional structure |
| [[adr\|adr-bw-010-cross-boundary-correlation]] | Carry correlation context across synchronous and asynchronous work. | End-to-end diagnosis versus sensitive-data exposure |
| [[adr\|adr-bw-011-shared-validation-and-error-contracts]] | Standardize validation and machine-readable error behavior. | Predictable clients versus host-specific registration |
| [[adr\|adr-bw-012-operation-aware-resilience]] | Apply bounded resilience according to operation semantics. | Fault tolerance versus duplicate or amplified side effects |
| [[adr\|adr-bw-013-opentelemetry-observability]] | Standardize distributed traces, metrics, and structured logs. | Consistent diagnosis versus sampling and retention cost |
| [[adr\|adr-bw-014-composable-ai-governance]] | Layer identity, privacy, policy, and tool controls on AI workflows. | Safer AI execution versus policy maintenance |
| [[adr\|adr-bw-015-explicit-environment-configuration]] | Separate logical system design from environment-specific settings. | Environment consistency versus deployment-specific variation |
| [[adr\|adr-bw-016-layered-architecture-verification]] | Use multiple verification layers to protect change safety. | Broad evidence versus test execution cost |
| [[adr\|adr-bw-017-compatible-contract-evolution]] | Evolve contracts with compatibility checks and staged changes. | Independent releases versus coordinated breaking changes |
| [[adr\|adr-bw-018-single-source-decision-documentation]] | Maintain one canonical record for each architecture decision. | Decision traceability versus duplicated rationale |
| [[adr\|adr-bw-019-polyglot-persistence-strategy]] | Match PostgreSQL, Cosmos DB, Redis, and Qdrant to capability needs. | Workload fit versus multi-engine operational overhead |
| [[adr\|adr-bw-020-durable-functions-order-saga]] | Coordinate checkout sagas with Azure Durable Functions keyed by OrderId. | Explicit compensation visibility versus Functions host runtime coupling |
| [[adr\|adr-bw-021-presidio-sidecar-pii-redaction]] | Enforce fail-closed PII redaction via the Presidio API sidecar. | Centralized NLP privacy controls versus extra internal hop latency |
| [[adr\|adr-bw-022-unprefixed-scheduler-vector-topic]] | Keep `scheduler.process-vector-batch` unprefixed across environments. | Binding stability versus per-environment Kafka cluster isolation |
| [[adr\|adr-bw-023-nextjs-multizone-gateway-routing]] | Compose storefront apps as Next.js multi-zones behind the gateway. | Independent frontend releases versus coordinated gateway routing |
## Capability and Integration Decisions
Each entry links directly to its ADR resource. Read the record for its scope, status, rationale, and links to related decisions.
| Area | Decisions |
| :----------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Catalog** | - [[adr\|adr-001-postgresql-system-of-record]]
- [[adr\|adr-002-hybrid-vector-search-qdrant]]
- [[adr\|adr-003-database-queue-for-vector-indexing]]
- [[adr\|adr-004-fusioncache-redis-for-catalog-reads]]
- [[adr\|adr-005-blob-storage-for-book-images]]
- [[adr\|adr-006-reviews-rating-projection-on-book]]
|
| **Shopping — Basket** | - [[adr\|adr-001-redis-authoritative-basket-store]]
- [[adr\|adr-002-customer-scoped-basket-ownership]]
- [[adr\|adr-003-replace-basket-items-as-a-set]]
- [[adr\|adr-004-catalog-enrichment-at-read-time]]
- [[adr\|adr-005-explicit-checkout-cleanup-outcomes]]
|
| **Ordering — Orders** | - [[adr\|adr-001-postgresql-order-system-of-record]]
- [[adr\|adr-002-preserve-checkout-purchase-snapshot]]
- [[adr\|adr-003-separate-order-status-from-finance-saga]]
- [[adr\|adr-004-stripe-hosted-checkout-pci-dss]]
|
| **Ordering — Finance** | - [[adr\|adr-001-finance-persisted-order-saga]]
- [[adr\|adr-002-finance-postgresql-message-persistence]]
- [[adr\|adr-003-finance-kafka-order-correlation]]
- [[adr\|adr-004-finance-bounded-scheduled-retries]]
- [[adr\|adr-005-finance-separate-workflow-and-order-status]]
- [[adr\|adr-006-finance-delegate-notification-delivery]]
|
| **Reviews — Rating** | - [[adr\|adr-001-postgresql-feedback-system-of-record]]
- [[adr\|adr-002-publish-feedback-events-for-catalog-projection]]
- [[adr\|adr-003-compensate-invalid-feedback-after-catalog-rejection]]
- [[adr\|adr-004-read-only-governed-feedback-summarization]]
|
| **Conversational — Chat** | - [[adr\|adr-001-chat-agent-orchestration-boundary]]
- [[adr\|adr-002-fail-closed-pii-middleware]]
- [[adr\|adr-003-separate-interactive-and-agent-protocols]]
- [[adr\|adr-004-in-memory-chat-sessions]]
- [[adr\|adr-005-govern-agent-tools-per-agent]]
- [[adr\|adr-006-user-scoped-episodic-and-semantic-memory]]
- [[adr\|adr-007-system-one-decision-model-routing-and-tool-selection]]
|
| **Conversational — MCP Tools** | - [[adr\|adr-001-mcp-read-only-domain-adapter]]
- [[adr\|adr-002-stateless-streamable-http-transport]]
- [[adr\|adr-003-separate-mcp-tools-resources-and-prompts]]
- [[adr\|adr-004-use-domain-apis-as-mcp-backends]]
- [[adr\|adr-005-authenticate-and-govern-mcp-calls]]
|
| **Platform — Notifications** | - [[adr\|adr-001-notification-kafka-command-intake]]
- [[adr\|adr-002-notification-postgresql-email-outbox]]
- [[adr\|adr-003-notification-smtp-provider-boundary]]
- [[adr\|adr-004-notification-scheduled-maintenance-boundary]]
- [[adr\|adr-005-notification-confidential-data-boundary]]
|
| **Platform — Scheduling** | - [[adr\|adr-001-postgresql-quartz-persistence]]
- [[adr\|adr-002-scheduler-invocation-boundary]]
- [[adr\|adr-003-idempotent-misfire-aware-jobs]]
- [[adr\|adr-004-protect-scheduler-secrets-and-telemetry]]
|
| **Platform — Email Provider** | - [[adr\|adr-001-provider-boundary-and-ownership]]
- [[adr\|adr-002-durable-outbox-and-bounded-retries]]
- [[adr\|adr-003-secret-and-sensitive-data-boundary]]
|
| **Identity Provider** | - [[adr\|adr-001-provider-boundary-and-identity-ownership]]
- [[adr\|adr-002-service-owned-authorization]]
- [[adr\|adr-003-fail-closed-token-validation]]
- [[adr\|adr-004-protect-credentials-and-auth-telemetry]]
|
| **Data Privacy** | - [[adr\|adr-001-use-presidio-analyze-for-pii-detection]]
- [[adr\|adr-002-anonymize-detected-pii]]
|
## Related Architecture Views
- [[doc\|arc42/08-crosscutting-concepts]] — System-wide rules that inform and constrain decisions.
- [[doc\|arc42/05-building-block-view]] — Capability ownership and structural boundaries.
- [[doc\|arc42/06-runtime-view]] — Runtime interactions shaped by these decisions.
- [[doc\|arc42/04-solution-strategy]] — Architectural approaches aligned with quality goals.
---
title: Quality Requirements
summary: Chapter guide to BookWorm's quality attributes, priorities, and measurable scenarios.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
This chapter applies ISO/IEC 25010 quality characteristics to BookWorm's prioritized goals in [[doc|arc42/01-introduction-and-goals/003-quality-goals]] and the architectural approaches in [[doc|arc42/04-solution-strategy]]. The overview summarizes priorities; the scenario register defines measurable acceptance criteria and identifies proposed targets that still require stakeholder approval.
## Chapter sections
- [[doc|arc42/10-quality-requirements/001-quality-requirements-overview]] — Priority summary and links between quality attributes and scenarios.
- [[doc|arc42/10-quality-requirements/002-quality-scenarios]] — Measurable runtime and change scenarios with evaluation guidance.
---
title: Quality Requirements Overview
summary: Prioritized quality attributes and their traceability to BookWorm's measurable scenarios.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
Quality requirements refine the priorities in [[doc|arc42/01-introduction-and-goals/003-quality-goals]] into observable outcomes. High priority protects correctness, interoperability, security, and essential reliability; medium priority covers deployability, operability, performance, and customer experience; low priority captures improvements that can follow once higher priorities are met.
## Quality attribute overview
**Quality Attribute Overview**
## Priority summary
| Quality Attribute | Priority (High / Medium / Low) | Key Focus Area | Linked Scenarios |
| :-------------------------- | :----------------------------- | :------------------------------------------------------------------------------------------ | :------------------ |
| Correctness | High | Validate authoritative purchase facts and keep order outcomes truthful. | QS-01, QS-02 |
| Interoperability | High | Preserve compatibility across supported service consumers. | QS-03 |
| Deployability | Medium | Release and roll back compatible changes independently. | QS-04 |
| Maintainability | Medium | Keep business-rule changes within their owning capability. | QS-05 |
| Maintainability | Low | Enable a new contributor to make a bounded change with focused verification. | QS-17 |
| Operability | Medium | Locate failed work and identify its real execution state. | QS-06 |
| Reliability | High | Recover asynchronous work and preserve delivery integrity. | QS-07, QS-08 |
| Reliability | Medium | Meet availability and restoration objectives for customer-facing paths and owned state. | QS-13, QS-14 |
| Security and privacy | High | Enforce access boundaries and prevent sensitive-data disclosure or unauthorized AI actions. | QS-09, QS-10, QS-15 |
| Performance | Medium | Bound interactive latency under a repeatable workload. | QS-12 |
| Usability and accessibility | Medium | Make errors actionable and core journeys accessible. | QS-11, QS-16 |
## Alignment with the architecture
- **Correctness** is supported by authoritative ownership of business facts and by keeping order state distinct from downstream coordination.
- **Interoperability** and **deployability** depend on explicit, compatible contracts and rehearsed independent releases.
- **Maintainability** is supported by capability ownership, localized change, and verification of dependency boundaries.
- **Operability** and **reliability** require correlated diagnostics, recoverable asynchronous work, and measured restoration.
- **Security and privacy** rely on least-privilege access, data minimization, and governed model and tool execution.
- **Performance, usability, and accessibility** are measured at customer-visible boundaries, separately from asynchronous freshness.
These approaches are consistent with [[doc|arc42/04-solution-strategy]]. Scenario targets marked as proposed remain subject to owner approval before they become release commitments.
---
title: Quality Scenarios
summary: Measurable runtime and change scenarios for BookWorm's quality requirements.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
The scenarios below refine the priorities in [[doc|arc42/01-introduction-and-goals/003-quality-goals]] and the approaches in [[doc|arc42/04-solution-strategy]]. Each states a stimulus, operating context, required response, measurable acceptance metric, and priority. All numerical service budgets are proposed until their owners approve them.
Checkout must use authoritative purchase facts; access denials must not expose protected data or cause protected writes; sensitive data must not be disclosed to model providers or telemetry; and failed asynchronous work must not be represented as successful business completion.
The response-time, availability, recovery, freshness, accessibility, rollout, and onboarding budgets below are proposed baselines, not approved service-level commitments. Assign owners and approve test conditions before treating them as release gates.
## Usage scenarios
| ID | Quality Attribute | Stimulus (Trigger) | Context / Environment | Expected Response | Measurable Metric | Priority |
| :--------------------------------------------- | :-------------------------- | :--------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------- |
| **QS-01 — Authoritative purchase** | Correctness | A customer submits checkout with valid, missing-item, or altered-price input. | Checkout reads the customer's persisted basket and current catalog facts. | Accept valid purchases using catalog-derived prices and basket quantities; reject unavailable items; never trust a client-supplied price. | 100% of accepted fixtures preserve authoritative quantities and prices; 0 purchases are created for unavailable-item fixtures. | High |
| **QS-02 — Truthful coordination outcomes** | Correctness | Basket cleanup, a retry, notification submission, or timeout returns success, failure, or an uncertain result. | Order coordination and downstream work may be retried or partially complete. | Determine completion or cancellation only from authoritative order state; expose cleanup and delivery failures without implying that retries prove business completion. | 0 order-state transitions are caused solely by cleanup, retry count, or notification outcome across the complete success and failure fixture set. | High |
| **QS-06 — Incident diagnosis** | Operability | An operator receives a request, message, scheduled-work, or order identifier associated with a failure. | A deployed verification environment includes correlated traces and execution records. | Identify the owning capability, failed boundary, and actual execution state. | Proposed: diagnose 100% of injected incidents within 15 minutes. | Medium |
| **QS-07 — Recoverable search freshness** | Reliability | A catalog update, deletion, indexing failure, or newer concurrent update occurs. | 1,000 catalog changes at 10 changes per minute with healthy dependencies. | Keep failed updates recoverable, prevent older revisions replacing newer ones, and remove deleted items from search. | Proposed: p95 commit-to-search visibility is at most 10 minutes; 100% of updates converge to the latest revision after recovery. | High |
| **QS-08 — Honest notification delivery** | Reliability | The mail provider or idempotency store fails before or after provider acceptance. | Notification work is delivered asynchronously with retries and a dead-letter recovery path. | Retry transient failures within configured bounds, retain exhausted work for investigation, and distinguish provider acceptance from recipient delivery. | 100% of exhausted failure fixtures are recoverable from the dead-letter mechanism; 0 provider failures are reported as confirmed recipient delivery. | High |
| **QS-09 — Enforced access boundaries** | Security | A request has missing or invalid credentials, insufficient permissions, or targets another customer's data. | Protected APIs and internal message-driven workers operate in a production-like environment. | Deny unauthorized access without exposing protected records or performing protected writes; valid authorized requests continue to work. | 100% of denial fixtures return an authorization failure; 0 protected records are disclosed and 0 protected writes occur. | High |
| **QS-10 — Sensitive-data minimization** | Security and privacy | A request, response, tool result, or exception contains synthetic personal data, a token, or another classified value. | Data crosses model-provider, API error, log, and telemetry boundaries. | Remove or protect sensitive values before disclosure; return public errors without credentials or internal diagnostic details. | 0 raw synthetic secrets appear in logs or telemetry; 0 raw synthetic personal data crosses protected model boundaries. | High |
| **QS-11 — Actionable interaction feedback** | Usability | A customer submits invalid data or waits on an outstanding operation. | Customer-facing forms include validation, conflict, and unexpected-error states. | Identify invalid fields, prevent invalid writes, provide progress feedback, and show a correlation reference without internal details for unexpected failures. | 100% of invalid fixtures identify the affected field and cause no write; proposed: progress feedback appears within 1 second. | Medium |
| **QS-12 — Interactive performance under load** | Performance | A representative workload runs for 30 minutes at 50 requests per second with 100 concurrent users. | 10,000 active books, baskets up to 20 items, healthy dependencies; workload mix is 60% catalog reads/search, 30% basket operations, and 10% checkout. | Maintain correct results while responding within operation-specific latency budgets; measure asynchronous work separately. | Proposed: p95 catalog and basket latency at most 500 ms; p95 checkout response after order persistence at most 2 s; p99 at most 2x each p95 budget; unexpected error rate below 1% per group. | Medium |
| **QS-13 — Customer-path availability** | Reliability | Synthetic probes exercise browsing, basket, and checkout once per minute. | Production-like environment measured over a rolling 30-day window, separately for each path. | Complete each eligible journey within its latency budget; count timeouts, incorrect results, and required-dependency outages as failures. | Proposed: at least 99.9% successful executions per path; exclude only intentional invalid-input and authorization-denial probes. | Medium |
| **QS-14 — Restore authoritative state** | Reliability | A service and its authoritative store are restored after simulated loss. | Each authoritative store is exercised independently; derived search data can be rebuilt from catalog records. | Restore usable service, reconcile queued and saga work, and avoid claiming exactly-once effects. | Proposed: RTO at most 30 minutes and RPO at most 5 minutes for committed authoritative data, measured per store. | Medium |
| **QS-15 — Govern model and tool execution** | Security and privacy | A prompt-injection fixture, denied tool request, rate-limit event, or tool-provider failure occurs. | Governed model workflows and registered tools run under their deployed policies. | Rejected inputs cause no agent handoff; denied tools do not run; allowed flows use only permitted tools; failures produce explicit degraded or failed outcomes. | 100% of policy fixtures follow the expected decision; 0 denied tool calls execute; rate-limited requests return an explicit limit response. | High |
| **QS-16 — Accessible core journey** | Usability and accessibility | A customer completes browsing, basket, checkout, and error states using keyboard navigation or a screen reader. | Agreed desktop and mobile browser and assistive-technology combinations. | Provide accessible names, logical focus order, field-associated errors, announced status changes, and no keyboard traps. | Proposed: meet applicable WCAG 2.2 AA criteria; 0 keyboard traps and 0 unresolved applicable conformance failures. | Medium |
## Change scenarios
| ID | Quality Attribute | Stimulus (Trigger) | Context / Environment | Expected Response | Measurable Metric | Priority |
| :----------------------------------------- | :---------------- | :----------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------------------------------- | :------- |
| **QS-03 — Compatible contracts** | Interoperability | A producer proposes an additive or breaking interface change. | Supported consumers use documented HTTP, RPC, or event contracts. | Verify compatibility with every supported consumer before release; provide an explicit migration and versioning plan for a breaking change. | 100% of supported consumers pass compatibility verification; 0 unplanned breaking changes are released. | High |
| **QS-04 — Independent compatible release** | Deployability | A capability releases a compatible change and rehearses rollback. | Unchanged consumers remain deployed during the release. | Release and roll back without unrelated capability releases; unchanged consumers continue to work in both versions. | 0 unrelated releases required; proposed: rollout and rollback each complete within 15 minutes. | Medium |
| **QS-05 — Local business-rule change** | Maintainability | A team implements an agreed small rule change that needs no new cross-capability contract. | The change is limited to one capability and includes focused verification. | Change the owning capability without altering another capability's data schema or implementation. | 0 changes to other capabilities' schemas or implementations; proposed: complete implementation and focused verification within 2 engineer-days. | Medium |
| **QS-17 — New-contributor onboarding** | Maintainability | A contributor unfamiliar with the system is assigned an agreed small behavior change. | Documentation, development tools, and required access are available; waiting time is tracked separately. | Find the owning capability and its contracts, implement the change, and pass focused behavior and boundary checks. | Proposed: complete within 5 working days; report active effort separately from access and review delays. | Low |
## Scenario evaluation prompts
For the selected BookWorm quality scenario, prepare a verification plan using synthetic data in an
isolated environment. Record the software versions, environment, data set, workload, dependency
health, and active governance policies. Define the measurement boundary: checkout ends when the
order is persisted, search freshness ends when the updated revision is queryable, and notification
evidence ends at provider acceptance. Specify the per-operation and per-customer-path percentiles
and error rates to collect, the failures that count against the metric, and the persisted side
effects or asynchronous states to verify. Do not claim exactly-once behavior or promote proposed
targets to approved commitments.
Create an evaluation record for the selected quality scenario with these fields: scenario ID and
owner; target approval status; evaluation date; frozen conditions and workload; measured result
against the stated metric; sanitized evidence; known gaps; follow-up owner; and the event that
should trigger re-evaluation. Report timeouts, incorrect results, and dependency outages as
failures wherever the scenario requires them. Use only synthetic data and exclude sensitive values
from the record.
## Alignment and trade-offs
| Concern | Architectural position | Scenario evidence still required |
| :-------------------------------------- | :---------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------- |
| Correctness versus latency | Checkout uses authoritative basket and catalog facts; latency targets do not justify bypassing validation. | Evaluate QS-01 with QS-12 and define explicit behavior when dependencies fail. |
| Durable work versus freshness | Catalog changes do not wait for search indexing; asynchronous work must converge after recovery. | Approve freshness and backlog budgets and evaluate recovery under sustained outages in QS-07. |
| Retries versus duplicate effects | Retries preserve work but may repeat cleanup or provider submissions; exactly-once behavior is not assumed. | Evaluate uncertain outcomes and duplicate handling in QS-02 and QS-08. |
| Independent release versus coordination | Compatible changes may be released independently; breaking changes require planned migration. | Approve supported mixed-version windows and rollback criteria in QS-03 and QS-04. |
| Diagnosis versus privacy | Correlation supports diagnosis without retaining raw sensitive values. | Approve retention and access controls and verify redaction in QS-06 and QS-10. |
| Availability versus recovery cost | Infrastructure configuration is not evidence that recovery objectives have been met. | Run isolated drills and verify external dependency commitments for QS-13 and QS-14. |
| AI usefulness versus least privilege | Model workflows use explicit policies; denied tools and failed providers do not create fabricated outcomes. | Evaluate policy coverage and provider failure behavior in QS-15. |
## Related architecture documentation
- [[doc|arc42/01-introduction-and-goals/003-quality-goals]] — Prioritized quality goals.
- [[doc|arc42/04-solution-strategy]] — Architectural approaches addressing those goals.
- [[doc|arc42/11-risks-and-technical-debt]] — Open exposures and verification gaps.
---
title: Risks and Technical Debt
summary: Prioritized architectural exposures and known compromises with actionable treatment and closure evidence.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
This register separates uncertain future exposures from known compromises and missing verification, ranks them by likelihood and impact, and tracks mitigation through observable closure evidence. Review it when contracts, data ownership, security controls, or operational assumptions change; qualitative ratings are not risk acceptance.
**R-03:** Confirm that every model and tool path enforces privacy and authorization controls; disable any path that fails verification.
**R-01:** Exercise duplicate delivery and timeout-after-side-effect cases; make uncertain outcomes visible and safe to reconcile.
**R-02:** Rehearse restoration and dependency-outage procedures for authoritative state before relying on recovery targets.
## Architectural and operational risks
The likelihood and impact ratings are qualitative: **H** high, **M** medium, and **L** low. “Mitigating” means safeguards or treatment exist but closure evidence is incomplete.
| ID | Risk | Affected Building Blocks / Quality Goals | Likelihood (H/M/L) | Impact (H/M/L) | Mitigation / Contingency | Status |
| :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------------------------------------------------------------------------- | :----------------: | :------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :-------------------------------------------- |
| **R-03** | A model integration or tool path may bypass privacy screening or authorization, exposing personal data or allowing an unapproved action and causing a privacy incident or loss of customer trust. | Conversational, Reviews, MCP Tools; Security, Privacy, Correctness; QS-09, QS-10, QS-15 | M | H | Inventory every model and tool path; verify least privilege, sensitive-data handling, and fail-closed behavior with synthetic fixtures. Disable a path that fails verification and use a non-AI fallback until corrected. | Mitigating; full-path evidence open |
| **R-01** | At-least-once delivery, retries, or ambiguous timeouts may repeat basket cleanup or external notification effects, creating duplicate customer-visible outcomes or difficult reconciliation. | Ordering, Finance, Basket, Notification; Correctness, Reliability, Operability; QS-02, QS-08 | M | H | Test duplicate delivery and timeout-after-effect cases. Define idempotency per operation and surface uncertain outcomes. Reconcile before replay when the prior effect cannot be determined. | Open |
| **R-02** | A store, service, or external provider outage may exceed recovery expectations because availability, alerting, failover, and restore behavior have not been demonstrated under production-like conditions; recovery may lose data or prolong an outage. | All service-owned stores, Platform, external providers; Reliability, Operability; QS-06, QS-13, QS-14 | M | H | Run isolated outage and restore drills for each authoritative store; measure recovery and data loss against approved targets. Maintain provider-specific recovery steps and degrade affected customer journeys when dependencies are unavailable. | Open |
| **R-05** | An undocumented consumer or semantic contract change may evade schema checks and break a dependent capability, causing failed requests or message processing. | All contract producers and consumers; Interoperability, Deployability; QS-03, QS-04 | M | H | Maintain a producer-consumer inventory, review behavioral changes as well as schema changes, and require compatibility evidence before release. For a regression, roll back or use a staged version migration. | Mitigating; unknown-consumer exposure remains |
| **R-04** | A backlog or dependency outage may leave derived search or rating views stale after authoritative data changes, misleading discovery even though catalog data remains authoritative for purchase decisions. | Catalog, Scheduler, Catalog Ingestion, Reviews; Correctness, Reliability, Performance; QS-07 | M | M | Measure per-change projection lag, alert on growing backlog, and verify replay and rebuild behavior. Keep purchase decisions on authoritative catalog data; suppress or clearly degrade stale discovery results when needed. | Mitigating; freshness target unapproved |
**R-03:** Record the inventory of model and tool paths and retain sanitized results showing that
unauthorized calls are denied and synthetic sensitive data is not disclosed.
**R-01:** Record duplicate and ambiguous-timeout outcomes, including the deduplication or
compensation behavior and how operators determine whether replay is safe.
**R-02:** Record one successful restore exercise per authoritative store and an outage exercise,
including measured recovery time, data loss, and comparison with approved objectives.
## Technical debt
These are known compromises or evidence gaps, not uncertain future events. Priority reflects the cost of leaving each item unresolved.
| ID | Technical Debt Item | Affected Scope | Business / Technical Impact | Remediation Plan | Priority |
| :-------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------: |
| **TD-01** | The duplicate-request guard does not make the complete checkout operation an atomic exactly-once transaction; a concurrent request or failure after key creation can leave an outcome requiring recovery. | Ordering checkout and downstream effects | A retry may be blocked after incomplete work, or an ambiguous result may lead to repeated downstream effects. | Document the actual guarantee; test concurrent requests and failures after request registration; choose and implement explicit recovery or compensation semantics. Link: [[doc\|arc42/10-quality-requirements/002-quality-scenarios]] (QS-02). | High |
| **TD-02** | The production operations profile is incomplete: service-specific alerts, scaling limits, ingress protections, and store recovery procedures are not all finalized and rehearsed. | Platform operations and service owners | Incidents may go undetected or take longer to contain and recover; configured infrastructure alone does not demonstrate readiness. | Assign an owner to each operating control, finalize thresholds and runbooks, and rehearse the procedures in the target environment. Link: [[doc\|arc42/10-quality-requirements/002-quality-scenarios]] (QS-06, QS-13, QS-14). | High |
| **TD-03** | Numerical quality budgets remain proposals rather than owner-approved service commitments. | Product, service owners, and operations | Teams cannot consistently judge release readiness or resolve trade-offs against shared targets. | Assign decision owners and approve or revise measurement conditions and thresholds before using them as release gates. Link: [[doc\|arc42/10-quality-requirements/002-quality-scenarios]] (QS-04 through QS-17). | Medium |
| **TD-04** | No recorded pass/fail evaluation evidence exists for the quality scenario set under frozen conditions. | All quality attributes | Architecture reviews cannot distinguish implemented mechanisms from demonstrated end-to-end outcomes. | Evaluate scenarios by risk, record conditions and measured results, and track failures to an owner and retest trigger. Link: [[doc\|arc42/10-quality-requirements/002-quality-scenarios]] (QS-01 through QS-17). | High |
| **TD-05** | Critical cross-service persistence workflows and the customer checkout journey lack sufficient automated integration and end-to-end verification. | Ordering, Finance, Catalog, Shopping, and customer commerce | Regressions across persistence, messaging, and customer-visible behavior may pass unit or contract checks. | Add isolated integration coverage for checkout, saga, and persistence boundaries; add customer-journey and accessibility checks for checkout. Link: [[doc\|arc42/10-quality-requirements/002-quality-scenarios]] (QS-01, QS-11, QS-12, QS-16). | High |
| **TD-06** | Older architecture records still describe persistence choices that have been superseded for Reviews, Finance, Notification, and Chat. | Architecture records and operational guidance | Contributors may follow obsolete ownership or recovery assumptions, resulting in incorrect changes or incident procedures. | Mark superseded records clearly, link each to its current decision, and review related guidance when persistence changes. Reference: [[doc\|arc42/09-architecture-decisions]]. | Medium |
### Known Contract and Runtime Quirks
Concrete contract/runtime mismatches discovered during post-rewrite catalog verification. Service-level engineering invariants and workarounds live alongside each owning service.
| ID | Quirk / Mismatch | Affected Resources | Impact | Remediation Direction |
| :-------- | :--------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------- |
| **TD-07** | Image upload pre-processor expects a different multipart field shape than the endpoint validator under certain payloads. | [[command\|CreateBook]], [[service\|catalog-api]] | Valid client uploads may fail validation unexpectedly. | Align pre-processor binding and endpoint validation rules; add contract regression tests. |
| **TD-08** | Publisher creation and update enforce inconsistent maximum name lengths. | [[command\|CreatePublisher]], [[command\|UpdatePublisher]], [[service\|catalog-api]] | Names accepted on creation can be rejected on update. | Unify max-length constraints across create/update validators. |
| **TD-09** | Creating a buyer with an existing identifier surfaces a database duplicate-key violation as `500` instead of `409`. | [[command\|CreateBuyer]], [[service\|order-api]] | Clients treat `500` as transient and retry instead of reconciling existing buyer state. | Map duplicate-key exceptions to `409 Conflict` ProblemDetails. |
| **TD-10** | [[query\|GetBasketGrpc]] returns an empty basket rather than `NotFound`, and checkout does not reject an empty item list. | [[command\|CreateOrder]], [[query\|GetBasketGrpc]], [[service\|order-api]], [[service\|basket-api]] | Empty baskets can persist as `201 Created` orders with zero line items. | Reject empty-item checkouts with `400 Bad Request` before persistence. |
| **TD-11** | Deleting a buyer with existing orders triggers an `ON DELETE SET NULL` foreign-key conflict against non-nullable `buyer_id`. | [[command\|DeleteBuyer]], [[service\|order-api]] | Buyer deletion fails at runtime when historical orders exist. | Enforce explicit pre-check (`409 Conflict`) or soft-delete semantics before persistence. |
| **TD-12** | OpenAPI metadata declares `404` as `application/problem+json`, while runtime returns `application/json`. | [[service\|order-api]], [[service\|catalog-api]], [[service\|rating-api]], [[command\|DeleteFeedback]] | Strict schema-validating clients may fail to parse `404` error bodies. | Standardize `404` responses on RFC 9457 `application/problem+json` (see [[adr\|adr-bw-011-shared-validation-and-error-contracts]]). |
## Review and acceptance
- Reassess likelihood and impact when new evidence changes an assumption; do not lower a rating solely because a safeguard has been configured.
- Close a risk only when its mitigation evidence is recorded or an accountable decision-maker accepts the residual exposure with a review date.
- Reprioritize debt when customer impact, operational exposure, or the cost of remediation changes.
## Related architecture documentation
- [[doc|arc42/09-architecture-decisions]] — Decision status and rationale, including superseding decisions.
- [[doc|arc42/10-quality-requirements/002-quality-scenarios]] — Measurable acceptance criteria cited by this register.
## Changelog
- Rewrote `index.mdx` to rank assessable architectural risks separately from known technical debt, add impacts and actionable treatments, and define closure evidence.
---
title: Glossary
summary: Shared plain-language definitions for BookWorm domain concepts, architecture terms, and recurring acronyms.
owners:
- architecture-enabling-team
badges:
- content: Architecture
backgroundColor: blue
textColor: blue
---
This glossary defines the shared ubiquitous language used across all arc42 sections, including domain concepts, acronyms, and BookWorm-specific technical terms. Each definition identifies important ownership or meaning differences so the same word does not imply different business and engineering behavior.
## Domain Terms
| Term | Definition | Synonyms / Acronyms |
| :------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------- |
| Address | Delivery destination associated with a Buyer; it does not identify the customer. | Delivery address |
| Author | Person credited with creating one or more books. | — |
| Availability | Whether Catalog currently offers a listed book as available for purchase; it does not reserve stock. | Catalog availability |
| Basket | A customer's mutable selection of books and quantities before checkout; it is not an Order, price lock, or inventory reservation. | Shopping basket |
| Basket item | A book reference and positive requested quantity in a Basket; it contains no purchase-price snapshot. | — |
| Book | A Catalog listing that supplies the title and purchase facts used for discovery and checkout. | Catalog book |
| Book reference | A link from a Reviews record to a Catalog book without transferring ownership of the book's details. | Catalog book reference |
| Buyer | An Ordering-owned customer profile used for delivery details and order history; it is distinct from the authenticated Customer identity. | — |
| Canceled | Terminal Order state meaning the purchase will not complete; it is reached by an explicit order decision, not inferred from a failed downstream workflow. | Order status; implementation spelling: Cancelled |
| Category | Catalog classification used to group books for browsing and filtering. | — |
| Checked-out event | Fact that checkout persisted an Order and started downstream coordination; it does not prove payment, basket cleanup, or notification delivery. | Checkout event |
| Checkout | The operation that validates a Basket against authoritative Catalog facts and creates an Order; it does not itself mean payment settlement or fulfillment. | — |
| Comment | Optional text submitted with a Feedback rating. | Review text |
| Completed | Terminal Order state meaning the purchase has explicitly finished. | Order status |
| Customer | Person using BookWorm's customer-facing experience; the person's authenticated identity and Ordering profile are separate concepts. | Shopper |
| Customer identifier | Authenticated subject used to scope a customer's Shopping data; it is not the Ordering Buyer identifier. | Authenticated subject identifier |
| Customer request | Message asking the conversational experience for help; mentioning a book, order, or account does not grant access to that record. | Chat request |
| Feedback | One customer's 0-to-5 score and optional Comment about a book, stored as a Reviews-owned record. | Customer review |
| Feedback summary | AI-generated qualitative classification of Feedback, such as Best Seller, Good, Bad, or No Data; it is not the Catalog rating average. | AI feedback classification |
| New | Initial Order state after creation; it can transition only to Completed or Canceled. | Order status |
| Order | Durable purchase record created by checkout, containing purchase-time items, prices, and business status; it is separate from the Basket and post-checkout workflow state. | Purchase |
| Order item | Order line recording a book reference, positive quantity, and unit price at purchase; later Catalog price changes do not alter it. | Order line |
| Order summary | Derived read view of Order information for queries; it does not replace the authoritative Order record. | — |
| Order total | Sum of each Order item's recorded unit price multiplied by its quantity. | Purchase total |
| Price | Catalog's regular price and optional discounted price; checkout records the applicable price on the Order item, while payment settlement is separate. | Regular price; sale price |
| Publisher | Publishing organization associated with a Catalog book. | — |
| Rating | Individual integer score from 0 through 5 submitted as Feedback; it is distinct from an aggregate rating summary. | Score |
| Rating summary | Catalog's average score and review count, updated asynchronously from Reviews data. | Catalog rating aggregate |
| Review | Customer-facing term for an individual Feedback record; it is not a second record or a rating summary. | Feedback |
## Technical Terms & Acronyms
| Term | Definition | Synonyms / Acronyms |
| :---------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------- |
| A2A | Protocol for communication between separate AI agents; BookWorm uses it for read-only specialist analysis. | Agent-to-Agent |
| ADR | Record of an architecture decision, including its context, considered options, decision, and consequences. | Architecture Decision Record |
| AG-UI | Interactive streaming protocol through which a customer interface exchanges conversational turns with the Chat service. | Agent-User Interaction |
| AI | Computer systems performing tasks such as language understanding, classification, or content generation. | Artificial intelligence |
| Anti-corruption layer | Adapter that translates another context's model into local terms so upstream changes do not leak into the consumer's business rules. | — |
| API Gateway | Edge component that routes client traffic to the appropriate user experience or service without owning their business data. | YARP gateway |
| arc42 | Architecture documentation approach that organizes system context, decisions, structure, behavior, quality, and operations into defined sections. | — |
| Aspire | Tooling for describing and orchestrating BookWorm's distributed application resources and their connections across development and deployment environments. | .NET Aspire |
| Azure Blob Storage | Object storage used for book images and conversational session data; it is not the authoritative store for Catalog or Order records. | Blob Storage |
| Azure Functions | Managed execution environment used for event-triggered Catalog ingestion work. | Functions |
| Backoffice | Staff-facing BookWorm application for managing catalog listings, orders, customers, and reviews. | Staff application |
| Book Agent | Primary conversational agent that answers book-discovery questions using Catalog information and specialist agents. | — |
| Book Catalog Researcher | Specialist agent that gathers factual book, author, and category information from Catalog tools. | — |
| Book Recommendation Researcher | Specialist agent that builds a Catalog-backed shortlist from a customer's stated preferences. | — |
| Bounded context | Boundary within which a domain model and its terms have one consistent meaning and an accountable owner. | Context |
| Building block | Named part of an architecture with a defined responsibility and boundary; its size depends on the view being described. | — |
| Business capability | Business responsibility that the organization needs to perform, regardless of which software component implements it. | Capability |
| CloudEvents | Standard envelope for event metadata and payload; it does not by itself guarantee delivery or processing. | CloudEvents format |
| Commerce | Customer-facing application for basket, checkout, and account journeys. | — |
| Cosmos DB | Managed document store used as the authoritative store for Reviews Feedback. | Azure Cosmos DB |
| CQRS | Separation of operations that change state from models optimized to read state; it does not require separate physical databases. | Command Query Responsibility Segregation |
| Dead-letter queue | Messaging destination for work that could not be processed within its retry policy, retained for investigation and controlled recovery. | DLQ |
| Decision Router | Conversational classifier that checks request safety and scope and selects the appropriate specialist before an agent responds. | — |
| Domain event | Fact about a state change inside one bounded context; it is not necessarily published to other contexts. | — |
| Durable Task Scheduler | Persistent workflow service that records Finance coordination progress and resumes work after interruptions. | Azure Durable Task Scheduler |
| Entity Framework Core | .NET data access framework used for relational persistence in selected services. | EF Core |
| EventCatalog | Catalog used to document and navigate BookWorm's domains, services, events, and architecture. | — |
| Eventual consistency | State in which an asynchronously updated view may temporarily lag its authoritative data before converging; no fixed convergence time is implied unless a target is agreed. | — |
| Finance orchestration | Durable post-checkout coordination of work such as basket cleanup and notification; it does not process payment or own Order status. | Finance workflow |
| FusionCache | Caching library configured with in-memory and Redis-backed layers; cached values do not become authoritative business data. | — |
| gRPC | Typed request/response protocol used for synchronous communication between selected BookWorm services. | — |
| Handoff | Transfer of conversational control between agents; it does not execute a business transaction such as placing an Order. | Agent handoff |
| Heartbeat job | Recurring check that indicates whether the Scheduler can run; it does not prove a business operation completed. | Liveness job |
| Idempotency | Property of handling a repeated request or message without repeating its intended business effect; it is not a guarantee of exactly-once processing across all systems. | Duplicate-safe processing |
| Inbox | Durable record of received or processed messages used to recognize and suppress duplicate handling. | Message inbox |
| Integration event | Published fact about a committed change that another context may consume without taking ownership of the source record. | Cross-context event |
| Integration event idempotency guard | Time-bounded deduplication mechanism that prevents a redelivered message from being handled again within its configured window. | Message deduplication guard |
| ISO/IEC 25010 | International standard that defines a model of software product quality characteristics used to organize quality requirements. | — |
| Kafka | Event-streaming platform used for asynchronous communication between BookWorm capabilities. | Apache Kafka |
| Large language model | AI model that generates or analyzes text from a prompt and supplied context. | LLM |
| Mailpit | Local SMTP test service used to capture and inspect email submissions during development; it is not the production mail provider. | — |
| Marten | .NET library used with PostgreSQL for document and event-oriented persistence in Ordering. | — |
| MCP | Protocol through which an AI client discovers and invokes tools or resources; BookWorm exposes read-only Catalog capabilities through it. | Model Context Protocol |
| Microfrontend | Independently developed and deployed part of a composed browser experience, focused on a customer or staff journey. | MFE |
| Microsoft Entra ID | Identity provider that authenticates users and workloads and supplies claims used by services to authorize access. | Entra ID |
| Microsoft Foundry | Managed platform hosting the AI models used for conversational, decision, and embedding tasks. | — |
| OAuth 2.0 | Authorization framework through which a client obtains delegated or workload access tokens for protected services. | OAuth |
| OpenID Connect | Identity layer built on OAuth 2.0 that communicates authenticated user identity to a client. | OIDC |
| OpenTelemetry | Vendor-neutral conventions and instrumentation for collecting traces, metrics, and logs across services. | OTel |
| Outbox | Durable outgoing-message record committed with a business change and published asynchronously afterward. | Transactional outbox |
| Pact | Consumer-driven contract testing approach in which consumer expectations are verified against a provider. | — |
| PII | Information that identifies, or can reasonably be linked to, an individual. | Personally identifiable information |
| PostgreSQL | Relational database system used for authoritative data in selected BookWorm capabilities; each capability remains responsible for its own data. | — |
| Presidio | Toolkit used to detect and anonymize personal information in selected AI request paths; detection is a safeguard, not a guarantee of perfect coverage. | Microsoft Presidio |
| Projection | Derived read model built from authoritative data or events and rebuildable from that source. | Read model |
| QA Agent | Conversational specialist that answers policy and service questions from supplied information without tools for changing customer records. | Question-answering agent |
| Qdrant | Vector search engine used for the derived book-search index; Catalog remains authoritative for book data. | — |
| Quality attribute | Characteristic of a system that stakeholders use to judge its behavior or fitness, such as reliability or maintainability. | Quality characteristic |
| Quality goal | Prioritized outcome that architecture must protect when making design trade-offs. | — |
| Quality scenario | Testable stimulus, context, response, and metric that makes a quality goal assessable. | Scenario |
| Quartz Dashboard | Operator interface for inspecting scheduled jobs, triggers, and execution history; a successful job run does not prove a business outcome. | Scheduler dashboard |
| Quartz.NET | .NET scheduler used to run recurring and scheduled background jobs. | Quartz |
| Rating Agent | Read-only specialist that analyzes known book Feedback and returns a qualitative summary. | — |
| Redis | In-memory data store used as authoritative Basket storage in Shopping and as a cache or deduplication store in other contexts; its authority depends on the use. | — |
| Risk | Uncertain event or condition that could cause a stated adverse outcome; likelihood and impact are assessed separately. | Architectural risk |
| RPO | Maximum targeted age of committed data that may be missing after recovery. | Recovery Point Objective |
| RTO | Maximum targeted time to restore a service to a usable state after disruption. | Recovery Time Objective |
| Saga | Durable sequence coordinating work across contexts, with retries or compensating actions; it is not one atomic transaction. | — |
| SLA | Formally agreed service commitment between a provider and a consumer, potentially with contractual remedies. | Service-level agreement |
| SLO | Quantified service target measured over an agreed window; a proposed SLO is not an approved SLA. | Service-level objective |
| Source of truth | Authoritative owner and record for a particular data item; different contexts may have different sources of truth. | Authoritative source |
| Storefront | Public customer-facing application for book discovery, book details, conversational assistance, and sign-in. | Customer storefront |
| Technical debt | Known compromise or verification gap that creates a cost or risk and has an explicit remediation or acceptance decision. | — |
| Ubiquitous language | Shared, precise vocabulary used by domain participants and engineers within a bounded context. | Shared domain language |
| Vector batch job | Scheduled work that publishes pending book-index updates; it triggers processing but does not own Catalog data or embeddings. | — |
| Vector embedding | Numeric representation of text used to compare semantic similarity between books or queries. | Embedding |
| Vector index | Derived search structure containing book embeddings for semantic retrieval; it can be rebuilt from Catalog data. | Search vector index |
| WAF | Edge security control that filters and blocks selected malicious web requests before they reach services. | Web application firewall |
| Wolverine | .NET messaging runtime used to handle commands and events and to support configured Kafka, inbox, and outbox workflows. | WolverineFx |
| YARP | .NET reverse-proxy technology used to implement the API Gateway. | Yet Another Reverse Proxy |
## Changelog
- Reorganized the glossary into alphabetized domain and technical tables with the requested three-column format.
- Clarified distinctions among Customer and Buyer, Feedback and Review, the two types of summary, and order states; consolidated synonyms and acronyms.
- Added recurring architecture terms and their system-specific meanings, and removed implementation paths, ownership inventories, and diagram references.
---
title: Run BookWorm locally
summary: The shortest path from a prepared machine to a responding local BookWorm application.
owners:
- architecture-enabling-team
---
Follow these five steps to start the application. With Docker ready and images cached, this path is designed to take under 10 minutes; first-time image downloads can take longer.
Have Git, mise, and Docker Desktop (or a compatible container runtime) installed. Keep Docker
running while the application starts.
Replace the placeholders with your repository URL and preferred local directory:
```bash
git clone
cd
```
From the repository root, install the versions selected for the project:
```bash
mise install
```
```bash
mise run prepare
```
```bash
mise run run
```
Wait for Aspire to finish starting the resources. The dashboard address is printed in the terminal.
Open the printed dashboard address, confirm the required resources report **Running**, then open the public application endpoint shown for the gateway. Confirm that the application responds.
If a step fails, start with [[doc|development/007-troubleshoot-local-dev]]. For tool choices, secrets, and workspace-specific setup, see [[doc|development/002-getting-started]].
---
title: Developer Onboarding
summary: A Day 1 and Week 1 roadmap for understanding BookWorm, verifying a workspace, and making a first contribution.
owners:
- architecture-enabling-team
badges:
- content: Onboarding
backgroundColor: teal
textColor: teal
---
Use this roadmap to move from orientation to a small, reviewed contribution. It points to the right guide for each task instead of repeating setup, testing, or review instructions.
_Developer Onboarding Path_
## Day 1: orient and verify
1. Read this roadmap, then skim [[doc|arc42/01-introduction-and-goals/001-introduction]].
2. To run BookWorm immediately, follow [[doc|development/000-local-quickstart]]. For a more deliberate environment setup, use [[doc|development/002-getting-started]] instead.
3. Identify the service or frontend that owns the behavior you want to understand. Keep changes inside that boundary and follow [[doc|development/004-engineering-standards]].
4. Verify one local application endpoint and one relevant check before changing code. Use [[doc|development/007-troubleshoot-local-dev]] if setup blocks you.
| Milestone | Evidence |
| :------------------- | :------------------------------------------------------------------------------ |
| Workspace ready | The required tools are available and dependencies are restored. |
| Application verified | The Aspire dashboard is reachable and the public application endpoint responds. |
| Change identified | You can name the owning business capability and the behavior to change. |
## Week 1: learn the contribution loop
| Focus | Read or do |
| :------------------------- | :---------------------------------------------------------------------------------------------------------------------------------- |
| Architecture and ownership | Follow the system introduction and trace one request or event across its owning boundaries. |
| Daily workflow | Use [[doc\|development/003-development-workflow]] for branches, focused changes, formatting, and synchronization. |
| Quality expectations | Review [[doc\|development/004-engineering-standards]] before implementing. |
| Verification | Choose the appropriate test layer with [[doc\|development/008-testing-matrix]], then run it using [[doc\|development/005-testing]]. |
| First contribution | Select a bounded issue, make one cohesive change, and follow [[doc\|development/006-pull-request-process]]. |
## Continue with a focused guide
## A good first contribution
Choose a change with a clear owner, observable outcome, and testable acceptance criteria. Confirm the expected behavior with a maintainer when those criteria are unclear. Keep the patch focused, run the checks for the changed area, and describe both the change and its verification in the pull request.
For common startup failures, use [[doc|development/007-troubleshoot-local-dev]]. For production-only incidents, follow [[doc|operational/003-incident-response-and-runbooks]].
---
title: Getting Started
summary: Tool requirements, editor options, local configuration, and common commands for contributing to BookWorm.
owners:
- architecture-enabling-team
badges:
- content: Setup Reference
backgroundColor: teal
textColor: teal
---
Use this guide to configure the tools needed for your kind of work. For the shortest first run, follow [[doc|development/000-local-quickstart]]; this page covers the broader setup choices.
## Tool requirements
| Requirement | Minimum or project version | Needed for | Verify |
| :--------------------------------------------- | :---------------------------------------------------------------------------- | :----------------------------------------------------------------- | :--------------------------------- |
| Git | Current supported release; no project-specific minimum | All changes | `git --version` |
| mise | Current release | Installing pinned tools and running workspace tasks | `mise --version` |
| .NET SDK | `11.0.100` | Backend development, backend tests, and the full local application | `dotnet --version` |
| Node.js | `26` selected by the project toolchain; package engine requires `24` or newer | JavaScript workspaces and documentation | `node --version` |
| Bun | `1.4.4` | Frontend and documentation workspaces | `bun --version` |
| Aspire CLI | `17` | Starting and inspecting the full local application | `aspire --version` |
| Docker Desktop or compatible container runtime | Current supported release; no project-specific minimum | Full local application and container-backed services | `docker version` and `docker info` |
Git, mise, and the relevant language runtime are enough for most focused changes. Docker and the Aspire CLI are only needed when you run the distributed application locally.
## Optional tools
| Tool or access | Minimum or project version | Use it when | Verify |
| :---------------------------------------------- | :------------------------------------------ | :---------------------------------------------------- | :--------------------------------------------- |
| Buf | Current release | Editing Protocol Buffer contracts | `buf --version` |
| GitHub CLI | Version `2` or newer | Creating or checking pull requests from a terminal | `gh --version` |
| Azure CLI | Version `2` or newer | Working directly with Azure resources | `az version` |
| `uv` | Managed by mise | A task explicitly requires Python tooling | `uv --version` |
| Microsoft Entra ID and Microsoft Foundry access | Project and tenant access; no local version | Testing authenticated flows or hosted AI capabilities | Confirm access in the relevant provider portal |
## Editor and shell
- **VS Code** is a practical choice for mixed .NET, TypeScript, and documentation work. Install the C# tooling and the repository's recommended extensions when prompted.
- **Visual Studio** or **JetBrains Rider** are good options for .NET debugging and test navigation.
- Use a shell where mise is activated so commands resolve the selected tool versions. Restart the shell after installing or changing tool versions.
## Fork remotes
For pull-request contributions, set `origin` to your fork and add the main project as `upstream`. Replace the placeholder with the project's repository URL:
```bash
git remote add upstream
git remote -v
```
Keep your feature branches on `origin`; use `upstream` to synchronize with the shared `main` branch.
## Local services, credentials, and cloud access
For local application runs, Aspire starts the configured backing services as containers. This keeps local database, cache, messaging, storage, and privacy dependencies separate from hosted cloud resources. Unit and contract tests do not require Docker; see [[doc|development/008-testing-matrix]].
Microsoft Entra ID and Microsoft Foundry are optional for basic local startup. Authenticated user journeys and hosted AI features require valid access and application configuration. Keep credentials in user secrets or environment variables, never in source control.
Useful user-secret commands:
```bash
dotnet user-secrets list --project
dotnet user-secrets set "" "" --project
```
Replace the placeholders with the AppHost project and setting supplied by your local configuration. Do not clear all secrets to fix a single missing value.
## Common workspace commands
Run repository tasks from the repository root. Run Bun commands from the relevant frontend or documentation workspace.
| Command | Purpose |
| :---------------------------------- | :-------------------------------------------------------------- |
| `mise tasks ls` | List available repository tasks. |
| `mise run prepare` | Restore dependencies and configure Git hooks. |
| `mise run build` | Build the .NET solution. |
| `mise run test:unit` | Run backend unit and architecture tests. |
| `mise run test:contracts` | Generate consumer contracts, then verify providers. |
| `mise run test` | Run the backend test tasks. |
| `mise run format` | Format all supported workspaces. |
| `mise run run` | Start the local application with Aspire. |
| `bun install` | Install dependencies in the current Bun workspace. |
| `bun run dev` | Start the current frontend or documentation development server. |
| `bun run test` | Run frontend tests from the frontend workspace. |
| `bun run check` / `bun run fitness` | Check documentation formatting and architecture rules. |
For the execution sequence, filters, and result interpretation, see [[doc|development/005-testing]]. For startup failures, see [[doc|development/007-troubleshoot-local-dev]].
---
title: Development Workflow
summary: The daily branch, implementation, verification, formatting, and synchronization loop for BookWorm changes.
owners:
- architecture-enabling-team
badges:
- content: Workflow
backgroundColor: teal
textColor: teal
---
Keep each branch focused on one cohesive change. Use this loop for backend, frontend, and documentation work; the standards and test guides define the detailed rules for each area.
_Branching and Change Flow_
## Create a focused branch
After configuring the `upstream` remote, update `main` and branch from it:
```bash
git fetch upstream
git switch main
git merge --ff-only upstream/main
git switch -c feature/
```
Replace `` with a concise lowercase-kebab-case name. Use `feature/`, `fix/`, or `docs/` to identify the change type.
## Implement and verify in small steps
1. Confirm the owning service, frontend, or documentation area before editing.
2. Make one cohesive change and add or update focused tests when behavior changes.
3. Run the smallest relevant build, test, and formatting tasks. See [[doc|development/005-testing]] for test commands and [[doc|development/004-engineering-standards]] for enforced rules.
4. For rapid iteration, use `dotnet watch` from the relevant .NET project workspace or `bun run dev` from the relevant frontend workspace.
Useful formatting tasks include `mise run format:cs`, `mise run format:fe`, and `mise run format:docs`. Use `mise run format` when you want to format every supported workspace.
## Keep the branch current
When `main` advances, update your branch without discarding local work:
```bash
git fetch upstream
git merge upstream/main
```
Resolve conflicts deliberately, rerun the affected checks, and push the branch to your fork. Do not reset a branch that contains work you have not confirmed is safe to discard.
## Commit and hand off
Use a Conventional Commit prefix such as `feat:`, `fix:`, `docs:`, `refactor:`, `test:`, or `chore:` followed by a concise, imperative summary. Repository hooks run formatting, analyzers, and build checks on commit.
When the change is ready, follow [[doc|development/006-pull-request-process]]. Do not start the full Aspire application for routine code or documentation checks.
---
title: Engineering Standards
summary: Practical coding, API, contract, naming, formatting, and analysis rules and how automated checks enforce them.
owners:
- architecture-enabling-team
badges:
- content: Standards
backgroundColor: teal
textColor: teal
---
Apply these standards at the boundary where a change is made. Automated checks catch many violations, but passing CI does not replace clear ownership or compatible contracts.
Keep business logic inside its owning service, preserve public contract compatibility, propagate
cancellation through asynchronous work, and never commit credentials. Do not introduce MediatR;
request handling uses the existing source-generated mediator.
## Rules and enforcement
| Area | Follow | How it is enforced |
| :------------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------- |
| Service design | Use Domain-Driven Design and Vertical Slice Architecture. Services own their business rules and persistence; do not add direct service-to-service project dependencies. | Architecture tests and review |
| C# | Prefer nullable-aware, file-scoped code. Seal endpoints, handlers, DbContexts, integration events, and test classes by default. Keep warnings actionable. | Compiler warnings as errors, Roslyn analyzers, architecture tests |
| Async work | Use `async`/`await` end to end and pass `CancellationToken` through every asynchronous boundary. | Analyzers and review |
| Requests and APIs | Keep endpoint handlers focused; use explicit API versions and apply authorization at the endpoint boundary. Validate input and return consistent errors. | Build checks, tests, and review |
| Messaging contracts | Name events `[Action][Entity]IntegrationEvent`. Publish only fields consumers need; preserve message identity and ownership metadata. | Pact contract tests and review |
| Protocol Buffers | Lint schemas, check backward compatibility, and regenerate the schema lock after an intentional change. | Buf checks and consumer coordination |
| PostgreSQL | Use `snake_case` for identifiers, columns, tables, and raw SQL. | Review and database tests |
| Frontend | Use Bun, keep workspace imports within the allowed dependency direction, avoid `any`, and provide accessible interactions. | Boundary checks, TypeScript checks, ESLint |
| Formatting | Apply the repository formatter to changed files; do not suppress a formatter or analyzer finding globally. | Git hooks and CI |
## Run the relevant checks
- **Backend:** `mise run build`, then the relevant test task from [[doc|development/005-testing]].
- **Frontend:** run `bun run boundaries`, `bun run check-types`, and `bun run lint` in the frontend workspace.
- **Protocol Buffers:** after installing Buf with `mise run setup:buf`, run `buf lint`, `buf breaking --against lock.binpb`, and `buf build -o lock.binpb` from the schema workspace. Commit the schema and refreshed lock together.
- **Formatting:** use `mise run format:cs`, `mise run format:fe`, or `mise run format:docs` for the changed area.
CI repeats the applicable format, analyzer, architecture, boundary, contract, and test checks. See [[doc|development/008-testing-matrix]] for which suites apply and [[doc|development/006-pull-request-process]] for merge requirements.
---
title: Testing Execution
summary: How to run backend, frontend, contract, browser, and documentation checks locally and interpret their results.
owners:
- architecture-enabling-team
badges:
- content: How-to Guide
backgroundColor: green
textColor: green
---
Use this guide to execute checks and diagnose their results. For the test-layer inventory, dependencies, and CI triggers, see [[doc|development/008-testing-matrix]].
## Run backend tests
Run the unit and architecture suites during backend iteration:
```bash
mise run test:unit
```
To run one project directly, replace `` with the relevant test project in `dotnet test `. Backend tests use TUnit on Microsoft.Testing.Platform.
Run consumer generation followed by provider verification:
```bash
mise run test:contracts
```
The task runs the consumer phase before the provider phase. Do not run provider verification against stale or missing consumer contracts.
Run unit, architecture, and contract tasks together:
```bash
mise run test
```
For coverage, run `mise run test:coverage`.
Use the Microsoft.Testing.Platform tree-node filter rather than VSTest's `--filter`:
```bash
dotnet test --treenode-filter ''
```
Replace the placeholders with the relevant test project and filter. For Pact tests, category filters look like `/*/*/*/*[Category=PactConsumer]` or `/*/*/*/*[Category=PactProvider]`. Select a test by its test-tree path when iterating on a single case.
## Frontend, browser, and documentation checks
Run Bun commands from the frontend workspace:
```bash
bun run boundaries
bun run check-types
bun run lint
bun run test
```
For browser journeys, install the Playwright browser once with `bunx turbo run playwright:install`, ensure the target application is already available, then run `bun run e2e`. The browser suite is not part of the shared pull-request test job; see [[doc|development/008-testing-matrix]].
Run documentation checks from the documentation workspace:
```bash
bun run check
bun run fitness
bun run build
```
## Understand results
- A passing run exits successfully with **zero failed tests**. Review skipped tests and ensure they were intentionally skipped.
- TUnit reports the discovered, passed, failed, and skipped test counts. Use the failed test name and assertion output to locate the first failure.
- If provider verification reports a missing or outdated contract, rerun `mise run test:contracts` so consumer contracts are generated first.
- CI publishes test and coverage reports as artifacts when the corresponding workflow produces them.
- No backend `.IntegrationTests` projects currently exist. Do not treat the absence of that layer as a failed or skipped suite.
Backend unit, architecture, and message contract suites do not require Docker. Browser end-to-end
checks require an available application environment; choose the appropriate test layer in
[[doc|development/008-testing-matrix]].
For frontend test scope and user-journey details, see [[doc|frontend/004-testing-and-quality-gates]]. For required pull-request checks, see [[doc|development/006-pull-request-process]].
---
title: Pull Request Process
summary: Prepare a focused draft, satisfy automated checks and review, and merge a contribution safely.
owners:
- architecture-enabling-team
badges:
- content: Workflow
backgroundColor: teal
textColor: teal
---
Open a pull request when the change is understandable, scoped, and locally verified. Keep it in draft while implementation or validation is still in progress.
_Pull Request Lifecycle_
## Before opening
- Keep the change to one cohesive outcome. Split unrelated work; discuss unusually broad changes before investing in them.
- Format changed files and run the relevant checks from [[doc|development/005-testing]].
- Use a Conventional Commit-style title, such as `fix: prevent duplicate checkout`.
- Include the user-visible or technical outcome, relevant context, test evidence, and any rollout or compatibility notes in the description.
## Move from draft to review
Push your branch and create a draft with the GitHub CLI or web interface. Link related work and state what remains before review.
```bash
gh pr create --draft --title ": " --body ""
```
Address unfinished work, update documentation when behavior or contracts change, and mark the pull request ready for review.
Required checks depend on changed areas. They can include backend formatting and analyzers, backend tests and contracts, frontend boundaries/types/lint/build/tests, documentation lint/fitness/build, and dependency review.
Check the current status with:
```bash
gh pr checks
```
Fix failures and push updates; changed commits rerun affected checks.
Address requested changes, keep the branch conflict-free, and request re-review when ready. Merge only after at least one maintainer approval and all required checks pass. Use the merge method enabled by the repository.
Do not disclose a security vulnerability in a public pull request or issue. Use the project's
private security reporting channel.
For branch naming and synchronization, see [[doc|development/003-development-workflow]]. For test-layer selection and commands, see [[doc|development/008-testing-matrix]] and [[doc|development/005-testing]].
---
title: How to troubleshoot local development
summary: Symptom-first fixes for local container, port, HTTPS, toolchain, and authentication failures.
owners:
- architecture-enabling-team
badges:
- content: Troubleshooting
backgroundColor: orange
textColor: orange
---
Use the symptom that matches the failure. Apply the exact fix, then repeat the command that originally failed. For initial setup, see [[doc|development/002-getting-started]].
## Docker and containers
**Symptom:** `mise run run` or `docker info` reports that Docker cannot connect.
**Likely Cause:** Docker Desktop is stopped, still starting, or its engine is unhealthy.
**Exact Fix:** Start Docker Desktop and wait for its engine to become ready. Run `docker info`; if it succeeds, retry `mise run run`. If a dependency remains unhealthy, inspect its Aspire console logs before changing local data.
**Symptom:** The dashboard shows a dependency or service as unhealthy, starting, or exited.
**Likely Cause:** A dependency is still initializing, the local container lacks resources, or the service reports a configuration error.
**Exact Fix:** In the dashboard, inspect the failing resource's console and structured logs. Confirm its dependency is healthy first, wait for first-boot initialization to finish, then retry. If Docker is resource constrained, close unrelated containers and allocate more memory to Docker Desktop.
## Ports
**Symptom:** Aspire or a development server fails to bind to a local port.
**Likely Cause:** Another application, an old development process, or a stale container owns that port.
**Exact Fix:** In PowerShell, identify the process listening on the reported port:
```powershell
Get-NetTCPConnection -LocalPort -State Listen |
Select-Object LocalAddress, LocalPort, OwningProcess
Get-Process -Id
```
Replace `` with the reported port and `` with the `OwningProcess` value. Stop only the confirmed conflicting process or container, then retry. Do not terminate an unknown process.
## HTTPS development certificates
**Symptom:** The browser shows a certificate warning or HTTPS requests fail certificate validation.
**Likely Cause:** The .NET development certificate is missing, expired, or not trusted by the operating system.
**Exact Fix:** Run `dotnet dev-certs https --trust`, accept the operating-system trust prompt, restart the browser, and retry. If the certificate still fails validation, run `dotnet dev-certs https --check` and follow its diagnostic output.
## Toolchain and PATH
**Symptom:** `dotnet`, `bun`, `node`, or `aspire` is not found, or its version differs from the project requirement.
**Likely Cause:** The project tool version is not installed or mise is not active in the current shell.
**Exact Fix:** Run `mise install`, reopen the terminal, then verify with `mise which dotnet`, `mise which bun`, and the relevant `--version` command. In PowerShell, activate mise for the current session with:
```powershell
mise activate pwsh | Out-String | Invoke-Expression
```
**Symptom:** `bun install` or `mise run prepare` fails with a runtime or package-manager version error.
**Likely Cause:** The shell is using a global tool version instead of the version selected for this workspace.
**Exact Fix:** Run `mise install`, open a new shell, confirm `bun --version` or `dotnet --version`, then retry the failed install command. Use Bun for JavaScript workspaces; do not mix package managers.
## Authentication and secrets
**Symptom:** An authenticated page returns `invalid_client`, a redirect mismatch, or an OAuth callback error.
**Likely Cause:** The local Entra application registration, client credentials, or callback URL does not match the application configuration.
**Exact Fix:** Confirm that the configured tenant and client identify the intended Entra application, that its credential is current, and that the registered redirect URL exactly matches the URL reported by the running application. Store local credentials in user secrets or environment variables; never commit them.
**Symptom:** A service exits with a missing-configuration error or Aspire prompts for an unset parameter.
**Likely Cause:** A required local parameter has not been supplied, or a credential was stored under a different setting name.
**Exact Fix:** Use the parameter name in the startup error and inspect the AppHost's stored values:
```bash
dotnet user-secrets list --project
dotnet user-secrets set "" "" --project
```
Replace placeholders with the exact project and setting from the error. Keep secrets out of source control and do not clear unrelated user secrets.
For the shortest clean startup, return to [[doc|development/000-local-quickstart]]. For broader environment choices, see [[doc|development/002-getting-started]].
---
title: Testing Matrix
summary: Reference tables for test scope, dependencies, local and CI execution triggers, and passing criteria.
owners:
- architecture-enabling-team
badges:
- content: Reference
backgroundColor: blue
textColor: blue
---
For commands, filters, and troubleshooting, see [[doc|development/005-testing]]. Frontend-specific guidance is in [[doc|frontend/004-testing-and-quality-gates]].
## Test layers
| Layer | Scope | Dependencies | Local trigger | Pull request trigger | Nightly trigger | Pass criteria |
| :-------------------------- | :------------------------------------------------------------------------------------------- | :-------------------------------------------------------- | :--------------------------------------------------------------------------------- | :-------------------------------------------- | :-------------- | :----------------------------------------------------------------------- |
| Backend unit | Nine service unit-test projects; domain and application behavior | In-memory doubles; no containers | `mise run test:unit` | Backend changes: Sonar analysis test job | None scheduled | All selected tests pass; no unexpected skips |
| Architecture | Service boundaries, dependency direction, and structural conventions | In-memory reflection checks; no containers | `mise run test:unit` | Backend changes: Sonar analysis test job | None scheduled | No architecture rules violated |
| Message contracts | Consumer message expectations and provider compatibility across seven contract-test projects | Generated Pact files and test doubles; no containers | `mise run test:contracts` | Backend changes: Sonar analysis test job | None scheduled | Consumer contracts generate and all selected provider verifications pass |
| Backend integration | Dedicated service tests against a composed backend and real dependencies | No dedicated `.IntegrationTests` projects currently exist | Not available | Not configured | Not configured | Not applicable until this layer is added |
| Frontend unit and component | UI and client logic across the frontend applications | Happy DOM, Testing Library, and MSW; no containers | `bun run test` in the frontend workspace | Frontend changes: affected test tasks | None scheduled | All affected tests pass |
| Frontend end-to-end | Browser user journeys and accessibility assertions | Playwright browser and an available target application | `bun run e2e` when a journey changes | Not run by the shared PR test job | None scheduled | Every selected journey and accessibility assertion passes |
| Documentation | MDX/frontmatter lint, formatting, fitness rules, and static build | Bun dependencies; no containers | `bun run check`, `bun run fitness`, `bun run build` in the documentation workspace | Documentation changes: documentation workflow | None scheduled | All checks pass and the site builds |
## Backend inventory
| Suite | Current scope | Docker required |
| :--------------------- | :-------------------------------------------------------- | :-------------- |
| Unit tests | Nine service test projects | No |
| Architecture tests | One repository-wide architecture suite | No |
| Message contract tests | Seven contract-test projects; consumer and provider cases | No |
| Integration tests | No dedicated backend integration-test projects | Not applicable |
## Trigger notes
| Trigger | What runs |
| :----------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Local | Choose the task matching the changed layer; use targeted project or tree-node filters during iteration. |
| Pull request | Path-filtered CI runs applicable backend, frontend, or documentation checks. Backend test execution is part of the analysis workflow for backend changes. |
| Nightly | No scheduled nightly run is configured for these test layers. |
---
title: Frontend Reference
summary: Architectural reference for BookWorm's multi-zone web platform, rendering and caching boundaries, authentication, client state, design governance, and observability.
owners:
- catalog-experience-team
badges:
- content: Frontend Reference
backgroundColor: blue
textColor: blue
---
BookWorm's frontend is a multi-zone web platform composed of three independent web applications—**Storefront**, **Commerce**, and **Backoffice**—served behind a single reverse-proxy **API Gateway** origin. Each surface is organized into domain-aligned vertical feature slices backed by layered shared foundations that enforce one-way dependencies, strict server-versus-client rendering boundaries, centralized authentication handoffs, and measurable accessibility and performance standards.
## Frontend Application Topology
The view below illustrates how customers and staff reach each web surface through the API Gateway, where identity boundaries sit, and how frontend surfaces connect to backend capability APIs.
## Reference Directory
| Topic | Scope | Primary Audience | Key Architectural Goal |
| :---------------------------------------------------------- | :--------------------------------------- | :--------------------------------------- | :--------------------------------------------------------------------------------- |
| [[doc\|frontend/001-monorepo-architecture]] | All web surfaces and shared layers | Frontend architects, tech leads | Enforce one-way dependencies and zero circular coupling |
| [[doc\|frontend/002-applications-and-routing]] | Storefront, Commerce, Backoffice | Architects, frontend engineers | Maintain clear surface ownership and deterministic gateway routing |
| [[doc\|frontend/003-data-fetching-and-state]] | Gateway transport and real-time channels | Frontend and API engineers | Standardize resilient requests, optimistic concurrency, and streaming |
| [[doc\|frontend/004-testing-and-quality-gates]] | Pre-merge and CI verification | Frontend engineers, QA leads | Catch boundary, accessibility, and journey regressions before release |
| [[doc\|frontend/005-accessibility]] | Shared UI system and theming | Frontend engineers, designers | Govern reusable accessible primitives, tokens, and responsive rules |
| [[doc\|frontend/006-microfrontend-architecture]] | Customer zone split | Solutions and frontend architects | Isolate public catalog caching from private checkout workflows |
| [[doc\|frontend/007-architecture-and-state-design]] | Client state and feature slices | Frontend tech leads, engineers | Keep server state and ephemeral UI state strictly separated |
| [[doc\|frontend/008-accessibility-principles]] | WCAG 2.1 Level AA defense | Frontend engineers, UX leads | Combine static, automated, keyboard, and live-region safeguards |
| [[doc\|frontend/009-add-customer-page]] | New customer capabilities | Frontend engineers | Route, protect, and validate new customer pages without prefix collisions |
| [[doc\|frontend/010-rendering-and-caching-strategy]] | Server/client rendering and caching | Frontend architects, engineers | Maximize edge/server cacheability for public pages and freshness for private flows |
| [[doc\|frontend/011-authentication-and-session-boundaries]] | Identity, sessions, and UI gating | Security, solutions, frontend architects | Enforce consistent session ownership and defense-in-depth authorization |
| [[doc\|frontend/012-performance-and-observability]] | Web Vitals, telemetry, resilience | Frontend architects, SREs | Sustain fast perceived load times, end-to-end traces, and graceful degradation |
---
title: Workspace & Dependency Tiers
summary: Four-tier dependency model separating application surfaces, domain capabilities, shared foundations, and tooling presets across the frontend workspace.
owners:
- catalog-experience-team
badges:
- content: Architecture
backgroundColor: purple
textColor: purple
- content: Reference
backgroundColor: blue
textColor: blue
---
## Purpose & Scope
This reference defines the structural dependency model governing BookWorm's three web surfaces—**Storefront**, **Commerce**, and **Backoffice**—and their shared platform libraries. It establishes strict one-way dependency tiers so domain UI, transport contracts, and configuration presets remain reusable without circular coupling.
## Workspace Tier Hierarchy
The visual below illustrates how dependencies flow strictly downward from deployable web surfaces through domain capabilities and shared foundations to configuration presets.
## Architectural Principles & Rules
- **Strict one-way dependency flow:** Higher tiers may depend on lower tiers, never the reverse. Application surfaces consume domain and foundation layers; domain capabilities consume foundations; foundations remain independent of domain UI.
- **Direct source composition:** Shared layers resolve directly from source within the workspace rather than through intermediate package registries, keeping cross-surface changes atomic while automated boundary checks prevent illegal imports.
- **Composable capability configuration:** Environment validation, telemetry startup, and API contracts are split into focused capability modules so each surface only adopts what its runtime requires.
Shared domain and foundation modules must never import from an application surface. Any capability
needed by more than one surface belongs in the domain or foundation tier before it is consumed.
## Patterns & Boundaries
| Concern / Surface | Architectural Approach | Responsibility Boundary | Key Trade-off |
| :------------------- | :---------------------------------------------------------------------------------------------- | :--------------------------------------------------------------- | :--------------------------------------------------------------------------------- |
| **Application Tier** | Independent deployable web surfaces (**Storefront**, **Commerce**, **Backoffice**) | Owns route entrypoints, surface layouts, and feature composition | Separate deployments require explicit shared shell contracts for visual continuity |
| **Domain Tier** | Shared UI system, customer shell, transport clients, query factories, auth, SEO, and validation | Owns reusable business-aligned UI and typed service integration | Changes to shared customer shell trigger rebuilds across both customer surfaces |
| **Foundation Tier** | Pure domain types, environment schemas, telemetry initialization, and stateless utilities | Owns cross-cutting primitives with zero UI or framework coupling | Must remain free of React, routing, or domain-specific business logic |
| **Config Tier** | Standardized linting, type-checking, test harness, and build presets | Owns engineering standards and quality gate definitions | Centralizing presets enforces uniformity but requires coordinated upgrades |
- **Storefront:** Public customer discovery, catalog browsing, customer reviews, conversational AI assistant, and customer authentication ownership.
- **Commerce:** Authenticated customer transactions including shopping basket, checkout confirmation, customer profile, and order history.
- **Backoffice:** Staff administration dashboard covering inventory management, catalog taxonomy, buyer directory, order lifecycle actions, and review moderation.
## Quality & Operational Impact
- **Maintainability:** Automated boundary enforcement prevents spaghetti dependencies and keeps domain logic portable across surfaces.
- **Build & CI Efficiency:** Scoped dependency graphs enable affected-only validation so isolated surface changes do not needlessly rebuild unrelated layers.
- **Security & Reliability:** Isolating environment schemas and authentication adapters in lower tiers ensures consistent validation and session handling across all surfaces.
---
title: Applications & Zone Routing
summary: Surface boundaries across Storefront, Commerce, and Backoffice, reverse-proxy gateway precedence, and search indexing scope.
owners:
- catalog-experience-team
badges:
- content: Architecture
backgroundColor: purple
textColor: purple
- content: Reference
backgroundColor: blue
textColor: blue
---
## Purpose & Scope
This reference defines the application boundaries and ingress routing rules across BookWorm's three web surfaces: **Storefront**, **Commerce**, and **Backoffice**. It governs how external requests enter through a single **API Gateway** origin, how zone precedence resolves overlapping paths, and which surfaces are exposed to public search indexing.
## Surface & Gateway Routing Topology
The visual below shows how customer and staff requests enter the single-origin **API Gateway** and route deterministically to backend capability APIs, the external identity provider, or the owning frontend surface.
## Architectural Principles & Rules
- **Single public origin:** All browser traffic enters through the **API Gateway** reverse proxy. Frontend surfaces and backend APIs run on internal ingress only and are never exposed directly to end users.
- **Deterministic precedence:** Backend API prefixes and identity provider routes match ahead of general frontend routes. **Storefront** acts as the lowest-priority catch-all surface for public customer discovery.
- **Exact-match collision resolution:** Where a customer page shares a top-level path segment with a backend API domain (such as the shopping basket page versus basket data operations), exact page routes take higher precedence than wildcard API prefixes.
- **Isolated static assets:** Each customer zone serves its static scripts, styles, and media under a distinct asset prefix so deployments never collide on shared paths.
- **Zone observability:** The gateway stamps every frontend response with a zone identifier header to support rapid routing diagnostics.
**Storefront** is the only surface configured for public search indexing and structured metadata.
**Commerce** and **Backoffice** serve private, user-specific or staff-only workflows and must
remain excluded from search engine crawlers.
## Patterns & Boundaries
| Concern / Surface | Architectural Approach | Responsibility Boundary | Key Trade-off |
| :---------------- | :------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------ |
| **Storefront** | Public catch-all zone with aggressive component caching and structured SEO metadata | Owns landing showcase, catalog discovery, book details, reviews, customer auth, and AI assistant | Catch-all ownership means new top-level routes in other zones must be explicitly registered |
| **Commerce** | Explicit transactional zone with dynamic, uncached rendering and crawler exclusion | Owns shopping basket, checkout confirmation, customer account, and order history | Depends on **Storefront** for initial sign-in handoff while sharing the origin session |
| **Backoffice** | Isolated staff zone mounted under a dedicated administrative base path | Owns KPI dashboard, catalog CRUD, customer management, order operations, and review moderation | Requires explicit staff role enforcement and separate authentication scopes |
| **API Gateway** | Reverse proxy reading a shared customer routing manifest alongside backend route rules | Owns TLS termination, CORS enforcement, prefix stripping, and zone header tagging | Adding a top-level **Commerce** route requires updating the shared routing manifest |
- **Catalog & Discovery:** Backed by **Catalog API** and **Rating API** for book details, taxonomy directories, and customer feedback.
- **Shopping & Ordering:** Backed by **Basket API** and **Ordering API** for cart persistence, checkout, and order lifecycle tracking.
- **Conversational Discovery:** Backed by **Chat API** through a dedicated server-side assistant runtime in **Storefront**.
## Quality & Operational Impact
- **User Experience:** Serving **Storefront** and **Commerce** behind one origin eliminates cross-domain redirects, cookie-scoping friction, and CORS complexity for shoppers.
- **Performance:** Isolating **Storefront** from transactional **Commerce** workflows allows public catalog pages to be aggressively cached without risking stale basket or order data.
- **Security:** Internal-only container ingress ensures all traffic passes through gateway routing, CORS, and identity boundaries.
---
title: Data Flow & Gateway Integration
summary: Typed transport contracts, retry and idempotency rules, optimistic concurrency with ETags, and real-time streaming channels.
owners:
- catalog-experience-team
badges:
- content: Architecture
backgroundColor: purple
textColor: purple
- content: Reference
backgroundColor: blue
textColor: blue
---
## Purpose & Scope
This reference governs how **Storefront**, **Commerce**, and **Backoffice** communicate with backend capability services (**Catalog API**, **Basket API**, **Ordering API**, **Rating API**, and **Chat API**) through the **API Gateway**. It defines transport standardization, resilience policies, optimistic concurrency controls, and real-time streaming patterns.
## Layered Data Flow
The visual below traces how feature slices interact with server query caches, minimal client state, resilient HTTP transport, and real-time streaming channels across the gateway boundary.
## Architectural Principles & Rules
- **Gateway-only communication:** Frontend surfaces never call internal backend services directly; every request routes through the **API Gateway** using shared, typed domain contracts.
- **Safe retry & idempotency discipline:** Transient timeouts, rate-limit responses (honoring server retry-after hints), and safe read methods retry automatically with bounded backoff. Non-idempotent writes only retry when carrying an explicit request idempotency identifier.
- **Optimistic concurrency for staff edits:** Mutable administrative resources in **Backoffice** (such as catalog items and order summaries) exchange entity tags (`ETag`) on reads and require matching preconditions on updates to prevent silent lost updates.
- **Zero-retry on authorization & conflict failures:** Missing credentials or stale precondition conflicts never retry automatically; the UI surfaces explicit re-authentication or reload-and-merge prompts.
Feature components must consume centralized query and mutation abstractions rather than issuing
raw network requests. This guarantees uniform authorization token injection, correlation headers,
retry rules, and cache key consistency.
## Patterns & Boundaries
| Concern / Surface | Architectural Approach | Responsibility Boundary | Key Trade-off |
| :------------------------------ | :------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------ |
| **Standard REST & Query Reads** | Centralized typed HTTP client with normalized cache keys and bounded retries | Shared transport layer handles headers, retries, and error classification; feature slices handle presentation | Slight abstraction overhead compared to inline fetches, repaid in consistent error and retry behavior |
| **Optimistic Concurrency** | Conditional reads and precondition-guarded writes via `ETag` headers | **Backoffice** surfaces detect precondition conflicts and prompt staff to refresh before overwriting | Requires staff to resolve concurrent edits manually rather than silent last-write-wins |
| **Dashboard Metrics Stream** | Initial snapshot load followed by authenticated Server-Sent Events (SSE) with exponential backoff | **Backoffice** dashboard subscribes to live ordering metrics; **Ordering API** pushes incremental updates | Maintains persistent connection per active admin session; falls back cleanly via bounded reconnects |
| **Conversational AI Stream** | Server-side assistant runtime forwarding customer identity to **Chat API** over AG-UI | **Storefront** mediates streaming responses and declarative UI cards; **Chat API** owns agent orchestration | Adds a lightweight server-side proxy hop in **Storefront** to keep agent integration decoupled from browser clients |
- **Not Modified:** Conditional reads retain the existing cached entity without re-downloading payloads.
- **Unauthorized:** Immediate halt of retries; customer surfaces redirect to sign-in while preserving the return destination.
- **Timeout / Rate Limited:** Automatic bounded retry respecting server-provided backoff windows.
- **Precondition Failed:** Explicit conflict notification in **Backoffice** prompting the operator to reload the latest state.
- **Server Errors:** Retried only for idempotent operations or writes carrying a correlation idempotency key.
## Quality & Operational Impact
- **Reliability:** Bounded retries with idempotency safeguards absorb transient network blips without creating duplicate orders or basket mutations.
- **Data Integrity:** `ETag` precondition checks protect **Backoffice** operators from accidentally overwriting concurrent catalog or order updates.
- **Responsiveness:** Real-time SSE and AG-UI streaming deliver live operational metrics and conversational AI responses without polling overhead.
---
title: Quality Gates & Verification
summary: Static boundary enforcement, isolated component testing, end-to-end journey validation, and production build gates across all frontend surfaces.
owners:
- catalog-experience-team
badges:
- content: Architecture
backgroundColor: purple
textColor: purple
- content: Reference
backgroundColor: blue
textColor: blue
---
## Purpose & Scope
This reference defines the mandatory verification pyramid and release quality gates for **Storefront**, **Commerce**, **Backoffice**, and shared workspace layers. It ensures architectural boundaries, type safety, accessibility rules, and end-to-end user journeys are validated before code reaches production.
## Verification Pipeline
Every change to frontend surfaces or shared layers progresses through sequential automated gates before merge:
Automated checks verify uniform code formatting, strict workspace tier boundaries (preventing upward or circular imports), strict type checking, and zero-warning linting including static accessibility rules.
Offline component and logic suites execute against deterministic mock service handlers and synthetic data factories, validating business rules, form schemas, and accessible DOM semantics without requiring live backend containers.
Full production builds compile all three Next.js surfaces, validating Server/Client Component boundaries, environment schema completeness, and microfrontend routing manifests.
Behavior-driven browser suites exercise real customer journeys (catalog discovery, authentication, AI assistant, basket, and checkout across **Storefront** and **Commerce**) and staff workflows in **Backoffice**, alongside automated `axe-core` contrast and landmark audits.
Linting and type-checking operate with zero tolerance for warnings. Any static accessibility
violation, illegal tier import, or type mismatch blocks pull request integration.
## Patterns & Boundaries
| Concern / Surface | Architectural Approach | Responsibility Boundary | Key Trade-off |
| :---------------------------- | :---------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------ |
| **Boundary & Type Gates** | Workspace-wide tier validation and strict type checking with affected-task caching | Shared config tier defines rules; CI enforces across all surfaces and libraries | Requires contributors to place shared abstractions in the proper tier upfront |
| **Isolated Component Tests** | Deterministic mock API handlers with per-worker isolated storage | Feature slices own unit/component specs; shared mock layer owns contract parity | Fast offline feedback, but cannot catch gateway routing or real session-cookie issues |
| **End-to-End BDD Suites** | Gherkin-backed browser journeys covering **Storefront**, **Commerce**, and **Backoffice** | **Storefront** suite covers cross-zone customer checkout; **Backoffice** suite covers staff CRUD | Higher execution cost; requires running gateway and target surfaces |
| **Unified Quality Reporting** | Aggregated test and defect categorization across all three surfaces | Shared reporting config normalizes failures across unit and browser runs | Adds post-test aggregation step in CI pipelines |
- **Storefront:** Covered by unit/component tests and 9 end-to-end behavioral suites spanning discovery, AI chat, authentication, accessibility, and cross-zone checkout.
- **Commerce:** Covered by unit/component tests; its end-to-end basket and checkout journeys are validated through the **Storefront** gateway suite.
- **Backoffice:** Covered by unit/component tests and 6 end-to-end behavioral suites covering authentication, catalog, customers, orders, and review moderation.
## Quality & Operational Impact
- **Architectural Integrity:** Continuous boundary checks guarantee that the four-tier dependency model does not erode over time.
- **Release Confidence:** Combining fast offline mock tests with real cross-zone browser journeys catches both logic regressions and gateway routing/auth integration defects.
- **Accessibility Assurance:** Enforcing static accessibility rules alongside browser `axe-core` checks prevents common UI regressions from reaching production.
---
title: Design System & UI Governance
summary: Shared accessible UI primitives, design tokens, responsive standards, and internationalization readiness across all frontend surfaces.
owners:
- catalog-experience-team
badges:
- content: Architecture
backgroundColor: purple
textColor: purple
- content: Reference
backgroundColor: blue
textColor: blue
---
## Purpose & Scope
This reference defines the UI governance model, shared component system, theming standards, and responsive design rules for **Storefront**, **Commerce**, and **Backoffice**. It ensures visual consistency, accessible interaction patterns, and long-term maintainability across customer and staff experiences.
## Architectural Principles & Rules
- **Headless accessible primitives first:** Interactive controls (dialogs, menus, popovers, selects, tabs) must be built on shared headless primitives that provide standardized ARIA roles, keyboard navigation, focus trapping, and focus restoration out of the box.
- **Token-driven styling:** Colors, typography, spacing, and elevation are governed by centralized design tokens rather than ad-hoc per-app values, ensuring WCAG-compliant contrast ratios across themes.
- **Shared customer chrome:** **Storefront** and **Commerce** share a unified navigation shell (header, footer, mobile bottom bar, basket indicator, and cross-zone links) so shoppers never perceive a visual seam when crossing microfrontend boundaries.
- **Mobile-first responsive discipline:** Customer surfaces prioritize touch-friendly targets, responsive grids, and zoom-safe layouts (remaining readable up to 200% zoom without horizontal overflow); **Backoffice** optimizes for dense data tables with responsive horizontal scrolling and clear hierarchy.
- **Internationalization readiness:** User-facing formatting (currency, dates, numbers) routes through centralized locale-aware utilities rather than hardcoded string concatenation, and layouts avoid fixed pixel widths that break under translated text expansion.
Never hand-roll custom modal dialogs, dropdowns, or form controls inside an application feature
slice. Extend or compose the shared UI primitive library so keyboard, focus, and contrast
guarantees apply uniformly.
## Patterns & Boundaries
| Concern / Surface | Architectural Approach | Responsibility Boundary | Key Trade-off |
| :----------------------- | :------------------------------------------------------------------------------------------------ | :---------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------- |
| **Shared UI Primitives** | Centralized component library wrapping accessible headless primitives and utility tokens | Domain UI layer owns reusable primitives; feature slices own domain composition | Changes to core primitives affect all three surfaces and require cross-app regression checks |
| **Customer Shell** | Shared header, footer, mobile navigation, and basket badge across **Storefront** and **Commerce** | Domain shell layer owns chrome; **Storefront** and **Commerce** inject page content | Couples customer shell releases across both customer zones |
| **Theming & Contrast** | Semantic design tokens for surfaces, text, borders, and status states | Design tokens enforce 4.5:1 normal text and 3:1 UI/large text contrast | Restricts arbitrary one-off colors in feature components |
| **Validation & Forms** | Schema-driven form validation paired with explicit field labels and error associations | Shared validation layer owns schemas; feature slices own form layout | Adds upfront schema definition before rendering forms |
- **Touch & Viewport:** Interactive controls maintain minimum touch target sizing on mobile viewports, and **Storefront** provides dedicated bottom navigation for thumb-friendly browsing.
- **Text Expansion & Zoom:** Layouts use flexible containers and relative units so content reflows cleanly at mobile widths and 200% browser zoom.
- **Locale-Safe Formatting:** Price, date, and order-status formatting are encapsulated in shared utilities to simplify future multi-locale expansion.
## Quality & Operational Impact
- **Visual Continuity:** Customers transition seamlessly between **Storefront** discovery and **Commerce** checkout with identical chrome and interaction behavior.
- **Engineering Velocity:** Teams compose pre-verified, accessible building blocks instead of rebuilding dialogs, tables, and form controls per surface.
- **Inclusive Compliance:** Tokenized contrast and headless primitives eliminate entire classes of keyboard and screen-reader defects at authoring time.
---
title: Multi-Zone Composition
summary: Why BookWorm splits customer discovery and authenticated checkout into two zones behind one gateway origin, and how cross-zone navigation works.
owners:
- catalog-experience-team
badges:
- content: Architecture
backgroundColor: purple
textColor: purple
- content: Reference
backgroundColor: blue
textColor: blue
---
## Purpose & Scope
This reference explains BookWorm's multi-zone microfrontend architecture for customer-facing experiences: **Storefront** (public discovery) and **Commerce** (authenticated shopping and account management). It defines why these two zones are separated behind a single **API Gateway** origin and how they coordinate routing, assets, and authentication.
## Cross-Zone Sign-In Handoff
The visual below illustrates how an unauthenticated shopper crossing from **Storefront** into a protected **Commerce** route is redirected to **Storefront**'s identity handoff and returned seamlessly to their destination.
## Architectural Principles & Rules
- **Workload isolation by caching profile:** Public catalog discovery (**Storefront**) and private transactional workflows (**Commerce**) run as separate application deployments so aggressive component caching and SEO optimization never risk leaking user-specific basket or order state.
- **Single-origin presentation:** Both customer zones share one HTTPS origin via the **API Gateway**, eliminating cross-domain cookie complexity, extra identity redirect URIs, and CORS overhead.
- **Shared routing manifest:** Both the reverse proxy and the microfrontend framework read a single authoritative route manifest so path ownership and static asset prefixes stay synchronized.
- **Document-level zone isolation:** Transitions across the **Storefront**–**Commerce** boundary use full-document navigation with prefetching rather than runtime bundle federation, preventing React tree or global state coupling across independent deployments.
**Storefront** owns the customer authentication callback and identity provider integration.
**Commerce** does not host its own login handler; it validates the shared origin-scoped session
cookie and redirects unauthenticated visitors back to **Storefront**'s sign-in flow.
## Patterns & Boundaries
| Concern / Surface | Architectural Approach | Responsibility Boundary | Key Trade-off |
| :------------------------ | :------------------------------------------------------ | :---------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------- |
| **Zone Split** | Two independent web runtimes behind one **API Gateway** | **Storefront** owns discovery and AI chat; **Commerce** owns basket, checkout, and orders | Two customer containers to operate, repaid by independent scaling and cache isolation |
| **Asset Isolation** | Dedicated asset prefix per non-root zone | **Commerce** serves static bundles under an isolated asset path | Prevents static asset collisions, but requires gateway route registration for zone assets |
| **Shared Chrome** | Build-time shared customer shell package | Shared shell owns header, footer, mobile nav, and basket indicator | Visual consistency without runtime federation; shell updates rebuild both customer apps |
| **Cross-Zone Navigation** | Prefetched cross-zone link abstraction | Shared shell provides zone-aware links; browser performs clean runtime handoff | Slightly heavier transition across zones than intra-app routing, mitigated by prefetching |
- **Single customer monolith:** Couples public catalog caching, heavy conversational AI dependencies, and private checkout routes into one build and failure domain.
- **Separate subdomains:** Simplifies path routing, but introduces cross-subdomain cookie scoping, fragmented SEO authority, and multiple identity callback registrations.
- **Client-side Module Federation:** Avoids document reloads across zones, but introduces bundler runtime coupling, version-skew risks across Server Components, and complex hydration.
## Quality & Operational Impact
- **Deployment Agility:** Teams can release **Storefront** catalog or AI assistant updates without redeploying or risking **Commerce** checkout stability.
- **Security & Privacy:** Separating caching profiles at the application boundary provides defense-in-depth against accidental caching of authenticated customer data.
- **Reliability:** A fault or memory spike in conversational AI streaming remains isolated to **Storefront** and cannot degrade **Commerce** checkout.
---
title: Client State & Feature Slices
summary: Separation of server cache from ephemeral UI state, thin route entrypoints, vertical feature slices, and client error boundaries.
owners:
- catalog-experience-team
badges:
- content: Architecture
backgroundColor: purple
textColor: purple
- content: Reference
backgroundColor: blue
textColor: blue
---
## Purpose & Scope
This reference governs internal application structure and client-side state management across **Storefront**, **Commerce**, and **Backoffice**. It defines how route entrypoints stay thin, how vertical feature slices mirror backend bounded contexts, and how server cache is strictly separated from ephemeral UI state.
## Architectural Principles & Rules
- **Thin route entrypoints:** Application route files only declare page metadata, loading/error boundaries, and server-side data prefetching, delegating all presentation and interaction logic to domain-aligned feature slices.
- **Vertical feature slices:** Inside each surface, UI components, filters, forms, and state are grouped by business capability (Catalog, Shopping, Ordering, Reviews) rather than technical file type, mirroring backend service boundaries.
- **Strict state separation:** Remote domain data lives exclusively in the server-state query cache (hydrated from server prefetching); ephemeral client state (session-derived flags, feature toggles, derived basket badge counts) lives in lightweight atomic state.
- **Auth-gated background queries:** Customer-specific queries such as basket state are gated on authenticated session status so anonymous visitors never trigger failing unauthorized requests.
- **Explicit error & loading boundaries:** Every route segment defines declarative loading skeletons and error boundaries so transient failures degrade gracefully within the affected slice without crashing the entire page shell.
Never duplicate backend entities (books, orders, reviews, or basket items) into a manual global
client store. Use the centralized query cache so deduplication, SSR hydration,
stale-while-revalidate, and invalidation remain consistent.
## Patterns & Boundaries
| Concern / Surface | Architectural Approach | Responsibility Boundary | Key Trade-off |
| :-------------------------- | :-------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------- |
| **Route Entrypoints** | Thin server wrappers handling metadata, prefetch hydration, and error/loading boundaries | Route layer owns URL mapping and SSR handoff; feature slices own UI and interactions | Adds one layer of indirection, repaid by clean Server/Client Component boundaries |
| **Server State Cache** | Centralized query client (per-request on server, singleton in browser) with shared cache keys | Shared query layer owns keys, stale windows, and hydration; feature slices consume hooks | Requires disciplined cache key invalidation on mutations |
| **Ephemeral Client State** | Minimal atomic state for auth flags, derived basket counts, and feature toggles | Customer shell owns cross-zone session/basket atoms; apps own local feature flags | Contributors must distinguish server state from client-only UI state |
| **Conversational AI State** | Streaming AG-UI client runtime with declarative generative UI cards (**Storefront** only) | **Storefront** manages chat session UI and live announcements; **Chat API** owns agent state | Real-time token streaming requires dedicated accessibility pacing |
- **Basket Mutations:** Interactive basket updates invalidate the shared basket query key and update derived badge counts immediately, rolling back cleanly if the backend rejects the change.
- **Staff Edits (Backoffice):** Resource updates avoid blind optimistic overwrites; instead, they pair `ETag` preconditions with explicit conflict banners so operators can inspect and reload concurrent changes.
- **Boundary Isolation:** Route-level error boundaries capture unexpected rendering errors and offer retry actions without losing top-level navigation chrome.
## Quality & Operational Impact
- **Predictability:** Single-source cache keys prevent hydration mismatches between server-rendered HTML and client-side query caches.
- **Performance:** Per-request server query clients prevent cross-user data leaks while pre-hydrating initial views for fast first paint.
- **Maintainability:** Vertical feature slices allow teams to evolve Catalog, Shopping, Ordering, or Reviews UI independently without cross-feature coupling.
---
title: Accessibility & Inclusive UX
summary: WCAG 2.1 Level AA target, four-layer accessibility defense, streaming AI chat announcements, and barrier reporting governance.
owners:
- catalog-experience-team
badges:
- content: Architecture
backgroundColor: purple
textColor: purple
- content: Reference
backgroundColor: blue
textColor: blue
---
## Purpose & Scope
This reference defines BookWorm's accessibility architecture across **Storefront**, **Commerce**, and **Backoffice**, targeting **WCAG 2.1 Level AA**. Because automated scanners detect only a fraction of real-world barriers—particularly around keyboard focus management and streaming AI responses—BookWorm enforces a four-layer defense from authoring time through runtime assistive-technology behavior.
## Four-Layer Accessibility Defense
The visual below illustrates how static linting, browser audits, keyboard focus management, and paced live announcements reinforce each other across development and runtime.
## Architectural Principles & Rules
- **Full keyboard operability:** Every interactive workflow—including catalog filtering, modal dialogs, and end-to-end checkout across **Storefront** and **Commerce**—must be operable without a mouse, with a visible skip-to-main-content link and predictable focus order.
- **Focus trapping & restoration:** Modal dialogs, drawers, and popovers must trap focus while open, dismiss on `Escape`, and restore focus to the triggering control upon closure.
- **Semantic landmarks & headings:** Every page must expose proper landmark regions (`main`, `navigation`, `contentinfo`), a single top-level heading, and non-skipped heading levels.
- **Non-color cues & contrast:** Text and interactive borders must meet WCAG 2.1 Level AA contrast ratios (4.5:1 normal text, 3:1 large text and UI components), and status or validation errors must never rely on color alone.
- **Paced live announcements:** Dynamic status updates (offline notices, rate-limit alerts, basket updates, and **Storefront**'s streaming AI assistant) must announce through `aria-live` regions without flooding screen readers during token streaming.
Unthrottled conversational AI token streams can overwhelm screen readers. **Storefront**
integrates generative accessibility adapters with the AG-UI stream so assistant responses, tool
calls, and interactive cards announce at a readable pace.
## Patterns & Boundaries
| Concern / Surface | Architectural Approach | Responsibility Boundary | Key Trade-off |
| :------------------------------------ | :-------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------ |
| **Layer 1: Primitives & Static Lint** | Headless accessible UI primitives paired with zero-warning static accessibility linting | Shared UI and lint config enforce baseline ARIA and semantic rules at authoring time | Cannot detect runtime contrast, focus traps, or screen-reader pacing |
| **Layer 2: Browser Audits** | Automated `axe-core` contrast and landmark checks inside end-to-end browser suites | **Storefront** suite verifies customer discovery and **Commerce** checkout journeys | Requires running browser stack; **Backoffice** relies on static lint and unit queries |
| **Layer 3: Keyboard & Focus** | Skip links, logical tab order, focus traps, and `Escape` restoration | Shared UI primitives provide focus mechanics; feature slices verify page-level tab flow | Requires manual keyboard verification on complex custom layouts |
| **Layer 4: Live Announcements** | `aria-live` regions and generative accessibility adapters for AI streams | Feature slices own status regions; **Storefront** AI integration owns stream pacing | Adds integration surface tied to conversational UI events |
- **Supported Environments:** Modern desktop and mobile browsers, keyboard-only navigation, and standard screen-reader workflows.
- **Barrier Reporting:** Accessibility barriers are tracked via dedicated issue templates capturing affected surface, reproduction steps, assistive technology, and severity.
- **Security Boundary:** Contributors and users must never include passwords, tokens, or private data in public accessibility reports.
## Quality & Operational Impact
- **Inclusivity:** Keyboard-only and screen-reader users can complete discovery, AI-assisted search, basket management, and checkout independently.
- **Early Defect Prevention:** Catching missing labels and invalid ARIA at lint time is significantly faster and cheaper than fixing them after UI release.
- **AI Usability:** Paced live announcements make conversational AI genuinely usable for assistive-technology users rather than noisy or disorienting.
---
title: Customer Surface Onboarding
summary: Architectural decision flow for placing, registering, protecting, and verifying new customer-facing routes across Storefront and Commerce.
owners:
- catalog-experience-team
badges:
- content: Architecture
backgroundColor: purple
textColor: purple
- content: Reference
backgroundColor: blue
textColor: blue
---
## Purpose & Scope
This reference defines the architectural onboarding workflow when introducing a new customer-facing capability or route across BookWorm's two customer zones: **Storefront** and **Commerce**. It ensures new pages land in the right caching and authentication boundary, avoid **API Gateway** prefix collisions, and integrate cleanly with the shared customer shell.
## Onboarding Decision Flow
Assign the capability to **Storefront** if it is public, cacheable, and search-indexed (catalog, editorial content, reviews). Assign it to **Commerce** if it is authenticated, user-specific, and must never be cached (basket, checkout, account, orders).
Confirm the chosen URL segment does not collide with reserved backend capability prefixes (Catalog, Basket, Ordering, Rating, Chat, Identity) or the **Backoffice** administrative base path.
Define a thin route entrypoint for metadata and server prefetching, and place all interactive UI, validation schemas, and query hooks inside a domain-aligned feature slice.
If placed in **Commerce**, register the new top-level path pattern in the shared microfrontend routing manifest and add it to the edge session-protection list so unauthenticated visitors redirect to sign-in with a return URL. **Storefront** routes require no manifest entry because **Storefront** owns the catch-all fallback zone.
Use the shared customer shell's zone-aware link component when linking between **Storefront** and **Commerce**, then verify gateway routing via the zone response header and run all static, unit, and build quality gates.
Never introduce new customer routes under reserved backend API prefixes. Existing exact-match
exceptions (such as the shopping basket page sharing a top-level segment with basket API
operations) are special-cased in gateway precedence and must not be replicated for new features.
## Patterns & Boundaries
| Concern / Surface | Architectural Approach | Responsibility Boundary | Key Trade-off |
| :--------------------- | :--------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------- |
| **Zone Placement** | Public/cacheable -> **Storefront**; Private/dynamic -> **Commerce** | Product and frontend leads decide placement based on cacheability and auth requirements | Misplacing a private page in **Storefront** risks accidental caching or crawler exposure |
| **Gateway Manifest** | Single shared routing manifest consumed by both **API Gateway** and Next.js zones | **Commerce** top-level routes must be explicitly listed; **Storefront** catches all remainder | Requires coordinated gateway + frontend update for new top-level **Commerce** prefixes |
| **Session Protection** | Edge proxy guard on **Commerce** routes redirecting unauthenticated requests to **Storefront** login | **Commerce** enforces route-level cookie presence; backend APIs enforce token authorization | Protects private UI shells without duplicating login handlers |
| **Cross-Zone Links** | Zone-aware navigation links in the shared customer shell | Shared shell owns navigation chrome and prefetch behavior | Full-document reload when crossing zones, traded for clean runtime isolation |
## Quality & Operational Impact
- **Zero Routing Surprises:** Checking reserved prefixes and manifest registration upfront prevents `404` or backend JSON collision errors in production.
- **Security by Default:** Enforcing edge session guards on **Commerce** routes ensures unauthenticated users are cleanly redirected before rendering private layouts.
- **Consistent UX:** Using the shared customer shell keeps navigation, basket state, and accessibility landmarks uniform across every new customer page.
---
title: Rendering & Caching Strategy
summary: Server versus client rendering boundaries, streaming SSR, component caching profiles, cache invalidation, and gateway interaction patterns.
owners:
- catalog-experience-team
badges:
- content: Architecture
backgroundColor: purple
textColor: purple
- content: Reference
backgroundColor: blue
textColor: blue
---
## Purpose & Scope
This reference defines the rendering and caching architecture across **Storefront**, **Commerce**, and **Backoffice**. It establishes where Server Components, streaming SSR, component caching, and Client Components are used, how server-prefetched data hydrates the browser cache, and how cache invalidation operates across public and private surfaces.
## Rendering and Data Hydration Flow
The visual below illustrates how initial page requests render on the server, dehydrate prefetched data into the client query cache, and hand off interactive mutations and streams through the **API Gateway**.
## Architectural Principles & Rules
- **Server-first rendering:** Routes default to Server Components for initial layout, SEO metadata, and data prefetching. Client Components are pushed to interactive leaf islands (filters, forms, basket controls, and conversational AI).
- **Surface-level caching isolation:** **Storefront** enables component-level caching for public catalog and editorial content. **Commerce** and **Backoffice** disable component caching entirely so personalized basket, checkout, order, and administrative views always render fresh per request.
- **Per-request server query isolation:** Server rendering creates an isolated query client per incoming HTTP request and dehydrates settled and pending queries to the browser, preventing cross-user data leakage while avoiding client-side loading waterfalls.
- **Mutation-driven cache invalidation:** Client mutations invalidate domain-scoped query keys upon success, while **Backoffice** pairs conditional reads with `ETag` preconditions to avoid serving stale edits.
Never enable shared component caching or static route caching on **Commerce** or **Backoffice**
routes. User-specific basket, order, and staff data must always bypass shared server caches.
## Patterns & Boundaries
| Concern / Surface | Architectural Approach | Responsibility Boundary | Key Trade-off |
| :--------------------------------- | :------------------------------------------------------------------------ | :--------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------- |
| **Public Discovery (Storefront)** | Server-rendered pages with component caching and structured SEO metadata | **Storefront** owns public cache lifetimes; **Catalog API** owns authoritative book data | Brief eventual staleness on public listings, traded for low latency and high throughput |
| **Transactional Flows (Commerce)** | Dynamic per-request SSR with zero shared caching and client hydration | **Commerce** enforces uncached dynamic rendering; **Basket API** and **Ordering API** own live state | Higher per-request compute cost, required for strict user data privacy |
| **Staff Operations (Backoffice)** | Dynamic SSR shell + live SSE dashboard updates + conditional `ETag` reads | **Backoffice** owns interactive admin views; backend APIs enforce preconditions | Conditional checks add header round-trips, preventing silent concurrent overwrites |
| **Streaming & Suspense** | Route-level loading skeletons and streaming server boundaries | Route entrypoints define suspense fallbacks; feature slices render streamed content | Requires carefully designed skeleton layouts to prevent cumulative layout shift |
- **Short Stale Windows:** The shared query cache uses a 60-second stale window on both server hydration and browser clients, balancing rapid navigation responsiveness with fresh catalog and order views.
- **Server Retry Suppression:** During SSR, failed queries do not retry automatically so slow upstream APIs fail fast into error boundaries rather than blocking server response times.
- **Conditional Revalidation:** **Backoffice** detail views send conditional `If-None-Match` headers and retain cached payloads on `304 Not Modified`, minimizing redundant payload transfers.
## Quality & Operational Impact
- **Fast Perceived Performance:** Server prefetching with streaming hydration eliminates client-side fetch waterfalls on initial page load.
- **Zero Cross-User Leakage:** Per-request server query clients and **Commerce**'s uncached rendering profile guarantee strict tenant and shopper data isolation.
- **SEO & Conversion:** Static optimization and component caching on **Storefront** deliver fast Time to First Byte (TTFB) for search crawlers and shoppers alike.
---
title: Authentication & Session Boundaries
summary: Identity provider handoff, origin-scoped session cookies, edge route protection, and role-based UI gating across customer and staff surfaces.
owners:
- catalog-experience-team
badges:
- content: Architecture
backgroundColor: purple
textColor: purple
- content: Reference
backgroundColor: blue
textColor: blue
---
## Purpose & Scope
This reference defines the authentication, session management, and authorization boundaries across **Storefront**, **Commerce**, and **Backoffice**. It governs how user identities are established with **Microsoft Entra ID**, how origin-scoped session cookies flow behind the **API Gateway**, and how frontend route protection pairs with backend API enforcement.
## Authentication and Session Boundary
The visual below traces how an unauthenticated user transitions through the **API Gateway**, completes OAuth2/OIDC handoff with **Microsoft Entra ID**, establishes an origin-scoped session cookie, and accesses protected APIs with a Bearer token.
## Architectural Principles & Rules
- **External identity delegation:** BookWorm does not store passwords or issue standalone user credentials; all customer and staff authentication delegates to **Microsoft Entra ID** via OAuth2/OIDC.
- **Two distinct session owners:** **Storefront** owns the customer authentication callback and session lifecycle (shared transparently with **Commerce** over the single gateway origin). **Backoffice** owns a separate staff session handler with administrative OAuth2 scopes.
- **Edge & layout route protection:** **Commerce** enforces session-cookie presence at the edge proxy before rendering protected basket, checkout, or account routes, redirecting unauthenticated users to **Storefront** sign-in with a preserved return URL. **Backoffice** enforces an administrative authentication guard at the layout boundary.
- **Defense-in-depth authorization:** UI gating and route guards improve user experience only; every backend capability API independently validates JWT Bearer tokens, audiences, and Entra ID roles/scopes on every request.
Hiding a button or protecting a frontend route is never a security boundary. Backend APIs must
enforce role and scope authorization on every operation regardless of frontend state.
## Patterns & Boundaries
| Concern / Surface | Architectural Approach | Responsibility Boundary | Key Trade-off |
| :------------------------------------------- | :------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------- |
| **Customer Session (Storefront + Commerce)** | Single origin-scoped session cookie owned by **Storefront** and read by **Commerce** | **Storefront** owns OAuth2 callback; **Commerce** validates session cookie on protected routes | **Commerce** depends on **Storefront** availability for initial login handoffs |
| **Staff Session (Backoffice)** | Dedicated staff session handler mounted under the **Backoffice** base path | **Backoffice** owns staff sign-in and requests elevated catalog/ordering/review scopes | Separate session lifecycle isolates staff credentials from customer browsing |
| **API Token Propagation** | Centralized token provider injects Bearer tokens into gateway-bound API requests | Auth layer supplies current access token; transport layer attaches authorization headers | Requires clean token refresh and immediate redirect on `401 Unauthorized` |
| **AI Assistant Identity** | Server-side assistant runtime forwards authenticated customer context to **Chat API** | **Storefront** server runtime bridges session to AG-UI; **Chat API** handles downstream OBO exchange | Keeps Entra Agent Identity OBO credentials strictly on the backend |
- **Customer Role:** Grants access to **Commerce** basket, checkout, and order history, plus authenticated **Storefront** reviews and AI assistant interactions.
- **Business User & Admin Roles:** Grant access to **Backoffice** catalog, customer, order, and review moderation capabilities, enforced by backend API scopes (`catalog_write`, `ordering_write`, `rating_write`).
- **Anonymous Visitors:** Can browse **Storefront** catalog, book details, and reviews; auth-gated client state suppresses basket queries until a valid session exists.
## Quality & Operational Impact
- **Seamless Customer Journey:** Origin-scoped session cookies allow shoppers to sign in on **Storefront** and immediately check out in **Commerce** without re-authenticating.
- **Reduced Attack Surface:** Keeping OAuth2 callbacks and token exchanges server-side behind the **API Gateway** prevents exposing client secrets or OBO credentials to browser code.
- **Zero Silent Auth Failures:** Failing `401` responses halt retries immediately and guide users cleanly through re-authentication.
---
title: Performance & Observability
summary: Core Web Vitals targets, bundle discipline, OpenTelemetry distributed tracing, and graceful degradation across all frontend surfaces.
owners:
- catalog-experience-team
badges:
- content: Architecture
backgroundColor: purple
textColor: purple
- content: Reference
backgroundColor: blue
textColor: blue
---
## Purpose & Scope
This reference defines performance budgets, bundle discipline, distributed telemetry, and graceful degradation standards across **Storefront**, **Commerce**, and **Backoffice**. It ensures customer discovery remains fast, checkout remains resilient under load, and frontend server operations participate in BookWorm's end-to-end observability pipeline.
## End-to-End Frontend Telemetry Flow
The visual below shows how frontend server runtimes export OpenTelemetry traces and metrics alongside **API Gateway** and backend service telemetry into BookWorm's centralized observability stack.
## Architectural Principles & Rules
- **Core Web Vitals discipline:** Public **Storefront** pages optimize for fast Largest Contentful Paint (LCP), minimal Cumulative Layout Shift (CLS) via explicit image dimensions and skeleton fallbacks, and low Interaction to Next Paint (INP) by keeping client hydration islands small.
- **Bundle & dependency isolation:** Heavy client dependencies—such as the conversational AI runtime—are scoped strictly to **Storefront** so **Commerce** checkout and **Backoffice** bundles remain lean.
- **OpenTelemetry instrumentation:** Every frontend server runtime initializes the shared OpenTelemetry Node SDK at startup, propagating W3C trace context through **API Gateway** calls to backend capability services and exporting telemetry via OTLP.
- **Graceful degradation:** Transient network errors, upstream timeouts, and rate limits surface non-blocking user feedback (offline/rate-limit banners and retry actions) rather than unhandled white-screen crashes.
Default to Server Components for data formatting, markdown/content rendering, and initial catalog
views. Only mark leaf interactive components as client-side to minimize JavaScript shipped to the
browser.
## Patterns & Boundaries
| Concern / Surface | Architectural Approach | Responsibility Boundary | Key Trade-off |
| :---------------------------- | :------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------ | :----------------------------------------------------------------------------------------------------- |
| **Bundle & Dependency Scope** | App-scoped heavy features (AI chat in **Storefront** only) + tree-shakeable shared packages | Application surfaces own feature dependencies; foundation/domain layers avoid heavy runtime bloat | Requires discipline when adding shared UI or utility dependencies |
| **Server Telemetry** | Shared OpenTelemetry startup instrumentation per Next.js server runtime | Foundation telemetry layer owns SDK setup; Aspire/Azure environment owns OTLP collector | Captures server-side SSR and proxy traces; browser RUM requires dedicated client-side beacons if added |
| **Correlation & Diagnostics** | Request correlation headers (`x-request-id`) and gateway zone headers (`X-Mfe-Zone`) | Transport layer stamps correlation IDs; **API Gateway** stamps zone routing headers | Simplifies cross-tier log correlation across browser, Next.js, gateway, and .NET APIs |
| **Resilient Degradation** | Route-level error boundaries, bounded transport retries, and SSE exponential backoff | Feature slices own fallback UI; transport layer owns bounded retry and backoff logic | Bounded retries slightly delay final error display in exchange for higher transient recovery |
- **LCP (Largest Contentful Paint):** Protected on **Storefront** by server-side rendering, component caching, and optimized responsive images.
- **CLS (Cumulative Layout Shift):** Prevented across all surfaces by reserving image aspect ratios and matching Suspense skeleton geometry to loaded content.
- **INP (Interaction to Next Paint):** Protected by keeping ephemeral client state minimal, avoiding unnecessary full-tree re-renders, and isolating streaming updates.
- **Observability Sink:** Local development streams traces and logs to the **Aspire Dashboard**; Azure deployments export to **Log Analytics Workspace**.
## Quality & Operational Impact
- **Conversion & Retention:** Fast **Storefront** paint times and responsive **Commerce** interactions directly support customer engagement and checkout completion.
- **End-to-End Traceability:** Propagating OpenTelemetry context from Next.js server runtimes through **API Gateway** to .NET services lets engineers diagnose slow page loads across the full stack.
- **Operational Resilience:** Bounded retries, SSE backoff, and isolated error boundaries keep partial backend degradation from cascading into full-page outages.
---
title: MS Decisions Model Use Case & Lessons Learned
summary: How BookWorm applies Microsoft-Decision-1 (System 1) for single-pass chat routing, safety gating, and dynamic tool selection, and the engineering lessons learned.
owners:
- architecture-enabling-team
badges:
- content: AI Architecture
backgroundColor: purple
textColor: purple
- content: Lessons Learned
backgroundColor: teal
textColor: teal
---
BookWorm's [[service|chat-api]] uses Microsoft Foundry's `Microsoft-Decision-1` ("System 1") model to evaluate safety, language, scope, specialist routing, and per-turn tool relevance in single-pass classification calls before invoking a generative chat model (`ModelRouter`). Replacing generative LLM router prompts with calibrated classification decisions cuts latency, lowers token spend, and enforces deterministic confidence thresholds (`0.5` for guardrails and tool selection; `0.6` for direct specialist routing before human-in-the-loop disambiguation).
## Context and motivation
Before a specialist AI agent answers a customer message on `/ag-ui`, Chat API must solve two high-frequency classification problems:
1. **Request screening and specialist routing:** Decide whether the message is safe, written in English, and relevant to BookWorm (books, orders, or store policies), then select the right specialist agent (**Book**, **QA**, or **Rating**).
2. **Per-turn tool filtering:** Choose which optional tools are relevant to the current conversation turn rather than sending every registered tool definition in every prompt.
Both problems are binary (`Yes`/`No`) or multiple-choice classification tasks rather than open-ended generation. Solving them with a full generative LLM adds round-trip latency, consumes prompt tokens on every turn, and risks malformed structured JSON outputs.
## How it works
BookWorm deploys `FoundryModel.Microsoft.MicrosoftDecision1` alongside `FoundryModel.Microsoft.ModelRouter` in `BookWorm.AppHost` and accesses it through a provider-agnostic `IDecisionClient` contract (`BookWorm.Chassis.AI.Decisions`), implemented by `FoundrySystemOneDecisionClient` (`/providers/microsoft/v1/systemone`).
### Use case 1: Single-pass screening and specialist routing
After deterministic rule-based validation (`InputValidationExecutor`), `DecisionRouterExecutor` evaluates four decision questions in a single `Microsoft-Decision-1` request:
| Question ID | Decision type | What it evaluates | Decision rule |
| :------------ | :------------------ | :------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------- |
| `is_safe` | Binary (`Yes`/`No`) | Detects prompt-injection, jailbreak, or instruction-override attempts | Confidence `< 0.5` stops the request (`UnsafeInput`) |
| `is_english` | Binary (`Yes`/`No`) | Verifies the message is written in English | Confidence `< 0.5` stops the request (`NonEnglish`) |
| `is_in_scope` | Binary (`Yes`/`No`) | Checks relevance to BookWorm books, orders, and store policies | Confidence `< 0.5` stops the request (`OutOfScope`) |
| `route` | Choice | Selects `book-agent`, `qa-agent`, or `rating-agent` (selected only when a specific book catalog ID is present) | Confidence `>= 0.6` routes directly; `< 0.6` triggers human-in-the-loop disambiguation via `RouteDisambiguationPort` |
End-to-end single-pass screening, partial-response fallback, and specialist routing flow in Chat API:
### Use case 2: Dynamic per-turn tool selection
`DecisionToolSelectionMiddleware` (`UseDecisionToolSelection`) filters optional tools before each specialist LLM invocation:
1. If `ChatOptions.Tools` is empty or `NoneChatToolMode` is active, it forwards the request unchanged.
2. Otherwise, it captures up to the last **6 messages** (`MaxContextMessages = 6`) as context and separates mandatory tools (`AlwaysIncludedToolNames` and `RequiredChatToolMode`) from optional candidate tools.
3. It sends one binary decision question per candidate tool to `IDecisionClient.GetDecisionAsync`.
4. Only candidate tools scoring `>= 0.5` (`ProbabilityThreshold = 0.5`) are merged with mandatory tools and passed to the inner `IChatClient`.
5. If the decision call fails, times out, or returns zero tools, the middleware **fails open**, logs the error, and retains all original tools so the customer still receives a response.
Per-turn tool filtering and fail-open recovery inside `DecisionToolSelectionMiddleware`:
### Key engineering lessons
- **Isolate vendor wire formats behind an internal contract:** Keeping `IDecisionClient` (`DecisionRequest`, `DecisionResponse`, `DecisionDefinition`) decoupled from `SystemOneProtocolMapper` lets Chat API workflows remain independent of Microsoft Foundry protocol changes.
- **Handle partial answers explicitly:** When `Microsoft-Decision-1` leaves `route` unanswered (`DecisionUnansweredException`), `HandlePartialResponse` still enforces any answered `is_safe`, `is_english`, or `is_in_scope` rejections and defaults the route to [[agent|book-agent]]—preventing both safety bypasses and avoidable chat crashes.
- **Protect mandatory tools before filtering:** Partitioning always-included and explicitly required tools before invoking the decision model ensures required workflow tools are never pruned.
- **Use AOT-safe source-generated JSON serialization:** `DecisionSerializationContext`, `ChatRoutingSerializationContext`, and `SystemOneSerializationContext` use compile-time `System.Text.Json` source generation (`UseStringEnumConverter = true`) to eliminate reflection overhead and preserve strict analyzer compliance.
- **Layer probabilistic screening with deterministic controls:** `Microsoft-Decision-1` complements—never replaces—`InputValidationExecutor`, Presidio `PIIMiddleware`, and Agent Governance `GuardrailMiddleware`.
- **Test cutoffs deterministically:** Unit tests (`DecisionRouterExecutorTests`, `WorkflowRegistrationTests`) inject simulated `IDecisionClient` stubs to verify boundary thresholds (`0.5` and `0.6`), partial responses, and fail-open paths offline without live Foundry calls.
`SystemOneProtocolMapper`, `ChatRoutingDecisionService`, `DecisionUnansweredException`, and `HandlePartialResponse` exist in the referenced source trees. No symbol named `DecisionSerializationContext` exists there.
## Design trade-offs
| Decision | Benefits | Costs and limits |
| :------------------------------------------------------------ | :--------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------- |
| **Single-pass System 1 classification** vs. generative router | Lower routing latency, lower token usage, and calibrated `0.0`-`1.0` scores | Requires maintaining explicit question definitions and tuning `0.5`/`0.6` thresholds as prompts evolve |
| **Fail-open tool filtering** | Preserves chat availability if the decision model times out or drops all optional tools | Temporarily increases prompt token size during fallback turns |
| **HITL disambiguation below `0.6` route confidence** | Avoids misrouting ambiguous customer questions to the wrong specialist agent | Adds an extra interactive user turn when intent is unclear |
| **Layered deterministic + AI safety checks** | Fast rejection of empty/malformed inputs plus PII redaction even if AI screening misses an edge case | Requires testing and maintaining three distinct middleware/executor layers |
## Alternatives considered
- **Full generative LLM router (`ModelRouter`):** Supports nuanced reasoning for ambiguous prompts, but adds multi-second latency and higher token cost on every turn and relies on brittle JSON prompt formatting.
- **Regex and keyword routing only:** Runs in microseconds with zero model cost, but fails on natural-language book queries, paraphrased intent, and subtle prompt injections.
- **Passing every tool unconditionally on every turn:** Eliminates tool-filtering middleware, but bloats prompt tokens and increases tool-selection errors as the tool catalog grows.
## Related documentation
- [[doc|development/001-developer-onboarding]] — How Chat API, MCP Tools, and Rating API fit into BookWorm's bounded contexts.
- [[doc|arc42/09-architecture-decisions]] — Formal decision records for Chat orchestration, System 1 routing, and per-agent tool governance.
- [[doc|platform/003-data-ai-and-messaging-resources]] — Microsoft Foundry deployments (`ModelRouter`, `MicrosoftDecision1`, `EmbedV40`) and Presidio configuration.
- [[doc|operational/003-incident-response-and-runbooks]] — Diagnosing AI chat throttling, Presidio sidecar errors, and Entra Agent Identity failures.
---
title: Operational Guides
summary: Operator-first runbooks, quick triage commands, deployment and rollback procedures, observability playbooks, disaster recovery, and SecOps rotation guides for BookWorm.
owners:
- platform-engineering-team
badges:
- content: Operations Hub
backgroundColor: red
textColor: red
---
Use this hub during live incidents, production deployments, disaster recovery drills, and security rotations. Every runbook leads with copy-pasteable CLI commands using consistent environment placeholders (``, ``, ``, ``).
## Quick Triage Cheat Sheet
Run these emergency commands first when responding to an alert or outage:
```bash
# 1. Verify Azure context and target subscription
az account show --query "{Subscription:name, Id:id, Tenant:tenantId}" -o table
az account set --subscription ""
# 2. Check health of all Container Apps
az containerapp list --resource-group "" \
--query "[].{Name:name, Status:properties.runningStatus, External:properties.configuration.ingress.external}" -o table
# 3. Tail live console logs for a failing service
az containerapp logs show --name "" --resource-group "" --type console --follow
# 4. List active and inactive revisions for a service
az containerapp revision list --name "" --resource-group "" \
--query "[].{Revision:name, Active:properties.active, Health:properties.healthState, Traffic:properties.trafficWeight}" -o table
# 5. Instant rollback to a known-good revision (multiple-revision mode)
az containerapp ingress traffic set --name "" --resource-group "" \
--revision-weight "=100"
# 6. Restart a stalled active revision
az containerapp revision restart --name "" --resource-group "" --revision ""
```
## Runbook Directory
### By Operational Domain
| Guide | Primary Role | When to Use |
| :---------------------------------------------------------------- | :------------- | :------------------------------------------------------------------------------------------------ |
| [[doc\|operational/003-incident-response-and-runbooks]] | SRE / Incident | During an active outage, `5xx` spike, stalled checkout, search lag, or AI/PII degradation |
| [[doc\|operational/002-observability-and-diagnostics]] | SRE / Incident | When investigating alerts, tracing requests, checking saturation, or querying KQL logs |
| [[doc\|operational/005-backup-restore-and-dr]] | SRE / Incident | During data corruption, accidental deletion, regional outage, or scheduled DR drills |
| [[doc\|operational/001-azure-deployment-guide]] | Cloud / DevOps | When deploying releases, promoting environments, shifting revision traffic, or rolling back |
| [[doc\|operational/007-scaling-and-cost-guardrails]] | Cloud / DevOps | During traffic spikes requiring manual scale overrides or when pausing non-prod spend |
| [[doc\|operational/004-security-hardening-checklist]] | SecOps | Before promoting an environment to Production or during periodic posture audits |
| [[doc\|operational/006-secrets-certificates-and-secops-rotation]] | SecOps | When rotating credentials, inspecting certificates, revoking compromised keys, or auditing access |
---
title: Deployment & Rollback Runbook
summary: Operator runbook for deploying BookWorm releases, shifting Container App revision traffic, and executing instant rollbacks.
owners:
- platform-engineering-team
badges:
- content: Cloud / DevOps
backgroundColor: green
textColor: green
---
## When to Use & Blast Radius
Use this runbook to deploy new infrastructure or application releases to `Development`, `Staging`, or `Production`, shift traffic between Container App revisions, or roll back a broken release. Provisioning and production rollouts modify live Container Apps, identity bindings, and ingress routing.
BookWorm deploys exclusively via `aspire deploy` or the CI/CD workflow (`apphost-cd.yml`). Do not
use `azd up` or manual template deployments. In single-active-revision mode, deploying a new
revision replaces live traffic immediately—verify candidate revisions or enable multiple-revision
mode before shifting production traffic.
### Release and Rollback Path
## Pre-Flight Check
Verify Azure authentication, target subscription, and current Container App health before deploying or shifting traffic:
```bash
az login
az account set --subscription ""
az containerapp list --resource-group "" \
--query "[].{Name:name, Status:properties.runningStatus, LatestRevision:properties.latestRevisionName}" -o table
```
## Procedure
Set the target Azure context and external partner connection strings before running `aspire deploy`:
```bash
export Azure__SubscriptionId=""
export Azure__TenantId=""
export Azure__Location=""
export Azure__ResourceGroup=""
export Azure__CredentialSource="AzureCli"
export ConnectionStrings__broker=""
export ConnectionStrings__vectordb=""
export Parameters__email_smtp_endpoint="smtp://smtp.sendgrid.net:587"
export Parameters__email_smtp_username="apikey"
export Parameters__email_smtp_password=""
export Parameters__email_sender_address=""
export Parameters__email_sender_name="BookWorm Support"
```
Run `aspire deploy` for direct operator releases, or dispatch the CI/CD workflow for audited environment promotion:
```bash
# Option A: Direct CLI deploy
aspire deploy --environment "" --pipeline-log-level information --include-exception-details
# Option B: Trigger CI/CD release promotion
gh workflow run apphost-cd.yml \
-f environment="" \
-f clear_cache=false \
-f pipeline_log_level=information
```
Watch the active workflow run until all build, push, and Container App rollout steps complete:
```bash
gh run list --workflow=apphost-cd.yml --limit 5
gh run watch ""
```
Switch a target Container App to multiple-revision mode to split traffic between the previous and candidate revisions:
```bash
az containerapp revision set-mode \
--name "" \
--resource-group "" \
--mode multiple
az containerapp ingress traffic set \
--name "" \
--resource-group "" \
--revision-weight "=90" "=10"
```
Once smoke checks and error rates remain clean, shift full traffic to the new revision:
```bash
az containerapp ingress traffic set \
--name "" \
--resource-group "" \
--revision-weight "=100"
```
## Verification
Confirm all 16 application Container Apps report `Running` and the **API Gateway** serves HTTP `200`:
```bash
GATEWAY_FQDN=$(az containerapp show --name gateway --resource-group "" --query "properties.configuration.ingress.fqdn" -o tsv)
az containerapp list --resource-group "" \
--query "[].{Name:name, Status:properties.runningStatus, External:properties.configuration.ingress.external}" -o table
curl -I "https://${GATEWAY_FQDN}/"
curl -I "https://${GATEWAY_FQDN}/backoffice"
```
Expected output:
```text
Name Status External
------------------- -------- ----------
gateway Running True
storefront Running False
commerce Running False
backoffice Running False
catalog Running False
...
HTTP/2 200
```
## Rollback / Escape Hatch
If a release causes `5xx` spikes, probe failures, or broken journeys, immediately shift 100% traffic back to the previous healthy revision or re-run the last known-good CI/CD commit:
```bash
# 1. List recent revisions to identify
az containerapp revision list --name "" --resource-group "" \
--query "[].{Revision:name, Active:properties.active, Health:properties.healthState, Created:properties.createdTime}" -o table
# 2. Ensure multiple-revision mode is enabled, activate previous revision, and shift 100% traffic
az containerapp revision set-mode --name "" --resource-group "" --mode multiple
az containerapp revision activate --name "" --resource-group "" --revision ""
az containerapp ingress traffic set --name "" --resource-group "" --revision-weight "=100"
# 3. Deactivate the faulty revision
az containerapp revision deactivate --name "" --resource-group "" --revision ""
```
To redeploy the previous release from GitHub Actions:
```bash
gh workflow run apphost-cd.yml --ref "" -f environment="" -f clear_cache=true
```
Deleting a resource group permanently destroys all Container Apps, databases, storage accounts,
and logs inside it. Never run this against Production.
```bash
az group delete --name "" --yes --no-wait
```
| Symptom | Cause | Fix |
| :-------------------------------------------------------------- | :---------------------------------------------------------------- | :------------------------------------------------------------------------ |
| Missing parameter error for `broker`, `vectordb`, or email | Required environment variable is unset | Export all variables in Step 1 and re-run `aspire deploy` |
| `AuthorizationFailed` during provisioning | Deploying identity lacks `User Access Administrator` or `Owner` | Assign `Contributor` + `User Access Administrator` on `` |
| `403` or PostgreSQL token login errors right after first deploy | Newly assigned Entra ID RBAC roles take 5–10 minutes to propagate | Wait 10 minutes and restart the failing revision |
| Unexpected resource drift | Cached Aspire deployment state is stale | Re-run `aspire deploy` with `--clear-cache` |
---
title: Observability & Alert Response
summary: Operator playbook for inspecting live Aspire Dashboard telemetry, running Log Analytics KQL queries, checking resource saturation, and responding to alerts.
owners:
- platform-engineering-team
badges:
- content: SRE / Incident
backgroundColor: teal
textColor: teal
---
## When to Use & Blast Radius
Use this guide when an Azure Monitor alert fires, latency degrades, or you need to correlate distributed traces and logs across **API Gateway**, backend services, **Message Broker** consumers, and AI pipelines. All commands in this runbook are read-only and safe to run against `Production`.
### Telemetry and Alerting Surface
## Pre-Flight Check
Verify your Azure CLI context and retrieve the Log Analytics workspace ID before running queries:
```bash
az account set --subscription ""
WORKSPACE_ID=$(az monitor log-analytics workspace list --resource-group "" --query "[0].customerId" -o tsv)
echo "Workspace ID: ${WORKSPACE_ID}"
```
## Procedure
Stream real-time stdout/stderr or platform lifecycle events without waiting for Log Analytics ingestion lag:
```bash
# Application stdout/stderr
az containerapp logs show --name "" --resource-group "" --type console --follow
# Platform events (image pulls, probe failures, scaling)
az containerapp logs show --name "" --resource-group "" --type system --tail 100
```
Run KQL queries across all Container Apps to surface recent exceptions or correlate a single request by ``:
```bash
# Recent application errors across all services
az monitor log-analytics query --workspace "${WORKSPACE_ID}" \
--analytics-query "ContainerAppConsoleLogs_CL | where TimeGenerated > ago(1h) | where Log_s has_any ('Error','Exception','Unhandled','Failed') | summarize ErrorCount=count() by ContainerAppName_s | order by ErrorCount desc" \
-o table
# Correlate a specific trace or request ID end-to-end
az monitor log-analytics query --workspace "${WORKSPACE_ID}" \
--analytics-query "ContainerAppConsoleLogs_CL | where TimeGenerated > ago(2h) | where Log_s contains '' | project TimeGenerated, ContainerAppName_s, Log_s | order by TimeGenerated asc" \
-o table
```
Check consumer failures and dead-letter routing across **Ordering Service**, **Finance Orchestrator**, **Basket Service**, **Notification Service**, **Catalog Service**, **Catalog Ingestion**, **Rating Service**, and **Scheduler Service**:
```bash
az monitor log-analytics query --workspace "${WORKSPACE_ID}" \
--analytics-query "ContainerAppConsoleLogs_CL | where TimeGenerated > ago(1h) | where ContainerAppName_s in ('ordering','finance','basket','notification','catalog','catalog-ingestion','rating','scheduler') | where Log_s has_any ('dead-letter','Wolverine','Kafka','ConsumeException') | project TimeGenerated, ContainerAppName_s, Log_s | order by TimeGenerated desc | take 50" \
-o table
```
Inspect Container App replica counts, PostgreSQL CPU/storage, and Redis memory pressure:
```bash
# Container App active replicas and provisioning state
az containerapp revision list --name "" --resource-group "" \
--query "[?properties.active==\`true\`].{Revision:name, Replicas:properties.replicas, Health:properties.healthState}" -o table
# PostgreSQL CPU and storage utilization (last 30 minutes)
PG_ID=$(az postgres flexible-server show --name "" --resource-group "" --query id -o tsv)
az monitor metrics list --resource "${PG_ID}" --metric cpu_percent storage_percent --interval PT5M --output table
# Azure Managed Redis memory usage
REDIS_ID=$(az redisenterprise show --name "" --resource-group "" --query id -o tsv)
az monitor metrics list --resource "${REDIS_ID}" --metric usedmemorypercentage --interval PT5M --output table
```
In the Azure Portal, open **Resource groups** → `` → **Container Apps Environment** → **Aspire Dashboard** to view end-to-end W3C traces, ASP.NET Core / HTTP metrics, and structured logs. For local troubleshooting, open `https://localhost:17290`.
## Common Alert Playbooks
1. Run the KQL error summary query in Step 2 to identify which `` is throwing exceptions.
2. Check `ContainerAppSystemLogs_CL` for `ContainerTerminated` or `UnhealthyProbe` events:
```bash
az monitor log-analytics query --workspace "${WORKSPACE_ID}" \
--analytics-query "ContainerAppSystemLogs_CL | where TimeGenerated > ago(1h) | where Reason_s in ('ContainerTerminated','ImagePullFailed','UnhealthyProbe') | project TimeGenerated, ContainerAppName_s, Reason_s, Log_s | order by TimeGenerated desc" -o table
```
3. If correlated with a recent deployment, follow [[doc|operational/001-azure-deployment-guide]] to roll back the revision immediately.
1. Open **Application Insights** linked to the AI project and filter **Failures** for HTTP `429`
on `chat`, `decision`, or `embedding` deployments. 2. Check **Privacy Analyzer** and **Privacy
Anonymizer** Container Apps (`presidio-analyzer`, `presidio-anonymizer`) for CPU/replica
saturation. 3. Increase model RPM/TPM capacity in Microsoft Foundry or scale up the privacy
sidecars using [[doc|operational/007-scaling-and-cost-guardrails]].
1. Verify `cpu_percent` and `storage_percent` on `` and `usedmemorypercentage` on `` using Step 4.
2. Check for runaway batch jobs in **Quartz Dashboard** (`https://quartz-dashboard./quartz`) or stuck sagas in **Finance Orchestrator**.
3. Scale compute/storage SKUs temporarily or pause non-critical batch ingestion until saturation subsides.
When an Azure Monitor alert triggers an **Azure SRE Agent** incident workflow, the agent automatically correlates Application Insights failures, Log Analytics exceptions, and recent deployment history.
1. Verify the `sre` Azure CLI extension is available (`az sre --help`) or query the agent's threads endpoint:
```bash
SRE_ENDPOINT=$(az rest -m GET \
--url "https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.App/agents/?api-version=2025-05-01-preview" \
--query properties.agentEndpoint -o tsv)
SRE_TOKEN=$(az account get-access-token --resource https://azuresre.dev --query accessToken -o tsv)
curl -s -H "Authorization: Bearer ${SRE_TOKEN}" "${SRE_ENDPOINT}/api/v1/threads"
```
2. Approve or reject proposed mitigations in the Azure Portal (**Review** mode) before any automated scaling or restart action runs against `Production`.
## Verification
Confirm log ingestion is active across all Container Apps within the last 15 minutes:
```bash
az monitor log-analytics query --workspace "${WORKSPACE_ID}" \
--analytics-query "ContainerAppConsoleLogs_CL | where TimeGenerated > ago(15m) | summarize Logs=count() by ContainerAppName_s | order by ContainerAppName_s asc" \
-o table
```
Expected output:
```text
ContainerAppName_s Logs
-------------------- ------
backoffice 14
basket 22
catalog 41
commerce 12
gateway 105
...
```
## Rollback / Escape Hatch
All diagnostic queries in this runbook are read-only. If you adjusted log sampling, diagnostic settings, or alert thresholds during an incident, revert them to baseline via `aspire deploy --environment ""`.
---
title: Incident Triage & Health Check Runbook
summary: First-5-minutes triage commands and symptom-first recovery playbooks for Container Apps, passwordless RBAC, order orchestration, vector ingestion, and AI pipelines.
owners:
- platform-engineering-team
badges:
- content: SRE / Incident
backgroundColor: red
textColor: red
---
## When to Use & Blast Radius
Use this runbook as your primary starting point during any live service degradation, failed checkout, search staleness, or authentication outage. Triage commands are read-only; mitigation commands (restarting revisions or modifying RBAC) affect live traffic for the targeted ``.
In `Staging` and `Production`, internal `/health` and `/alive` routes are not exposed externally.
Verify service health using Container App revision status, platform system logs, and **API
Gateway** HTTP responses.
### Incident Triage Flow
## Pre-Flight Check
Set the active Azure subscription and list all Container Apps in `` to identify unhealthy workloads:
```bash
az account set --subscription ""
az containerapp list --resource-group "" \
--query "[].{Name:name, Status:properties.runningStatus, LatestRevision:properties.latestRevisionName}" -o table
```
## Procedure (First 5 Minutes)
Check whether the active revision of `` is `Healthy` or stuck in `Activating` / `Failed`:
```bash
az containerapp revision list --name "" --resource-group "" \
--query "[].{Revision:name, Active:properties.active, Health:properties.healthState, Provisioning:properties.provisioningState, Replicas:properties.replicas}" \
-o table
```
Capture real-time application errors and Container App lifecycle events:
```bash
az containerapp logs show --name "" --resource-group "" --type console --tail 100
az containerapp logs show --name "" --resource-group "" --type system --tail 50
```
Check whether **Ordering Service**, **Basket Service**, **Notification Service**, or **Finance Orchestrator** are routing poison messages to native dead-letter queues (`bookworm...dead-letter-queue`):
```bash
WORKSPACE_ID=$(az monitor log-analytics workspace list --resource-group "" --query "[0].customerId" -o tsv)
az monitor log-analytics query --workspace "${WORKSPACE_ID}" \
--analytics-query "ContainerAppConsoleLogs_CL | where TimeGenerated > ago(1h) | where Log_s has_any ('dead-letter','ConsumeException','Failed') | project TimeGenerated, ContainerAppName_s, Log_s | order by TimeGenerated desc | take 30" \
-o table
```
Restart the active revision if the container is deadlocked or recovering from a transient dependency/RBAC propagation delay. If a recent release caused the regression, roll back immediately via [[doc|operational/001-azure-deployment-guide]].
```bash
az containerapp revision restart \
--name "" \
--resource-group "" \
--revision ""
```
If an **Azure SRE Agent** is attached to ``, inspect its active investigation threads to correlate Container Apps revision failures, Application Insights exceptions, and recent deployments before applying manual fixes:
```bash
# Retrieve the Azure SRE Agent endpoint and list recent investigation threads
SRE_ENDPOINT=$(az rest -m GET \
--url "https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.App/agents/?api-version=2025-05-01-preview" \
--query properties.agentEndpoint -o tsv)
SRE_TOKEN=$(az account get-access-token --resource https://azuresre.dev --query accessToken -o tsv)
curl -s -H "Authorization: Bearer ${SRE_TOKEN}" "${SRE_ENDPOINT}/api/v1/threads"
```
Review any proposed mitigation (such as scaling overrides or revision restarts) in the Azure Portal under your **SRE Agent** resource before approving execution in **Review** mode, or use the `az sre` CLI extension (`az sre --help`).
## Domain-Specific Recovery Playbooks
**Symptoms:** Revision stuck in `Activating`/`Failed`, `ImagePullFailed`, or crash loop.
1. Verify the Container Apps environment Managed Identity holds `AcrPull` on ``:
```bash
ACR_ID=$(az acr show --name "" --resource-group "" --query id -o tsv)
az role assignment list --scope "${ACR_ID}" \
--query "[?roleDefinitionName=='AcrPull'].{Principal:principalId, Role:roleDefinitionName}" -o table
```
2. Confirm the target image tag exists in ``:
```bash
az acr repository show-tags --name "" --repository "" --orderby time_desc -o table
```
3. Check console logs for missing external parameters (Message Broker, Vector Database, or SMTP relay), then redeploy via `aspire deploy --environment ""`.
**Symptoms:** PostgreSQL token login failure, Redis `NOAUTH`/`NOPERM`, or `403 Forbidden` on Cosmos DB, Blob Storage, or Microsoft Foundry. Never re-enable static passwords or shared keys as a workaround.
1. Confirm PostgreSQL Entra ID admin registration (**Catalog Service**, **Catalog Ingestion**, **Ordering Service**, **Scheduler Service** only):
```bash
az postgres flexible-server ad-admin list --resource-group "" --server-name "" -o table
```
2. Inspect Managed Identity role assignments for ``:
```bash
az role assignment list --resource-group "" --assignee "" \
--query "[].{Role:roleDefinitionName, Scope:scope}" -o table
```
Expected datastore bindings:
- **Azure Storage:** `Storage Blob Data Contributor` for **Catalog Service** and **Chat Service**; `Storage Blob Data Owner` for **Catalog Ingestion** and **Finance Orchestrator**.
- **Microsoft Foundry:** `Cognitive Services User` for **Catalog Service**, **Catalog Ingestion**, **Chat Service**, and **Rating Service**.
3. Wait 5–10 minutes for Entra ID RBAC propagation, then restart the failing revision.
**Symptoms:** Orders stay in `New` status, customer baskets do not clear, or checkout emails never send.
1. Verify **Finance Orchestrator** (`finance`) has **Durable Task Scheduler** and broker settings populated:
```bash
az containerapp show --name finance --resource-group "" \
--query "properties.template.containers[0].env[?name=='DTS_CONNECTION_STRING' || name=='TASKHUB_NAME' || name=='BrokerList']" -o table
```
2. Confirm **Finance Orchestrator** holds `Storage Blob Data Owner` on `` and that the Container Apps outbound static IP is in the Durable Task Scheduler allowlist.
3. Inspect logs and dead-letter queues for **Ordering Service**, **Finance Orchestrator**, **Basket Service**, and **Notification Service**. For missing checkout emails, verify **Notification Service** connectivity to the Message Broker, Redis, and SMTP relay.
**Symptoms:** Newly created or updated books do not appear in semantic search.
1. Sign in to **Quartz Dashboard** (`https://quartz-dashboard./quartz`) and verify the 5-minute vector batch job is executing without misfires.
2. Tail **Catalog Ingestion** logs:
```bash
az containerapp logs show --name catalog-ingestion --resource-group "" --type console --tail 100
```
3. If Microsoft Foundry returns HTTP `429` on `embedding`, increase model capacity. If **Qdrant Cloud** fails, verify the vector database connection secret.
**Symptoms:** **Chat Service** (`chatting`) or **Rating Service** (`rating`) returns HTTP `502`/`503`, `429`, or high latency.
1. Check **Privacy Analyzer** and **Privacy Anonymizer** status:
```bash
az containerapp list --resource-group "" \
--query "[?name=='presidio-analyzer' || name=='presidio-anonymizer'].{Name:name, Status:properties.runningStatus}" -o table
```
2. Inspect Application Insights **Failures** for HTTP `429` throttling on `chat`, `decision`, or `embedding` deployments.
3. If Agent-to-Agent calls return `401`/`403`, verify Entra Agent Identity Federated Identity Credentials using [[doc|operational/006-secrets-certificates-and-secops-rotation]].
## Verification
Confirm the affected Container App revision is `Healthy` with active replicas and zero new errors in Log Analytics:
```bash
az containerapp revision list --name "" --resource-group "" \
--query "[?properties.active==\`true\`].{Revision:name, Health:properties.healthState, Replicas:properties.replicas}" -o table
```
Expected output:
```text
Revision Health Replicas
-------------------------- -------- ----------
-- Healthy 1
```
## Rollback / Escape Hatch
If a revision restart or RBAC adjustment does not restore service within 10 minutes, roll back to the previous known-good revision using [[doc|operational/001-azure-deployment-guide]].
---
title: Production Hardening & Compliance Checklist
summary: Pre-production SecOps and reliability checklist for locking down network perimeters, scaling limits, backup drills, and alerting before serving live traffic.
owners:
- platform-engineering-team
badges:
- content: SecOps
backgroundColor: amber
textColor: amber
---
## When to Use & Blast Radius
Complete this checklist before promoting a BookWorm environment to `Production` or during periodic security posture audits. Network perimeter changes (disabling public access or restricting ingress allowlists) can sever CI/CD runners or **Finance Orchestrator** connectivity if Private Endpoints and outbound static IPs are not configured first.
Configure Virtual Network integration, Private Endpoints, and self-hosted CI/CD runners before disabling public network access on Azure data and AI services.
## Pre-Flight Check
Authenticate to Azure and inspect current public ingress exposure across all Container Apps:
```bash
az account set --subscription ""
az containerapp list --resource-group "" \
--query "[?properties.configuration.ingress.external==\`true\`].{Name:name, Fqdn:properties.configuration.ingress.fqdn}" -o table
```
## Procedure
Attach the Container Apps environment to a dedicated Virtual Network, enable Private Endpoints on all Azure data and AI services, restrict **Durable Task Scheduler** and **Quartz Dashboard** access, tighten Blob Storage CORS to the **API Gateway** domain, and bind a WAF + Key Vault TLS certificate.
Configure `maxReplicas` and scaling rules across all 16 application Container Apps, verify production liveness/readiness probes, set Production Cosmos DB autoscale RU/s, and raise Microsoft Foundry RPM/TPM quotas above starter baselines.
Execute a PostgreSQL point-in-time restore drill, confirm Cosmos DB continuous backup and multi-region failover, test a full **Qdrant Cloud** vector re-index through **Catalog Ingestion**, and verify **Message Broker** retention and Blob Storage soft-delete.
Store external partner credentials and signing/session secrets in Azure Key Vault with rotation schedules, configure Azure Monitor alert rules for `5xx`, saturation, throttling, and dead-letter queues, and publish service-level objectives.
## Detailed Hardening Checklists
- [ ] Attach the Container Apps environment to a dedicated Virtual Network subnet with deterministic outbound static IPs.
- [ ] Enable Private Endpoints and disable public network access on PostgreSQL, Azure Managed Redis, Azure Cosmos DB, Azure Storage, and Microsoft Foundry.
- [ ] Restrict **Durable Task Scheduler** IP allowlist to the Container Apps environment outbound static IPs.
- [ ] Restrict Blob Storage CORS allowed origins to your production **API Gateway** custom domain.
- [ ] Restrict **Quartz Dashboard** external ingress to an internal VNet, VPN, or operator IP allowlist.
- [ ] Bind a custom domain, Key Vault-managed TLS certificate, and Web Application Firewall (WAF) in front of **API Gateway**.
- [ ] Define upper autoscaling limits (`maxReplicas`) alongside HTTP concurrency and KEDA message-lag rules across all 16 application Container Apps.
- [ ] Verify Container Apps liveness/readiness probes target valid production endpoints.
- [ ] Benchmark **Privacy Analyzer**, **Privacy Anonymizer**, **Catalog Ingestion**, and **Finance Orchestrator** under peak load.
- [ ] Configure Production Cosmos DB autoscale Request Units (RU/s) on the Rating database.
- [ ] Raise Microsoft Foundry RPM and TPM quotas for `chat`, `decision`, and `embedding` deployments above starter baselines.
- [ ] Execute and time a PostgreSQL point-in-time restore drill covering Catalog, Ordering, and Scheduler databases.
- [ ] Confirm Cosmos DB continuous backup mode and multi-region failover policy.
- [ ] Execute a full **Qdrant Cloud** vector re-index drill from PostgreSQL through **Catalog Ingestion**.
- [ ] Verify external **Message Broker** topic retention, replication factor, and dead-letter replay procedures.
- [ ] Confirm soft-delete and versioning settings on Azure Blob Storage.
- [ ] Store external partner credentials (Message Broker, Vector Database, SMTP Relay) and application signing/session secrets in Azure Key Vault with scheduled rotation.
- [ ] Configure Azure Monitor alert rules for `5xx` spikes, container terminations, probe failures, database/cache saturation, AI HTTP `429` throttling, and non-empty dead-letter queues.
- [ ] Publish availability, p95 latency, RTO, and RPO targets per service boundary.
## Verification
Audit Storage, Cosmos DB, and Container App ingress posture with Azure CLI before Production sign-off:
```bash
# 1. Confirm Storage disables public blob access and shared-key access
az storage account show --name "" --resource-group "" \
--query "{PublicBlobAccess:allowBlobPublicAccess, SharedKeyAccess:allowSharedKeyAccess, MinTls:minimumTlsVersion, PublicNetwork:publicNetworkAccess}" \
-o table
# 2. Confirm Cosmos DB disables local auth and public access
az cosmosdb show --name "" --resource-group "" \
--query "{DisableLocalAuth:disableLocalAuth, PublicNetwork:publicNetworkAccess}" -o table
# 3. Confirm only API Gateway exposes external ingress
az containerapp list --resource-group "" \
--query "[?properties.configuration.ingress.external==\`true\`].{Name:name, Fqdn:properties.configuration.ingress.fqdn, MaxReplicas:properties.template.scale.maxReplicas}" \
-o table
```
Expected output:
```text
PublicBlobAccess SharedKeyAccess MinTls PublicNetwork
------------------ ----------------- -------- ---------------
False False TLS1_2 Disabled
DisableLocalAuth PublicNetwork
------------------ ---------------
True Disabled
Name Fqdn MaxReplicas
------- -------------------- -------------
gateway 10
```
## Rollback / Escape Hatch
If tightening a network perimeter or IP allowlist blocks **Finance Orchestrator** or CI/CD runners, temporarily add the Container Apps outbound static IP (`az containerapp env show --name "" --resource-group "" --query properties.staticIp -o tsv`) to the blocked resource's allowlist while Private Endpoint DNS is verified.
---
title: Backup, Restore & Disaster Recovery (DR)
summary: Operator runbook for PostgreSQL point-in-time restore, Cosmos DB failover verification, Blob Storage recovery, and Qdrant vector index rebuilds.
owners:
- platform-engineering-team
badges:
- content: SRE / Incident
backgroundColor: red
textColor: red
---
## When to Use & Blast Radius
Use this runbook during data corruption, accidental deletion, regional Azure outages, or scheduled disaster recovery drills. Restores provision new database instances or overwrite derived indexes and can incur temporary service downtime until connection bindings are updated.
Never restore directly over a live `Production` database. Always restore PostgreSQL or Cosmos DB
into a new target resource, validate data integrity first, and then cut over service bindings.
### Backup and Recovery Topology
## Pre-Flight Check
Verify Azure CLI context and inspect current backup and replication status for authoritative stores:
```bash
az account set --subscription ""
az postgres flexible-server show --name "" --resource-group "" \
--query "{State:state, BackupRetentionDays:backup.backupRetentionDays, GeoRedundant:backup.geoRedundantBackup, HaState:highAvailability.state}" -o table
az cosmosdb show --name "" --resource-group "" \
--query "{BackupPolicy:backupPolicy.type, Locations:locations[].{Region:locationName, Priority:failoverPriority}}" -o table
```
## Procedure
Restore the PostgreSQL Flexible Server to a known-good UTC timestamp (``, e.g., `2026-11-27T12:00:00Z`) into a new server instance:
```bash
az postgres flexible-server restore \
--resource-group "" \
--name "-restored" \
--source-server "" \
--restore-time ""
```
Ensure passwordless Entra ID authentication is enabled for **Catalog Service**, **Catalog Ingestion**, **Ordering Service**, and **Scheduler Service**:
```bash
az postgres flexible-server ad-admin create \
--resource-group "" \
--server-name "-restored" \
--display-name "" \
--object-id "" \
--type Group
```
Inspect failover priorities and trigger a manual failover only if the primary write region is unavailable:
```bash
az cosmosdb failover-priority-change \
--name "" \
--resource-group "" \
--failover-policies "=0" "=1"
```
Verify soft-delete retention and restore soft-deleted blobs in ``:
```bash
az storage blob undelete \
--account-name "" \
--container-name "" \
--name "" \
--auth-mode login
```
Because the vector index is derived from the Catalog database, trigger a batch re-index through **Quartz Dashboard** (`https://quartz-dashboard./quartz`) and monitor **Catalog Ingestion** logs until all catalog records are re-embedded:
```bash
az containerapp logs show --name catalog-ingestion --resource-group "" --type console --follow
```
## Verification
Confirm the restored PostgreSQL server is `Ready`, Cosmos DB write region is active, and **Catalog Ingestion** reports zero errors:
```bash
az postgres flexible-server show --name "-restored" --resource-group "" \
--query "{Name:name, State:state, Fqdn:fullyQualifiedDomainName}" -o table
az cosmosdb show --name "" --resource-group "" \
--query "writeLocations[].{Region:locationName, Status:provisioningState}" -o table
```
Expected output:
```text
Name State Fqdn
------------------------- ------- -------------------------------------------
-restored Ready -restored.postgres.database.azure.com
Region Status
---------------- ---------
Succeeded
```
## Rollback / Escape Hatch
If a restored PostgreSQL server fails data validation, keep the original `` untouched and delete the scratch restore instance:
```bash
az postgres flexible-server delete --name "-restored" --resource-group "" --yes
```
If the primary Azure region is unreachable, use geo-restore to recover the PostgreSQL server into `` from geo-redundant backups:
```bash
az postgres flexible-server geo-restore \
--resource-group "" \
--name "-dr" \
--source-server "" \
--location ""
```
---
title: Secrets, Certificates & SecOps Rotation
summary: SecOps runbook for verifying Managed Identities, inspecting TLS certificates, revoking compromised credentials, rotating secrets, and querying audit logs.
owners:
- platform-engineering-team
badges:
- content: SecOps
backgroundColor: amber
textColor: amber
---
## When to Use & Blast Radius
Use this runbook during scheduled credential rotations, TLS certificate renewals, suspected secret compromise, or security incident investigations. Rotating session secrets or revoking partner keys invalidates active sessions or interrupts downstream calls until affected Container App revisions restart.
Rotating frontend authentication secrets logs out active users across **Storefront** and
**Commerce** simultaneously. Revoking **Message Broker**, **Vector Database**, or **SMTP Relay**
credentials requires updating CI/CD environment secrets and restarting dependent Container Apps.
### Credential Rotation and Revocation Flow
## Pre-Flight Check
Verify Azure CLI context, inspect Key Vault certificates, and confirm Managed Identity assignments:
```bash
az account set --subscription ""
az keyvault certificate list --vault-name "" \
--query "[].{Name:name, Enabled:attributes.enabled, Expires:attributes.expires}" -o table
az identity list --resource-group "" \
--query "[].{Name:name, PrincipalId:principalId, ClientId:clientId}" -o table
```
## Procedure
Confirm **API Gateway**, backend services, and AI agent identities have valid Federated Identity Credentials and no unauthorized role assignments:
```bash
az ad app federated-credential list --id "" \
--query "[].{Name:name, Subject:subject, Audiences:audiences}" -o table
az role assignment list --resource-group "" --assignee "" \
--query "[].{Role:roleDefinitionName, Scope:scope}" -o table
```
Check expiration dates on custom domain certificates bound to the Container Apps environment and import renewed certificates from Key Vault:
```bash
az containerapp env certificate list --name "" --resource-group "" \
--query "[].{Name:name, Subject:properties.subjectName, Expiration:properties.expirationDate}" -o table
```
Generate a new API key or connection string in the external provider (**Message Broker**, **Qdrant Cloud**, or **SMTP Relay**), update the GitHub Environment secret, and roll out updated Container Apps:
```bash
gh secret set "" --env "" --body ""
gh workflow run apphost-cd.yml -f environment="" -f clear_cache=false
```
When immediate rotation cannot wait for a full CI/CD run, update the Container App secret and restart the active revision:
```bash
az containerapp secret set --name "" --resource-group "" \
--secrets "="
az containerapp revision restart --name "" --resource-group "" --revision ""
```
Inspect recent control-plane mutations, role assignment changes, and Key Vault secret access:
```bash
az monitor activity-log list --resource-group "" --offset 24h \
--query "[?level=='Warning' || level=='Error' || contains(operationName.value,'roleAssignments')].{Time:eventTimestamp, Caller:caller, Operation:operationName.localizedValue, Status:status.value}" \
-o table
```
## Verification
Confirm all rotated Container Apps are `Running` with healthy revisions and zero `401`/`403` authentication errors in Log Analytics:
```bash
WORKSPACE_ID=$(az monitor log-analytics workspace list --resource-group "" --query "[0].customerId" -o tsv)
az monitor log-analytics query --workspace "${WORKSPACE_ID}" \
--analytics-query "ContainerAppConsoleLogs_CL | where TimeGenerated > ago(15m) | where Log_s has_any ('401','403','Unauthorized','NOAUTH') | summarize AuthErrors=count() by ContainerAppName_s" \
-o table
```
Expected output:
```text
(0 rows returned)
```
## Rollback / Escape Hatch
If a rotated partner credential breaks connectivity, re-apply the previous active credential (if not yet revoked) via `az containerapp secret set` and restart the affected revision, or re-run the last known-good CI/CD deployment.
- **Compromised external API key (Message Broker, Qdrant Cloud, SMTP):** Issue a replacement key in the provider portal first, roll out via Step 3 or Step 4, verify zero auth errors, and **then** revoke the compromised key in the provider portal.
- **Compromised Entra ID application secret or Federated Credential:** Delete the compromised credential via `az ad app federated-credential delete --id "" --federated-credential-id ""`, recreate it via `aspire deploy --environment ""`, and restart affected revisions.
- **Unauthorized RBAC assignment detected in Activity Log:** Remove the assignment immediately with `az role assignment delete --assignee "" --role "" --scope ""`.
---
title: Scaling & Cost Guardrails
summary: Cloud/DevOps runbook for manual Container App replica overrides, concurrency and KEDA scaling limits, and pausing non-production environments to control spend.
owners:
- platform-engineering-team
badges:
- content: Cloud / DevOps
backgroundColor: green
textColor: green
---
## When to Use & Blast Radius
Use this runbook during planned traffic events, saturation incidents requiring immediate manual scale-out, or off-hours cost optimization in `Development` and `Staging`. Lowering `minReplicas` to `0` introduces cold-start latency; stopping non-production databases makes those environments unavailable until resumed.
Never set `minReplicas` to `0` or stop PostgreSQL Flexible Server in `Production`. Keep
`minReplicas >= 1` for all production services and enforce `maxReplicas` caps to prevent runaway
autoscaling spend.
## Pre-Flight Check
Inspect current replica counts and scaling bounds across all Container Apps in ``:
```bash
az account set --subscription ""
az containerapp list --resource-group "" \
--query "[].{Name:name, MinReplicas:properties.template.scale.minReplicas, MaxReplicas:properties.template.scale.maxReplicas, Status:properties.runningStatus}" \
-o table
```
## Procedure
Temporarily raise `min-replicas` and cap `max-replicas` on a saturated Container App (for example, `gateway`, `ordering`, `catalog`, or `presidio-analyzer`):
```bash
az containerapp update \
--name "" \
--resource-group "" \
--min-replicas 3 \
--max-replicas 10
```
Attach an HTTP scaling rule so replicas scale predictably under concurrent request load without exceeding ``:
```bash
az containerapp update \
--name "" \
--resource-group "" \
--min-replicas 1 \
--max-replicas 10 \
--scale-rule-name http-concurrency \
--scale-rule-type http \
--scale-rule-http-concurrency 50
```
Stop non-production Container Apps and pause the PostgreSQL Flexible Server outside working hours:
```bash
# Stop all Container Apps in a non-prod resource group
for app in $(az containerapp list --resource-group "" --query "[].name" -o tsv); do
az containerapp stop --name "${app}" --resource-group "" --no-wait
done
# Stop non-prod PostgreSQL Flexible Server (auto-restarts after 7 days per Azure policy)
az postgres flexible-server stop --name "" --resource-group ""
```
Start the PostgreSQL Flexible Server first, then start all Container Apps:
```bash
az postgres flexible-server start --name "" --resource-group ""
for app in $(az containerapp list --resource-group "" --query "[].name" -o tsv); do
az containerapp start --name "${app}" --resource-group "" --no-wait
done
```
## Verification
Confirm updated replica limits and running state across ``:
```bash
az containerapp list --resource-group "" \
--query "[].{Name:name, MinReplicas:properties.template.scale.minReplicas, MaxReplicas:properties.template.scale.maxReplicas, Status:properties.runningStatus}" \
-o table
```
Expected output (active environment):
```text
Name MinReplicas MaxReplicas Status
--------- ------------- ------------- --------
gateway 1 10 Running
ordering 1 10 Running
catalog 1 10 Running
...
```
## Rollback / Escape Hatch
If a manual scale override or concurrency rule causes instability or unexpected cost, revert to baseline scaling bounds immediately:
```bash
az containerapp update \
--name "" \
--resource-group "" \
--min-replicas 1 \
--max-replicas 5
```
---
title: Platform Reference
summary: Technical reference for BookWorm's Azure hosting topology, compute inventory, stateful data and AI infrastructure, identity and RBAC matrix, scheduler schema, and service contracts.
owners:
- platform-engineering-team
badges:
- content: Platform Reference
backgroundColor: blue
textColor: blue
---
The Platform Reference documents BookWorm's shared infrastructure, runtime hosting model, stateful backing stores, identity and access boundaries, job persistence schema, and cross-service contract surface. It is designed as a fast-lookup reference for application engineers integrating with platform capabilities, platform engineers managing infrastructure, and operators diagnosing production workloads.
## Platform Topology Overview
## Quick Navigation
## Capability Index
| Platform Capability | Responsibility | Primary Components | Key Consumers |
| :---------------------------------------------------- | :----------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------- |
| [[doc\|platform/001-platform-overview]] | Environment isolation, public ingress routing, and shared observability/registry backbone | API Gateway, Container Apps Environment, Container Registry, Log Analytics, Aspire Dashboard | Customers, staff, all workloads |
| [[doc\|platform/002-compute-and-container-apps]] | Managed container hosting, ingress tiers, revision lifecycle, and runtime identity binding | Frontends, [[service\|catalog-api]], [[service\|basket-api]], [[service\|order-api]], [[service\|order-orchestration]], [[service\|rating-api]], [[service\|chat-api]], [[service\|mcp-server]], [[service\|notification-api]], [[service\|scheduler-service]], [[service\|presidio-api]] | Application and platform engineers |
| [[doc\|platform/003-data-ai-and-messaging-resources]] | Authoritative service persistence, distributed caching, AI inference, and event transport | [[container\|catalog-database]], [[container\|order-database]], [[container\|scheduler-database]], [[container\|rating-database]], [[container\|basket-database]], [[container\|catalog-vector]], [[container\|catalog-blob]], [[container\|chat-session-blob]], Kafka, [[service\|sendgrid-api]] | Capability APIs and background workers |
| [[doc\|platform/004-identity-and-rbac-matrix]] | User/agent authentication, OBO token delegation, and passwordless Azure RBAC | [[service\|oauth-api]], Entra Agent Identities, user-assigned Managed Identities | Frontends, APIs, AI agents, operators |
| [[doc\|platform/005-quartz-schema]] | Durable cron job definitions, cluster locking, and execution/misfire history | [[service\|scheduler-service]], Quartz Dashboard, [[container\|scheduler-database]] | Platform operators, [[service\|catalog-ingestion]] |
| [[doc\|platform/006-api-and-contracts]] | Versioned synchronous APIs, error semantics, and asynchronous CloudEvents contracts | HTTP v1, gRPC, AG-UI, MCP, A2A, Wolverine/Kafka topics and DLQs | Frontends, backend services, AI agents |
---
title: Azure Platform & Topology Overview
summary: Reference architecture for BookWorm's subscription-scoped Azure deployment, shared platform services, and network ingress boundaries.
owners:
- platform-engineering-team
badges:
- content: Platform Reference
backgroundColor: blue
textColor: blue
---
BookWorm runs on an Azure Container Apps environment provisioned per resource group across `Development`, `Staging`, and `Production` environments. The platform boundary encompasses public ingress routing via a YARP API Gateway, shared container registry and telemetry infrastructure, and identity-based integration with managed data, AI, and external messaging services.
## Platform Topology and Ingress Boundaries
## Component & Responsibility
| Component | Role | Protocol / Interface | Persistence / State | Notes |
| :------------------------------- | :----------------------------------------------------------------------------------------- | :------------------------------- | :------------------------------------------------------------------------- | :------------------------------------------------------------ |
| **Container Apps Environment** | Managed `Consumption` runtime hosting all 16 application workloads and operational tooling | Internal & external HTTP/gRPC | Stateless orchestration | Resource group-isolated |
| **API Gateway** | Sole public entry point for customer/staff frontends and capability APIs | External HTTPS (port `5000`) | Stateless | YARP reverse proxy; proxies identity routes and enforces CORS |
| **Quartz Dashboard** | Administrative UI for scheduled job inspection and manual triggering | External HTTPS (port `8080`) | Reads [[container\|scheduler-database]] via [[service\|scheduler-service]] | Protected by [[service\|oauth-api]] OIDC (`admin` role) |
| **Azure Container Registry** | Stores .NET and Next.js container images | HTTPS (registry pull) | Container image artifacts | `Basic` SKU; pulled via shared environment identity |
| **Environment Managed Identity** | Shared user-assigned identity for registry image pulls | Azure RBAC (`AcrPull`) | Stateless identity | Bound to Container Apps Environment |
| **Log Analytics Workspace** | Centralized platform and application telemetry sink | OTLP / Azure Monitor | 30 days (Dev/Staging); 90 days (Prod) | Shared across all hosted workloads |
| **Aspire Dashboard** | Live OpenTelemetry logs, distributed traces, and metrics console | Managed Container Apps component | Ephemeral live stream | Provisioned per environment |
## Configuration & Operational Defaults
### Network & Ingress Boundary
- **Public gateway entry:** External HTTPS traffic enters through the API Gateway.
- **Internal service addressing:** All internal apps communicate over environment-internal HTTPS without public exposure.
- **CORS policy:** Every routed backend API permits `GET`, `POST`, `PUT`, `PATCH`, and `DELETE` with credentials from the gateway browser origin.
- **Internal-only workloads:** Frontends (Storefront, Commerce, Backoffice), capability APIs (Catalog, Basket, Ordering, Rating, Chat), MCP Tools (accepts gateway origin CORS), background workers (Catalog Ingestion, Finance, Notification, Scheduler), and privacy sidecars (Presidio Analyzer and Anonymizer on HTTP port `3000`) have no public ingress.
### API Gateway Route Map
Backend routes match in registration order; the Storefront catch-all route carries the lowest routing priority.
| Route pattern | Destination | Routing behavior |
| :----------------------------------------------------------- | :----------------------- | :-------------------------------------------------------------- |
| `/chatting/{**remainder}` | [[service\|chat-api]] | Strips `/chatting` prefix; preserves host and forwarded headers |
| `/rating/{**remainder}` | [[service\|rating-api]] | Strips `/rating` prefix; preserves host and forwarded headers |
| `/ordering/{**remainder}` | [[service\|order-api]] | Strips `/ordering` prefix; preserves host and forwarded headers |
| `/basket/{**remainder}` | [[service\|basket-api]] | Strips `/basket` prefix; preserves host and forwarded headers |
| `/catalog/{**remainder}` | [[service\|catalog-api]] | Strips `/catalog` prefix; preserves host and forwarded headers |
| `/entra/{**remainder}` | [[service\|oauth-api]] | Strips `/entra` prefix; forwards to external identity provider |
| `/backoffice/{**remainder}` | Backoffice | Routes staff administration microfrontend |
| `/basket`, `/checkout/*`, `/account/*`, `/commerce-assets/*` | Commerce | Routes customer checkout and account microfrontend |
| `/{**remainder}` | Storefront | Catch-all storefront microfrontend (lowest priority) |
Resource names use deterministic per-resource-group tokens. Deploy each environment (`Development`, `Staging`, `Production`) to a dedicated resource group to keep resource names isolated.
| Parameter | Purpose | Default / notes |
| :-------- | :------ | :-------------- |
| **Subscription & Tenant** | Target Azure subscription and Microsoft Entra ID tenant | Required |
| **Region & Resource Group** | Target Azure region and environment resource group | Defaults to `southeastasia` in CI/CD |
| **Kafka Broker Connection** | External Kafka cluster connection | Required in Azure deployments |
| **Vector Database Connection** | External Qdrant Cloud connection | Required in Azure deployments |
| **SMTP Endpoint & Port** | External email relay endpoint | Defaults to SendGrid on port `587` |
| **SMTP Credentials & Sender** | Relay username, password, sender address, and display name | Password and sender address required |
| Concern | Local Run Mode | Azure Publish Mode |
| :------ | :------------- | :----------------- |
| **Data stores** | Local containers and emulators (PostgreSQL, Redis, Cosmos DB, Azurite, Durable Task Scheduler) | Azure-managed services |
| **Kafka and Qdrant** | Local containers with Kafka UI | External managed providers |
| **Email** | Mailpit container (SMTP port `587`) | SendGrid SMTP relay |
| **Developer tooling** | Scalar API explorer and MCP inspector | Not provisioned |
| **Entra Agent Identities** | Not provisioned | Provisioned via Microsoft Graph |
## Guardrails & Constraints
Quartz Dashboard is the second externally reachable workload alongside the API Gateway. Restrict
its public network ingress before serving Production traffic; see
[[doc|operational/004-security-hardening-checklist]].
The exact Commerce path `/basket` overlaps with the backend `/basket/{**remainder}` API prefix. Exact microfrontend routes take precedence so the Commerce page serves bare `/basket` requests while `/basket/...` API calls still route to [[service|basket-api]].
## Related Documentation
- [[doc|platform/002-compute-and-container-apps]] — Inventory of all 16 application Container Apps and Quartz Dashboard.
- [[doc|platform/003-data-ai-and-messaging-resources]] — Environment-tier SKUs and datastore ownership.
- [[doc|platform/004-identity-and-rbac-matrix]] — Entra ID applications, scopes, Agent Identities, and Managed Identity roles.
- [[doc|operational/001-azure-deployment-guide]] — Provisioning procedure.
---
title: Container Apps & Compute Inventory
summary: Reference inventory of all 16 Azure Container Apps, ingress ports, revision modes, and platform-owned runtime services.
owners:
- platform-engineering-team
badges:
- content: Compute Reference
backgroundColor: blue
textColor: blue
---
The compute platform hosts 16 application Container Apps plus the Quartz Dashboard operational tooling container inside the shared Azure Container Apps environment on the `Consumption` workload profile. Every workload runs in single-revision mode with at least one active replica.
## Compute Tiers and Workload Topology
## Component & Responsibility
| Component | Role | Protocol / Interface | Persistence / State | Notes |
| :------------------------------------- | :-------------------------------------------------------- | :---------------------------------- | :------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------ |
| **API Gateway** | Public edge reverse proxy (YARP) | External HTTPS (`5000`) | Stateless | Routes frontends, APIs, and identity proxy |
| **Storefront** | Customer catalog browsing & chat UI (Next.js 16) | Internal HTTP (`3000`) | Stateless (Better Auth + Entra ID) | Copilot enabled |
| **Commerce** | Customer basket, checkout & account UI (Next.js 16) | Internal HTTP (`3000`) | Stateless (shares Storefront session) | Health at `/api/health` |
| **Backoffice** | Staff administration UI (Next.js 16) | Internal HTTP (`3000`) | Stateless (Better Auth + Entra ID) | Path prefix & health `/backoffice` |
| [[service\|catalog-api]] | Book, author, category, publisher & vector search API | Internal HTTP `v1` & gRPC | [[container\|catalog-database]], [[container\|catalog-cache]], [[container\|catalog-vector]], [[container\|catalog-blob]] | Entra ID JWT; Foundry consumer |
| [[service\|catalog-ingestion]] | Asynchronous vector-index batch updater (Azure Functions) | Kafka trigger | Reads [[container\|catalog-database]], writes [[container\|catalog-vector]], host storage | Foundry consumer |
| [[service\|basket-api]] | Customer pre-checkout basket service | Internal HTTP `v1` & gRPC | [[container\|basket-database]] | Entra ID JWT; HMAC signing; calls [[service\|catalog-api]] gRPC |
| [[service\|order-api]] | Accepted orders, lifecycle & SSE updates | Internal HTTP `v1` & SSE | [[container\|order-database]], [[container\|order-cache]] | Entra ID JWT; HMAC signing; calls [[service\|catalog-api]] & [[service\|basket-api]] gRPC |
| [[service\|order-orchestration]] | Post-checkout saga orchestrator (Azure Durable Functions) | Kafka triggers | Durable Task Scheduler, host storage | No PostgreSQL database |
| [[service\|chat-api]] | Conversational AI assistant (AG-UI) | Internal HTTP (`/ag-ui`, `/agents`) | [[container\|chat-session-blob]] | Entra ID JWT + Agent Identity; calls [[service\|mcp-server]], [[service\|rating-api]], [[service\|presidio-api]], Foundry |
| [[service\|rating-api]] | Customer feedback & review intelligence agent | Internal HTTP `v1` & A2A gRPC | [[container\|rating-database]], [[container\|rating-cache]] | Entra ID JWT + Agent Identity; calls [[service\|mcp-server]], [[service\|presidio-api]], Foundry |
| [[service\|mcp-server]] | Shared Model Context Protocol server | Internal HTTP (`/mcp`) | Stateless | Entra ID JWT; gateway origin CORS; calls [[service\|catalog-api]] gRPC |
| [[service\|notification-api]] | Transactional order email worker (MailKit + Mjml.Net) | Kafka worker & SMTP | Redis (FusionCache & idempotency) | HMAC signing; no HTTP/gRPC API or SQL DB |
| [[service\|scheduler-service]] | Cron job runner (Quartz.NET) | Internal HTTP & Kafka | [[container\|scheduler-database]] | Explicit start in local run mode |
| [[service\|presidio-api]] (Analyzer) | PII detection sidecar | Internal HTTP (`3000`) | Stateless | `/health` probe; called by [[service\|chat-api]] & [[service\|rating-api]] |
| [[service\|presidio-api]] (Anonymizer) | PII redaction sidecar | Internal HTTP (`3000`) | Stateless | `/health` probe; called by [[service\|chat-api]] & [[service\|rating-api]] |
| **Quartz Dashboard** | Operational job management UI (`/quartz`) | External HTTPS (`8080`) | Reads [[container\|scheduler-database]] via [[service\|scheduler-service]] | [[service\|oauth-api]] OIDC (`admin` role) |
## Configuration & Operational Defaults
### Workload Identity Bindings
User-assigned Managed Identities are provisioned for [[service|catalog-api]], [[service|catalog-ingestion]], [[service|basket-api]], [[service|order-api]], [[service|chat-api]], [[service|rating-api]], [[service|mcp-server]], [[service|notification-api]], [[service|scheduler-service]], [[service|order-orchestration]], Storefront, and Backoffice. API Gateway, Commerce, both Presidio sidecars, and Quartz Dashboard have no workload-specific identity; the environment uses a shared managed identity for registry pulls.
| Workload | Local Dev Ports | Runtime Notes | | :------- | :-------------- | :------------ | |
**API Gateway** | Dynamic (Aspire-assigned) | YARP reverse proxy | | **Storefront** | `3000` |
Next.js standalone container | | **Commerce** | `3001` | Next.js standalone container | |
**Backoffice** | Dynamic | Next.js standalone container | | [[service\|catalog-api]] | HTTP
`5100`, HTTPS `7187` | .NET 11 Minimal API + gRPC | | [[service\|catalog-ingestion]] | Functions
`7071` | Azure Functions Kafka trigger | | [[service\|basket-api]] | HTTP `5052`, HTTPS `7155` |
.NET 11 Minimal API + gRPC | | [[service\|order-api]] | HTTP `5244`, HTTPS `7203` | .NET 11
Minimal API + Marten | | [[service\|order-orchestration]] | Functions `7072` | Connected to
Durable Task Scheduler | | [[service\|chat-api]] | HTTP `5026`, HTTPS `7132` | .NET 11 +
Microsoft Agent Framework (AG-UI) | | [[service\|rating-api]] | HTTP `5278`, HTTPS `7003` | .NET
11 + Microsoft Agent Framework (A2A gRPC) | | [[service\|mcp-server]] | HTTP `5243`, HTTPS
`7193` | .NET 11 MCP server at `/mcp` | | [[service\|notification-api]] | HTTP `5259`, HTTPS
`7036` | .NET 11 worker (MailKit + Mjml.Net) | | [[service\|scheduler-service]] | HTTP `5062`,
HTTPS `7062` | Runs vector batch (5m) and heartbeat (30s) jobs | | [[service\|presidio-api]] |
Dynamic HTTPS (dev) / HTTP `3000` (prod) | Uses developer cert in local run mode |
## Guardrails & Constraints
The published deployment baseline declares single-revision mode with a minimum of 1 replica on all
17 Container Apps, with no upper replica limit or scale rules. Establish explicit upper bounds and
scale signals before production capacity commitments.
Developer and diagnostic containers (Scalar, MCP Inspector, pgAdmin, RedisInsight, Kafka UI, Azure
Storage Explorer, Cosmos DB Data Explorer, and Mailpit) are active only in local run mode and are
never deployed to Azure.
## Related Documentation
- [[doc|platform/001-platform-overview]] — Shared platform layer and API Gateway route map.
- [[doc|platform/003-data-ai-and-messaging-resources]] — Datastores backing each workload.
- [[doc|platform/004-identity-and-rbac-matrix]] — Role assignments and scopes per workload.
- [[doc|operational/003-incident-response-and-runbooks]] — Recovery steps for failing Container Apps.
---
title: Stateful Data, AI & Messaging Infrastructure
summary: Technical reference for Azure-managed databases, caches, storage, Durable Task Scheduler, Microsoft Foundry, and external dependencies.
owners:
- platform-engineering-team
badges:
- content: Infrastructure Reference
backgroundColor: blue
textColor: blue
---
Each BookWorm bounded context owns its authoritative persistence, isolated behind service APIs and authenticated via Microsoft Entra ID RBAC. This reference documents the Azure-managed data and AI stores alongside external messaging, vector search, and email dependencies.
## Data, AI, and Messaging Topology
## Component & Responsibility
| Component | Role | Protocol / Interface | Persistence / State | Notes |
| :----------------------------- | :---------------------------------------------- | :------------------------------------------ | :-------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------- |
| **PostgreSQL Flexible Server** | Relational & event-store persistence | PostgreSQL 16 (Entra ID auth) | [[container\|catalog-database]], [[container\|order-database]], [[container\|scheduler-database]] | Password auth disabled; PgBouncer in Staging/Prod |
| **Azure Managed Redis** | Distributed cache, basket state & idempotency | TLS port `10000` (Entra ID auth) | [[container\|basket-database]], [[container\|catalog-cache]], [[container\|order-cache]], [[container\|rating-cache]] | Used by [[service\|catalog-api]], [[service\|basket-api]], [[service\|order-api]], [[service\|rating-api]], [[service\|notification-api]] |
| **Azure Cosmos DB** | Customer feedback document store | EF Core Cosmos (Session consistency) | [[container\|rating-database]] (partitioned by book ID) | Owned by [[service\|rating-api]] only |
| **Azure Storage** | Blob assets & Azure Functions host state | HTTPS (TLS 1.2+, Managed Identity) | [[container\|catalog-blob]], [[container\|chat-session-blob]], Functions host | Public blob access disabled |
| **Durable Task Scheduler** | Durable orchestration state & timers | Managed Identity auth | Order workflow task hub | Owned by [[service\|order-orchestration]] only |
| **Microsoft Foundry** | Managed LLM chat, routing & embedding inference | HTTPS (Cognitive Services User RBAC) | Stateless inference (`S0` + App Insights) | Used by [[service\|catalog-api]], [[service\|catalog-ingestion]], [[service\|chat-api]], [[service\|rating-api]] |
| **Kafka Broker** | Asynchronous event & command transport | Kafka | Topic logs & dead-letter queues | Wolverine transport with CloudEvents JSON |
| **Qdrant Cloud** | Derived semantic vector search index | gRPC / HTTP | [[container\|catalog-vector]] | Read by [[service\|catalog-api]]; written by [[service\|catalog-ingestion]] |
| **SMTP Relay** | External transactional email delivery | SMTP port `587` ([[service\|sendgrid-api]]) | Stateless relay | Used by [[service\|notification-api]]; Mailpit in local run mode |
## Configuration & Operational Defaults
### Data Ownership per Service
| Service | Primary store | Cache / idempotency | Messaging | Other |
| :------------------------------- | :----------------------------------------------- | :-------------------------------- | :-------------------------------- | :------------------------------------------------------------------ |
| [[service\|catalog-api]] | [[container\|catalog-database]] | [[container\|catalog-cache]] | Kafka + PostgreSQL outbox/inbox | [[container\|catalog-vector]], [[container\|catalog-blob]], Foundry |
| [[service\|catalog-ingestion]] | [[container\|catalog-database]] (read) | — | Kafka trigger + PostgreSQL outbox | [[container\|catalog-vector]] (write), Foundry, host storage |
| [[service\|basket-api]] | [[container\|basket-database]] | [[container\|basket-database]] | Kafka | No SQL database |
| [[service\|order-api]] | [[container\|order-database]] (EF Core + Marten) | [[container\|order-cache]] | Kafka + PostgreSQL outbox/inbox | — |
| [[service\|order-orchestration]] | Durable Task Scheduler | — | Kafka | Host storage; no PostgreSQL |
| [[service\|rating-api]] | [[container\|rating-database]] | [[container\|rating-cache]] | Kafka + Cosmos DB persistence | Foundry; no PostgreSQL |
| [[service\|chat-api]] | [[container\|chat-session-blob]] | — | — | Foundry; no PostgreSQL, Redis, or Kafka |
| [[service\|mcp-server]] | — (stateless) | — | — | — |
| [[service\|notification-api]] | — | Redis (FusionCache + idempotency) | Kafka | MailKit + Mjml.Net over SMTP; no PostgreSQL |
| [[service\|scheduler-service]] | [[container\|scheduler-database]] | — | Kafka + PostgreSQL outbox/inbox | — |
### Kafka Messaging Conventions
- **Transport:** Wolverine with Kafka transport and CloudEvents JSON serialization (propagates W3C trace context, request ID, and user identity).
- **Default topic naming:** `bookworm.{env}.{owner-service}.{topic-name}` (exception: `scheduler.process-vector-batch` is unprefixed).
- **Dead-letter queues:** One native dead-letter queue per service (`bookworm.{env}.{service}.dead-letter-queue`).
- **Retry policy:** Cooldowns of `50ms`, `250ms`, and `1s` with full jitter before routing to the native dead-letter queue.
#### PostgreSQL Flexible Server
| Property | `Development` | `Staging` | `Production` |
| :------- | :------------ | :-------- | :----------- |
| SKU / tier | `Standard_B1ms` (Burstable) | `Standard_D2ds_v5` (General Purpose) | `Standard_D4ds_v5` (General Purpose) |
| High availability | Disabled | Zone-redundant (zones 1 & 2) | Zone-redundant (zones 1 & 2) |
| Backup retention | 7 days | 14 days | 35 days |
| Geo-redundant backup | Disabled | Disabled | Enabled |
| Storage | 32 GB, auto-grow off | 128 GB, auto-grow on | 256 GB, auto-grow on |
| PgBouncer | Disabled | Enabled | Enabled |
#### Azure Managed Redis
| Property | `Development` | `Staging` | `Production` |
| :------- | :------------ | :-------- | :----------- |
| SKU | `BalancedB0` | `BalancedB1` | `BalancedB5` |
| High availability | Disabled | Enabled | Enabled |
#### Azure Cosmos DB
| Property | `Development` | `Staging` | `Production` |
| :------- | :------------ | :-------- | :----------- |
| Capacity mode | Serverless | Serverless | Provisioned throughput |
| Local (key) auth | Enabled | Disabled | Disabled |
#### Azure Storage (publish mode only)
| Property | `Development` | `Staging` | `Production` |
| :------- | :------------ | :-------- | :----------- |
| SKU | `Standard_LRS` | `Standard_ZRS` | `Standard_GZRS` |
| Access tier / TLS | Hot / TLS 1.2+ | Hot / TLS 1.2+ | Hot / TLS 1.2+ |
Foundry provisions SKU `S0` with an `Agents` capability host and links Application Insights. All deployments use `GlobalStandard` capacity `1`.
| Deployment | Model | Version | Purpose |
| :--------- | :---- | :------ | :------ |
| `chat` | `model-router` | `2025-11-18` | Chat completions and agent reasoning |
| `decision` | `Microsoft-Decision-1` | `1` | Chat workflow routing decisions |
| `embedding` | `embed-v-4-0` | `6` | Catalog vector embeddings |
## Guardrails & Constraints
Azure Storage Blob CORS currently permits all origins (`*`, 1-hour cache), and Durable Task
Scheduler declares an open IP allowlist (`0.0.0.0/0`). Restrict both to known gateway and workload
boundaries before Production; see [[doc|operational/004-security-hardening-checklist]].
PostgreSQL hosts **only** [[container|catalog-database]], [[container|order-database]], and
[[container|scheduler-database]]. [[service|order-orchestration]], [[service|notification-api]],
[[service|basket-api]], [[service|rating-api]], and [[service|chat-api]] must never provision
relational PostgreSQL databases.
## Related Documentation
- [[doc|platform/002-compute-and-container-apps]] — Workloads that consume these resources.
- [[doc|platform/004-identity-and-rbac-matrix]] — Role assignments for each resource.
- [[doc|operational/004-security-hardening-checklist]] — Network, backup, and quota hardening.
- [[doc|operational/003-incident-response-and-runbooks]] — Datastore and messaging recovery steps.
---
title: Identity, Entra Agent Identities & RBAC Matrix
summary: Reference for Microsoft Entra ID app registrations, Agent Identities for OBO token exchange, and per-service Managed Identity RBAC assignments.
owners:
- platform-engineering-team
badges:
- content: Security & IAM
backgroundColor: purple
textColor: purple
---
Microsoft Entra ID authenticates users and AI agents across BookWorm, while user-assigned Managed Identities authorize service-to-resource access in Azure without static passwords or connection keys. Frontends maintain user sessions with Better Auth backed by Entra ID, and AI agents exchange user assertions via On-Behalf-Of (OBO) federated credentials.
## Identity, Agent OBO, and RBAC Boundaries
## Component & Responsibility
| Component | Role | Protocol / Interface | Persistence / State | Notes |
| :------------------------- | :------------------------------------------ | :------------------------------ | :------------------------------ | :------------------------------------------------------- |
| [[service\|oauth-api]] | Primary user and API identity provider | OAuth 2.0 / OIDC / JWT Bearer | External tenant | Local dev cert in run mode; federated MI in publish mode |
| **Entra Agent Identities** | Federated OBO agent blueprints & identities | Token Exchange FIC | External tenant (single-tenant) | Provisioned in publish mode only |
| **Frontend Sessions** | Browser session & OAuth2 callback handling | Better Auth + Entra ID | Cookie / session state | Commerce shares the Storefront session |
| **Quartz Dashboard Auth** | Administrative UI authentication | OpenID Connect (`/signin-oidc`) | Session cookie | Requires Entra ID `admin` app role |
| **Managed Identities** | Passwordless service-to-Azure RBAC | Azure Workload Identity | Azure RBAC assignments | Environment identity holds `AcrPull` |
## Configuration & Operational Defaults
### App Roles & OAuth2 Scopes
| Role value | Display name | Allowed member types | Description |
| :-------------- | :----------- | :-------------------- | :--------------------------------------- |
| `admin` | Admin | `User`, `Application` | Manages all aspects of the application |
| `business_user` | BusinessUser | `User`, `Application` | Manages books and catalog reference data |
| `customer` | Customer | `User`, `Application` | Browses and purchases books |
Each protected .NET API registers read and write scopes (12 total):
| Service | Read scope | Write scope |
| :----------------------- | :-------------- | :--------------- |
| [[service\|catalog-api]] | `catalog_read` | `catalog_write` |
| [[service\|mcp-server]] | `mcptools_read` | `mcptools_write` |
| [[service\|basket-api]] | `basket_read` | `basket_write` |
| [[service\|order-api]] | `ordering_read` | `ordering_write` |
| [[service\|chat-api]] | `chatting_read` | `chatting_write` |
| [[service\|rating-api]] | `rating_read` | `rating_write` |
### Managed Identity RBAC Matrix
| Service | PostgreSQL | Azure Managed Redis | Cosmos DB | Azure Storage | Microsoft Foundry | Other |
| :--------------------------------------------------------------------- | :-------------------------------- | :------------------ | :----------------------------- | :---------------------------- | :---------------------- | :--------------------- |
| [[service\|catalog-api]] | [[container\|catalog-database]] | Yes | — | Storage Blob Data Contributor | Cognitive Services User | — |
| [[service\|catalog-ingestion]] | [[container\|catalog-database]] | — | — | Storage Blob Data Owner | Cognitive Services User | — |
| [[service\|basket-api]] | — | Yes | — | — | — | — |
| [[service\|order-api]] | [[container\|order-database]] | Yes | — | — | — | — |
| [[service\|order-orchestration]] | — | — | — | Storage Blob Data Owner | — | Durable Task Scheduler |
| [[service\|chat-api]] | — | — | — | Storage Blob Data Contributor | Cognitive Services User | — |
| [[service\|rating-api]] | — | Yes | [[container\|rating-database]] | — | Cognitive Services User | — |
| [[service\|notification-api]] | — | Yes | — | — | — | — |
| [[service\|scheduler-service]] | [[container\|scheduler-database]] | — | — | — | — | — |
| [[service\|mcp-server]], Gateway, Frontends, [[service\|presidio-api]] | — | — | — | — | — | — |
| Environment identity | — | — | — | — | — | `AcrPull` on ACR |
PostgreSQL assigns each service principal as a Flexible Server administrator. Redis uses the default database access policy. Cosmos DB assigns the built-in Data Contributor role at the account scope.
| Client | Callback path |
| :----- | :------------ |
| **Storefront** | `/api/auth/oauth2/callback/microsoft-entra-id` (via Gateway) |
| **Backoffice** | `/backoffice/api/auth/oauth2/callback/microsoft-entra-id` (via Gateway) |
| **Commerce** | — (shares Storefront session) |
| **Quartz Dashboard** | `/signin-oidc` (via Quartz Dashboard host) |
In local run mode, the gateway's local HTTP endpoint is also registered as a redirect URI. Quartz Dashboard uses OpenID Connect against the tenant v2.0 authority and restricts access to the `admin` role.
Each Federated Identity Credential (FIC) trusts the parent Entra ID service principal (`api://AzureADTokenExchange` audience) and is scoped to the deployment environment.
| Identity | Purpose | Assigned workload |
| :------- | :------ | :---------------- |
| **BookWorm Agent Identity Blueprint** | Parent agent identity blueprint | Platform-wide |
| **BookWorm Chat Agent** | OBO token exchange for conversational discovery | [[service\|chat-api]] |
| **BookWorm Rating Agent** | OBO token exchange for review intelligence | [[service\|rating-api]] |
| Azure built-in role | Role definition GUID | Assigned to |
| :------------------ | :------------------- | :---------- |
| AcrPull | `7f951dda-4ed3-4680-a7ca-43fe172d538d` | Environment identity |
| Cognitive Services User | `a97b65f3-24c7-4388-baec-2e87135dc908` | [[service\|catalog-api]], [[service\|catalog-ingestion]], [[service\|chat-api]], [[service\|rating-api]] |
| Storage Blob Data Owner | `b7e6dc6d-f1e8-4753-8033-0f276bb0955b` | [[service\|catalog-ingestion]], [[service\|order-orchestration]] |
| Storage Blob Data Contributor | `ba92f5b4-2d11-453d-a403-e96b0029c9fe` | [[service\|catalog-api]], [[service\|chat-api]] |
| Secret | Consumers | Origin |
| :----- | :-------- | :----- |
| **HMAC signing key** | [[service\|basket-api]], [[service\|order-api]], [[service\|notification-api]] | Generated (min length 32, alphanumeric) |
| **Better Auth secret** | Storefront, Backoffice | Generated (min length 32, alphanumeric) |
| **Kafka credentials** | Kafka consumers and producers | External |
| **Qdrant Cloud credentials** | [[service\|catalog-api]], [[service\|catalog-ingestion]] | External |
| **SMTP password** | [[service\|notification-api]] | External ([[service\|sendgrid-api]]) |
## Guardrails & Constraints
HMAC signing keys, Better Auth secrets, and external provider credentials (Kafka, Qdrant Cloud,
and SMTP) sit outside Managed Identity coverage. Rotate them per
[[doc|operational/004-security-hardening-checklist]].
[[service|notification-api]] has a Managed Identity binding only for Azure Managed Redis. It
authenticates to Kafka and the SendGrid SMTP relay using external credentials.
## Related Documentation
- [[doc|platform/001-platform-overview]] — Ingress boundary and Entra ID proxy route.
- [[doc|platform/002-compute-and-container-apps]] — Workloads and their auth configuration.
- [[doc|platform/003-data-ai-and-messaging-resources]] — Resources protected by these role assignments.
- [[doc|operational/003-incident-response-and-runbooks]] — RBAC and On-Behalf-Of (OBO) failure runbooks.
---
title: "Quartz scheduler schema reference"
summary: "PostgreSQL schema, keys, retention limits, and BookWorm job configuration for all 15 Quartz.NET 4.8.1 tables in schedulerdb."
owners:
- platform-engineering-team
badges:
- content: Schema Reference
backgroundColor: blue
textColor: blue
---
[[service|scheduler-service]] persists durable job definitions, cron triggers, cluster locks, and execution history across 15 PostgreSQL tables in [[container|scheduler-database]] using Quartz.NET `4.8.1`. This reference documents the active job schedule, table keys, and retention defaults for platform operators.
## Scheduler Persistence Model
## Component & Responsibility
| Component | Role | Protocol / Interface | Persistence / State | Notes |
| :------------------------------ | :---------------------------------------------------------- | :------------------------------------------------------------------------------- | :------------------------------------------------------------------------- | :---------------------------------------------------------- |
| [[service\|scheduler-service]] | Executes durable cron jobs & syncs schedule definitions | Quartz.NET `4.8.1` + Kafka | [[container\|scheduler-database]] (PostgreSQL) | Processor-count concurrency; drains active jobs on shutdown |
| **Quartz Dashboard** | Operational UI for inspecting jobs & triggering manual runs | External HTTPS (`/quartz`) | Reads [[container\|scheduler-database]] via [[service\|scheduler-service]] | Protected by [[service\|oauth-api]] OIDC (`admin` role) |
| **Core Job & Trigger Tables** | Stores job definitions, triggers, and cron expressions | PostgreSQL (`qrtz_job_details`, `qrtz_triggers`, `qrtz_cron_triggers`) | Relational (FK cascade) | Synced every 1 minute from schedule config |
| **Cluster & Lock Tables** | Coordinates active firings, heartbeats, and row locks | PostgreSQL (`qrtz_fired_triggers`, `qrtz_scheduler_state`, `qrtz_locks`) | Ephemeral / cluster state | Scoped by `sched_name` |
| **Execution & Misfire History** | Tracks job outcomes, retries, logs, and misfires | PostgreSQL (`qrtz_execution_history`, `qrtz_misfire_history`, `qrtz_job_status`) | 30-day retention, max `100,000` entries | Rolling summary in `qrtz_job_status` |
## Configuration & Operational Defaults
### Active Scheduled Jobs
| Job name | Trigger name | Group | Cron expression (UTC) | Misfire policy | Durable / Recover | Concurrency |
| :---------------------- | :-------------------------- | :---------- | :--------------------------- | :------------- | :---------------- | :----------------- |
| `ProcessVectorBatchJob` | `ProcessVectorBatchTrigger` | `Scheduler` | `0 0/5 * * * ?` (every 5m) | Fire once now | `true` / `false` | Non-concurrent |
| `HeartbeatJob` | `HeartbeatTrigger` | `Scheduler` | `0/30 * * * * ?` (every 30s) | Fire once now | `true` / `false` | Concurrent allowed |
`ProcessVectorBatchJob` publishes [[event|ProcessVectorBatchIntegrationEvent]] to [[channel|scheduler.process-vector-batch]] via Wolverine's PostgreSQL outbox in [[container|scheduler-database]]. Schedule configuration is scanned every 1 minute, overwriting existing definitions and failing fast on missing or invalid schedules.
### Core Tables
#### `qrtz_job_details`
Primary key: `(sched_name, job_name, job_group)`.
| Column | Type | Required | Description |
| :------------------ | :-------- | :------- | :----------------------------------------------------- |
| `sched_name` | `text` | Yes | Logical Quartz scheduler name |
| `job_name` | `text` | Yes | Unique job name within `job_group` |
| `job_group` | `text` | Yes | Logical job group (`Scheduler` in BookWorm) |
| `description` | `text` | No | Human-readable operator description |
| `job_class_name` | `text` | Yes | Fully qualified job type name |
| `is_durable` | `boolean` | Yes | Keeps the job stored when no triggers reference it |
| `is_nonconcurrent` | `boolean` | Yes | Prevents overlapping runs |
| `is_update_data` | `boolean` | Yes | Persists modified `JobDataMap` entries after execution |
| `requests_recovery` | `boolean` | Yes | Re-executes the job if a node crashes mid-run |
| `job_data` | `bytea` | No | Serialized binary `JobDataMap` payload |
#### `qrtz_triggers`
Primary key: `(sched_name, trigger_name, trigger_group)`. Foreign key: `(sched_name, job_name, job_group)` -> `qrtz_job_details`.
| Column | Type | Required | Description |
| :---------------------------------------------------------------------------- | :------------------------- | :------- | :------------------------------------------------------- |
| `sched_name`, `trigger_name`, `trigger_group` | `text` | Yes | Composite primary key |
| `job_name`, `job_group` | `text` | Yes | Target job in `qrtz_job_details` |
| `description` | `text` | No | Human-readable trigger description |
| `next_fire_time`, `prev_fire_time` | `bigint` | No | Next and most recent fire timestamps (UTC ticks) |
| `priority` | `integer` | No | Firing priority when triggers share a fire time |
| `trigger_state` | `text` | Yes | `WAITING`, `ACQUIRED`, `PAUSED`, `BLOCKED`, or `ERROR` |
| `trigger_type` | `text` | Yes | `CRON`, `SIMPLE`, `SIMPROP`, or `BLOB` |
| `start_time`, `end_time` | `bigint` | Yes / No | Active window timestamps (UTC ticks) |
| `calendar_name` | `text` | No | Optional exclusion calendar in `qrtz_calendars` |
| `misfire_instr`, `misfire_orig_fire_time`, `misfire_threshold` | `smallint` / `bigint` | No | Misfire handling code, original fire time, and threshold |
| `execution_group`, `preferred_node`, `preferred_node_auto` | `varchar(200)` / `boolean` | No / Yes | Execution grouping and cluster node affinity |
| `retry_policy`, `retry_attempt` | `varchar(250)` / `integer` | No | Retry policy descriptor and current attempt count |
| `continues_trigger_name`, `continues_trigger_group`, `continuation_condition` | `text` / `integer` | No | Follow-on continuation trigger metadata |
| `overlap_policy`, `fixed_delay` | `integer` / `boolean` | No | Overlap policy and fixed-delay scheduling flag |
| `pause_reason`, `paused_by`, `paused_at` | `varchar` / `bigint` | No | Pause audit metadata |
| `job_data` | `bytea` | No | Serialized trigger-scoped `JobDataMap` payload |
#### `qrtz_cron_triggers`
Primary / foreign key: `(sched_name, trigger_name, trigger_group)` -> `qrtz_triggers`.
| Column | Type | Required | Description |
| :-------------------------------------------- | :----- | :------- | :--------------------------------------------- |
| `sched_name`, `trigger_name`, `trigger_group` | `text` | Yes | Composite primary/foreign key |
| `cron_expression` | `text` | Yes | Quartz cron expression (e.g., `0 0/5 * * * ?`) |
| `time_zone_id` | `text` | No | Time zone ID (`UTC` in BookWorm) |
Because BookWorm defines cron triggers only, `qrtz_simple_triggers`, `qrtz_simprop_triggers`, `qrtz_blob_triggers`, and `qrtz_calendars` remain empty unless ad-hoc triggers or calendars are added at runtime.
| Table | Primary Key | Purpose |
| :---- | :---------- | :------ |
| `qrtz_simple_triggers` | `(sched_name, trigger_name, trigger_group)` | Fixed-interval repeat schedules (`repeat_count`, `repeat_interval`, `times_triggered`) |
| `qrtz_simprop_triggers` | `(sched_name, trigger_name, trigger_group)` | Calendar-interval and daily-time-interval property slots (`str_prop_*`, `int_prop_*`, `long_prop_*`, `dec_prop_*`, `bool_prop_*`, `time_zone_id`) |
| `qrtz_blob_triggers` | `(sched_name, trigger_name, trigger_group)` | Binary-serialized custom triggers (`blob_data`) |
| `qrtz_calendars` | `(sched_name, calendar_name)` | Serialized exclusion/inclusion `calendar` definitions |
| `qrtz_paused_trigger_grps` | `(sched_name, trigger_group)` | Cluster-wide paused trigger groups with `pause_reason`, `paused_by`, `paused_at` |
| `qrtz_paused_job_grps` | `(sched_name, job_group)` | Cluster-wide paused job groups with `pause_reason`, `paused_by`, `paused_at` |
| Table | Primary Key | Key Columns |
| :---- | :---------- | :---------- |
| `qrtz_fired_triggers` | `(sched_name, entry_id)` | `trigger_name`, `trigger_group`, `instance_name`, `fired_time`, `sched_time`, `priority`, `state` (`ACQUIRED`, `EXECUTING`, `BLOCKED`), `job_name`, `job_group`, `is_nonconcurrent`, `requests_recovery`, `progress`, `progress_message`, `interrupt_requested_time` |
| `qrtz_scheduler_state` | `(sched_name, instance_name)` | `last_checkin_time`, `checkin_interval`, `quartz_version` (`4.8.1`) |
| `qrtz_locks` | `(sched_name, lock_name)` | Row-level coordination locks (`TRIGGER_ACCESS`, `STATE_ACCESS`) |
| Table | Primary Key | Key Columns |
| :---- | :---------- | :---------- |
| `qrtz_execution_history` | `(sched_name, entry_id)` | `instance_name`, `job_name`, `job_group`, `trigger_name`, `trigger_group`, `fired_time`, `run_time`, `succeeded`, `error_message`, `retry_attempt`, `retry_scheduled`, `execution_log`, `result`, `summary`, `metrics`, `manual`, `fire_instance_id`, `job_input`, `job_input_too_large` |
| `qrtz_misfire_history` | `(sched_name, entry_id)` | `instance_name`, `trigger_name`, `trigger_group`, `job_name`, `job_group`, `misfire_time`, `sched_time`, `reason` |
| `qrtz_job_status` | `(sched_name, job_group, job_name)` | `first_fired_time`, `last_fired_time`, `last_result`, `last_run_time`, `last_instance_name`, `last_entry_id`, `last_summary`, `last_success_time`, `last_failure_time`, `last_failure_message`, `consecutive_failures`, `run_count` |
### Inspect Recent Job Health
```sql
SELECT
job_group,
job_name,
run_count,
consecutive_failures,
last_failure_message
FROM qrtz_job_status
ORDER BY job_group, job_name;
```
## Guardrails & Constraints
Never modify `qrtz_*` rows directly in PostgreSQL. Manage schedules through declarative
configuration or the Quartz Dashboard so Quartz validates cron expressions, updates binary
payloads safely, and preserves cluster lock invariants.
All `BIGINT` timestamp columns store 100-nanosecond UTC ticks from year `0001`, not Unix epoch
milliseconds.
## Related Documentation
- [[doc|platform/003-data-ai-and-messaging-resources]] — Platform storage inventory including [[container|scheduler-database]].
- [[doc|platform/002-compute-and-container-apps]] — Hosting details for [[service|scheduler-service]] and Quartz Dashboard.
---
title: "API and contracts index"
summary: "Consolidated index of BookWorm HTTP v1, gRPC, AG-UI, MCP, A2A, and Kafka/Wolverine contracts grouped by service with auth, gateway routes, and error rules."
owners:
- platform-engineering-team
badges:
- content: Contracts Reference
backgroundColor: blue
textColor: blue
---
This index consolidates all synchronous HTTP `v1`, gRPC, AG-UI, Model Context Protocol (MCP), Agent-to-Agent (A2A), and asynchronous Kafka/Wolverine contracts across BookWorm's 10 backend services and 3 external integrations. Use it to locate gateway routes, local ports, Microsoft Entra ID scopes, RFC 9457 error semantics, and per-service contract links.
## Protocol and Contract Interaction Fabric
## Component & Responsibility
| Component | Role | Protocol / Interface | Persistence / State | Notes |
| :------------------------------- | :------------------------------- | :------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------- |
| [[service\|catalog-api]] | Book catalog & vector search | HTTP `v1` (`/catalog/api/v1/*`), gRPC server, Kafka | [[container\|catalog-database]], [[container\|catalog-vector]], [[container\|catalog-blob]], [[container\|catalog-cache]] | `catalog_read`; `business_user` or `admin` + `catalog_read/write` |
| [[service\|catalog-ingestion]] | Vector index batch ingestion | Kafka trigger (Azure Functions) | Reads [[container\|catalog-database]], writes [[container\|catalog-vector]] | Managed Identity RBAC; internal only |
| [[service\|basket-api]] | Pre-checkout customer basket | HTTP `v1` (`/basket/api/v1/baskets`), gRPC server & client, Kafka | [[container\|basket-database]] | `customer` + `basket_read`, `basket_write` |
| [[service\|order-api]] | Accepted orders & lifecycle | HTTP `v1` (`/ordering/api/v1/*`) + SSE, gRPC clients, Kafka | [[container\|order-database]], [[container\|order-cache]] | `customer` or `admin` + `ordering_read/write` |
| [[service\|order-orchestration]] | Post-checkout saga orchestrator | Kafka triggers + Durable Functions | Durable Task Scheduler | Managed Identity RBAC; internal only |
| [[service\|rating-api]] | Customer feedback & review agent | HTTP `v1` (`/rating/api/v1/feedbacks*`), A2A gRPC, MCP client, Kafka | [[container\|rating-database]], [[container\|rating-cache]] | `rating_read` (A2A); `admin` + `rating_read/write`; Agent Identity |
| [[service\|chat-api]] | Conversational book discovery | AG-UI (`/chatting/*`), Agent Discovery, MCP & A2A clients | [[container\|chat-session-blob]] | `customer` or `admin` + `chatting_read/write`; Agent Identity |
| [[service\|mcp-server]] | Shared AI tool & prompt catalog | MCP Streamable HTTP (`/mcp`), gRPC client | Stateless | `mcptools_read`; internal with gateway CORS |
| [[service\|notification-api]] | Transactional order email worker | Kafka worker, MailKit SMTP | Redis idempotency only | Internal worker + Managed Identity (Redis) |
| [[service\|scheduler-service]] | Cron scheduler & admin UI | Quartz.NET (`/quartz`), Kafka | [[container\|scheduler-database]] | Quartz Dashboard: Entra ID OIDC `admin` role |
| [[service\|oauth-api]] | Identity & OBO token provider | OAuth 2.0 / OIDC (`/entra/*`) | External provider | Roles: `admin`, `business_user`, `customer` |
| [[service\|presidio-api]] | PII detection & redaction | Internal HTTP (`3000`: `/analyze`, `/anonymize`) | Stateless containers | Fail-closed dependency for [[service\|chat-api]] & [[service\|rating-api]] |
| [[service\|sendgrid-api]] | Email delivery boundary | SMTP (`587`) | External provider | Authenticated via SMTP API key |
## Configuration & Operational Defaults
### Global API & Error Conventions
- **Single public ingress:** External browser and API traffic enters through the YARP API Gateway, which strips `/{service}` prefixes before forwarding.
- **API versioning:** REST services use URL-segment and header versioning (`V1` at `/api/v1/...`).
- **Rate limiting:** Global chained limiter (100 concurrent requests + 30 requests/minute per IP/Host) plus a per-user token bucket (30-token burst, 20 tokens replenished every 10s, queue limit 5).
- **Standard error format:** HTTP services return RFC 9457 Problem Details JSON (`application/problem+json`).
| Status | Meaning | Typical cause | Client recovery |
| :---------------------- | :-------------------------------- | :--------------------------------------------------------------------------------- | :--------------------------------------------------- |
| `400 Bad Request` | Validation or domain-rule failure | Payload validation error, missing request ID header, or invalid Order transition | Fix payload or preconditions; do not retry unchanged |
| `401 Unauthorized` | Authentication failed | Missing, expired, or invalid Microsoft Entra ID JWT | Re-authenticate and retry |
| `403 Forbidden` | Authorization denied | Token lacks required Entra ID role or scope | Request token with required role and scopes |
| `404 Not Found` | Missing or out-of-scope resource | Entity does not exist or belongs to another customer | Verify resource ID and ownership |
| `409 Conflict` | Concurrency or duplicate request | Duplicate request ID (1-hour Redis window), lock contention, or duplicate feedback | Query current state before issuing a new request |
| `429 Too Many Requests` | Rate limit exceeded | Global or per-user rate limit hit (`Retry-After` header included) | Back off for `Retry-After` seconds and retry |
| `500 / 502 / 503` | Server or upstream failure | Unhandled error or unavailable downstream dependency (e.g., fail-closed Presidio) | Retry idempotent requests with exponential backoff |
### Synchronous gRPC, MCP, and A2A Contracts
| Contract | Server | Clients | Operations |
| :------------------------------- | :----------------------- | :----------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `book.v1.BookGrpcService` | [[service\|catalog-api]] | [[service\|basket-api]], [[service\|order-api]], [[service\|mcp-server]] | [[query\|GetBookGrpc]], [[query\|GetBooksGrpc]], [[query\|GetBookDetailsGrpc]], [[query\|ListBooksGrpc]], [[query\|ListCategoriesGrpc]], [[query\|ListAuthorsGrpc]], [[query\|GetDashboardGrpc]] (`admin`) |
| `basket.v1.BasketGrpcService` | [[service\|basket-api]] | [[service\|order-api]] | [[query\|GetBasketGrpc]] |
| **A2A gRPC** | [[service\|rating-api]] | [[service\|chat-api]] (`rating_read`) | Delegates conversational review insights to [[agent\|rating-agent]] |
| **MCP Streamable HTTP** (`/mcp`) | [[service\|mcp-server]] | [[service\|chat-api]], [[service\|rating-api]] | Tools: `search_catalog`, `get_book`, `list_categories`, `list_authors`; Prompts: `recommend_books`, `summarize_rating`, `reduce_rating_summaries`, `analyze_book_quality` |
### Asynchronous Kafka / Wolverine Contracts
Topics follow `bookworm.{env}.{owner}.{topic}` (exception: `scheduler.process-vector-batch`). Messages use CloudEvents JSON envelopes, W3C trace propagation, retry cooldowns (`50ms`, `250ms`, `1s` with jitter), and per-service native dead-letter queues.
| Message | Type | Kafka topic | Producer | Consumer(s) |
| :------------------------------------------------------ | :------ | :----------------------------------------------------------------------------- | :------------------------------- | :----------------------------------------------------- |
| [[event\|UserCheckedOutIntegrationEvent]] | Event | [[channel\|bookworm.{env}.ordering.user-checked-out]] | [[service\|order-api]] | [[service\|order-orchestration]] |
| [[event\|OrderStatusChangedToCompleteIntegrationEvent]] | Event | [[channel\|bookworm.{env}.ordering.order-status-change-to-complete]] | [[service\|order-api]] | [[service\|order-orchestration]] |
| [[event\|OrderStatusChangedToCancelIntegrationEvent]] | Event | [[channel\|bookworm.{env}.ordering.order-status-change-to-cancel]] | [[service\|order-api]] | [[service\|order-orchestration]] |
| [[command\|PlaceOrderCommand]] | Command | [[channel\|bookworm.{env}.finance.place-order]] | [[service\|order-orchestration]] | [[service\|basket-api]], [[service\|notification-api]] |
| [[command\|CompleteOrderCommand]] | Command | [[channel\|bookworm.{env}.finance.complete-order]] | [[service\|order-orchestration]] | [[service\|notification-api]] |
| [[command\|CancelOrderCommand]] | Command | [[channel\|bookworm.{env}.finance.cancel-order]] | [[service\|order-orchestration]] | [[service\|notification-api]] |
| [[command\|DeleteBasketCompleteCommand]] | Command | [[channel\|bookworm.{env}.finance.delete-basket-complete]] | [[service\|order-orchestration]] | [[service\|order-api]] |
| [[command\|DeleteBasketFailedCommand]] | Command | [[channel\|bookworm.{env}.finance.delete-basket-failed]] | [[service\|order-orchestration]] | [[service\|order-api]] |
| [[event\|BasketDeletedCompleteIntegrationEvent]] | Event | [[channel\|bookworm.{env}.basket.delete-complete]] | [[service\|basket-api]] | [[service\|order-orchestration]] |
| [[event\|BasketDeletedFailedIntegrationEvent]] | Event | [[channel\|bookworm.{env}.basket.delete-failed]] | [[service\|basket-api]] | [[service\|order-orchestration]] |
| [[event\|FeedbackCreatedIntegrationEvent]] | Event | [[channel\|bookworm.{env}.rating.feedback-create]] | [[service\|rating-api]] | [[service\|catalog-api]] |
| [[event\|FeedbackDeletedIntegrationEvent]] | Event | [[channel\|bookworm.{env}.rating.feedback-delete]] | [[service\|rating-api]] | [[service\|catalog-api]] |
| [[event\|BookUpdatedRatingFailedIntegrationEvent]] | Event | [[channel\|bookworm.{env}.catalog.book-update-rating-failed]] | [[service\|catalog-api]] | [[service\|rating-api]] |
| [[event\|ProcessVectorBatchIntegrationEvent]] | Event | [[channel\|scheduler.process-vector-batch]] | [[service\|scheduler-service]] | [[service\|catalog-ingestion]] |
#### Dead-Letter Queues
- [[channel|bookworm.{env}.basket.dead-letter-queue]] (`bookworm.{env}.basket.dead-letter-queue`)
- [[channel|bookworm.{env}.catalog.dead-letter-queue]] (`bookworm.{env}.catalog.dead-letter-queue`)
- [[channel|bookworm.{env}.notification.dead-letter-queue]] (`bookworm.{env}.notification.dead-letter-queue`)
- [[channel|bookworm.{env}.ordering.dead-letter-queue]] (`bookworm.{env}.ordering.dead-letter-queue`)
- [[channel|bookworm.{env}.rating.dead-letter-queue]] (`bookworm.{env}.rating.dead-letter-queue`)
#### AI Agents (5)
- **Conversational:** [[agent|book-agent]], [[agent|book-catalog-researcher]], [[agent|book-recommendation-researcher]], [[agent|qa-agent]]
- **Reviews:** [[agent|rating-agent]]
#### Data Containers (11)
- **Catalog:** [[container|catalog-database]] (PostgreSQL), [[container|catalog-cache]] (Redis), [[container|catalog-vector]] (Qdrant), [[container|catalog-blob]] (Azure Blob)
- **Shopping:** [[container|basket-database]] (Redis)
- **Ordering:** [[container|order-database]] (PostgreSQL + Marten), [[container|order-cache]] (Redis)
- **Reviews:** [[container|rating-database]] (Azure Cosmos DB), [[container|rating-cache]] (Redis)
- **Conversational:** [[container|chat-session-blob]] (Azure Blob)
- **Platform:** [[container|scheduler-database]] (PostgreSQL — see also [[doc|platform/005-quartz-schema]])
#### Domain Entities (10)
- **Catalog:** [[entity|book]], [[entity|author]], [[entity|category]], [[entity|publisher]]
- **Shopping:** [[entity|basket]], [[entity|basket-item]]
- **Ordering:** [[entity|order]], [[entity|order-item]], [[entity|buyer]]
- **Reviews:** [[entity|feedback]]
## Guardrails & Constraints
OpenAPI specification endpoints (`/openapi/v1.json`), interactive Scalar testing, and default
health/liveness endpoints (`/health`, `/alive`) are mapped only in the `Development` environment
and are not exposed in Staging or Production.
## Related Documentation
- [[doc|arc42/00-c4-overview]] — System context and container overview across frontends and backend services.
- [[doc|platform/004-identity-and-rbac-matrix]] — Azure Managed Identity and Microsoft Entra ID permission matrix.
- [[doc|development/008-testing-matrix]] — Backend, frontend, contract, and documentation verification matrix.
---
title: "Start here: BookWorm project guide"
summary: A newcomer's guide to BookWorm's business scope, subdomain topology, team ownership, and where to go next.
version: 1.0.0
type: guides
order: 1
badges:
- content: Guide
backgroundColor: teal
textColor: teal
---
Use this guide to navigate BookWorm's domain architecture documentation in the right order—from the top-level bounded-context map down to individual flows, engineering references, and operational runbooks. To set up your machine and run BookWorm locally, follow [[doc|development/000-local-quickstart]]; for the broader repository contributor overview, start with [[doc|development/001-developer-onboarding]].
## Context and motivation
BookWorm spans 10 deployable .NET 11 backend services/functions and 3 Next.js 16 web applications across six bounded contexts. Reading individual endpoint docs or runbooks before understanding domain ownership leads contributors to place business rules in the wrong service or bypass explicit contracts. Following a top-down reading path builds an accurate mental model before you edit code.
## How it works
This reading path moves from whole-system architecture down to service contracts and operational runbooks.
### Recommended reading order
1. **Whole-system map:** Read [[domain|bookworm]] and the [[doc|arc42/00-c4-overview]] to see how all six bounded contexts and three edge apps fit together.
2. **Owning subdomain:** Open the relevant bounded-context page ([[domain|catalog]], [[domain|shopping]], [[domain|ordering]], [[domain|reviews]], [[domain|conversational]], or [[domain|platform]]) to inspect its services, persistence stores, and invariants.
3. **End-to-end runtime flows:** Review the affected flow under `explanation/architecture/flows/` (such as [[flow|user-checkout]] or [[flow|agent-orchestration]]) before altering cross-service messages.
4. **Engineering standards and ADRs:** Check domain engineering checklists, [[doc|development/004-engineering-standards]], and [[doc|arc42/09-architecture-decisions]] before changing contracts or schemas.
5. **Runbooks:** Consult the domain runbooks under `how-to/domain-runbooks/` when diagnosing production or staging incidents.
### Subdomain ownership summary
For full team charters and repository maintainers, see [[team|architecture-enabling-team]].
| Subdomain | Core responsibility | Recorded domain owner |
| :----------------------------- | :------------------------------------------------------------------ | :-------------------------------------------------------------------------- |
| **[[domain\|catalog]]** | Book metadata, pricing, availability, and hybrid vector search | Business Strategy _(system co-owned by Platform Team and Contributor Team)_ |
| **[[domain\|shopping]]** | Customer-scoped mutable basket and pre-order checkout handoff | Business Strategy |
| **[[domain\|ordering]]** | Accepted orders, purchase-time snapshots, and Finance checkout saga | Business Strategy |
| **[[domain\|reviews]]** | Individual customer feedback (`Cosmos DB`) and AI summaries | Business Strategy |
| **[[domain\|conversational]]** | Privacy-filtered multi-agent chat and read-only Catalog MCP tools | Contributor Team |
| **[[domain\|platform]]** | Recurring Quartz jobs and stateless Kafka-to-SMTP email delivery | Platform Team |
## Design trade-offs
| Decision | Benefits | Costs and limits |
| :-------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------- |
| **Separate domain ownership from system implementation co-ownership** | Business stakeholders steer domain scope while Platform and Contributor engineers share technical stewardship (for example, `Catalog`) | Contributors must verify both domain boundaries and technical owners before proposing contract changes |
| **Dedicated reading guide separate from hands-on setup** | Keeps architecture orientation concise and avoids duplicating `mise` / Aspire setup commands across pages | Developers looking to run code locally must follow the link to [[doc\|development/000-local-quickstart]] |
## Alternatives considered
- **Combining local setup, engineering standards, and domain orientation into one monolithic onboarding page:** Mixes Diátaxis tutorials, reference, and explanation, making the page too long for returning readers and prone to setup-command drift.
## Related documentation
- [[doc|development/000-local-quickstart]] — Guided local quickstart tutorial.
- [[doc|development/001-developer-onboarding]] — Contributor onboarding overview.
- Business capabilities and customer journeys — End-to-end customer journeys across domains.
- Domain principles and boundaries — Ownership rules and pre-change boundary gate.
- [[team|architecture-enabling-team]] — Canonical team charters and maintainers.
- [[doc|arc42/12-glossary]] — Shared platform and domain terms.
---
title: Business capabilities and journey map
summary: The core capabilities BookWorm delivers and how customer journeys cross the catalog, shopping, ordering, reviews, and platform domains.
version: 1.0.0
type: guides
order: 2
badges:
- content: Guide
backgroundColor: blue
textColor: blue
---
BookWorm organizes its online bookstore around six business capabilities aligned to bounded contexts rather than UI screens. Separating capabilities by business ownership lets product discovery, basket management, order processing, customer reviews, AI guidance, and operational messaging evolve independently while delivering one seamless shopping experience.
## Context and motivation
When an e-commerce platform structures code around frontend screens, product rules, basket state, checkout pricing, and order status collapse into one coupled layer. A minor change to search filtering or email formatting then risks corrupting committed orders. BookWorm prevents this coupling by assigning each business capability a single owning context and connecting journeys across explicit HTTP, gRPC, MCP, A2A, and Kafka contracts.
## How it works
This journey map shows how a customer moves through Storefront and Commerce while interacting with each underlying bounded context.
### Capability ownership map
| Capability | Owning bounded context | Primary edge app | Purpose |
| :--------------------------------- | :------------------------- | :--------------------------- | :---------------------------------------------------------------------------------------------------------- |
| **Product discovery and metadata** | [[domain\|catalog]] | Storefront, Backoffice | Maintain canonical titles, authors, categories, publishers, pricing, availability, and hybrid vector search |
| **Basket and checkout intent** | [[domain\|shopping]] | Commerce | Manage mutable customer baskets and initiate checkout handoff |
| **Order lifecycle management** | [[domain\|ordering]] | Commerce, Backoffice | Record accepted purchases with locked prices and manage `New` → `Completed` / `Cancelled` transitions |
| **Customer feedback and ratings** | [[domain\|reviews]] | Storefront, Backoffice | Store individual customer ratings and comments in Cosmos DB and publish summary updates to Catalog |
| **Conversational guidance** | [[domain\|conversational]] | Storefront | Route customer requests through privacy-filtered AI agents for book discovery and policy answers |
| **Scheduling and notifications** | [[domain\|platform]] | Quartz Dashboard (`/quartz`) | Trigger scheduled vector indexing and deliver transactional order emails without owning business state |
### Five end-to-end customer journeys
- **Discovery and selection:** Shoppers browse and search titles in **Storefront** (`@bookworm/storefront`). Catalog is the single source of truth for book details, pricing, and availability; see [[flow|product-ingestion]] and Search and discovery.
- **Basket and checkout:** Authenticated shoppers manage items in **Commerce** (`@bookworm/commerce`) under `/basket` and submit checkout under `/checkout/*`. Shopping holds temporary intent in Redis, while Ordering validates current Catalog pricing and creates an authoritative `Order`; see [[flow|user-checkout]].
- **Order confirmation and processing:** Ordering manages the accepted order lifecycle, while Finance orchestrates post-checkout basket cleanup and triggers Notification email commands over Kafka; see [[flow|order-lifecycle]] and [[flow|notification-delivery]].
- **Reviews and trust signals:** Shoppers submit ratings and comments to Rating API (`Reviews`), which persists individual `Feedback` records in Cosmos DB and publishes Kafka events so Catalog refreshes its derived `Rating summary`; see [[flow|feedback-publication]].
- **Conversational assistance:** Shoppers ask book discovery or store-policy questions via Storefront's CopilotKit chat runtime (`/ag-ui`), routed by `Microsoft-Decision-1` through read-only MCP tools and remote A2A review analysis; see [[flow|agent-orchestration]].
## Design trade-offs
| Decision | Benefits | Costs and limits |
| :-------------------------------------------------------- | :--------------------------------------------------------------------------------------- | :------------------------------------------------------------------------- |
| **Eventually consistent derived views** | Catalog browsing stays fast and available even if Reviews or `Catalog Ingestion` is busy | Rating summaries and Qdrant search vectors can briefly trail source writes |
| **Operational delivery separated from business outcomes** | SMTP outages or email retries never corrupt or roll back accepted `Order` records | Operators must monitor Notification delivery independently of Order status |
| **Capability boundaries over screen-oriented services** | Teams evolve pricing, checkout, and AI agents independently | Cross-context journeys require explicit contracts and Pact verification |
## Alternatives considered
- **Screen-oriented Backend-for-Frontend (BFF) monolith:** Simplifies initial CRUD screens but merges pre-order baskets, committed orders, and product catalogs into one blast radius.
- **Synchronous cross-domain writes:** Guarantees immediate rating and vector consistency but couples Catalog availability directly to Reviews and Microsoft Foundry latency.
## Related documentation
- [[doc|development/001-developer-onboarding]] — Contributor onboarding and platform introduction.
- [[doc|development/000-local-quickstart]] — Step-by-step tutorial to run BookWorm on your machine.
- [[domain|bookworm]] — Strategic DDD map and deployable services.
- Domain principles and boundaries — Ownership rules and pre-change boundary gate.
---
title: Domain principles and boundaries
summary: The guiding principles BookWorm uses to keep ownership, contracts, and change propagation consistent across its bounded contexts.
version: 1.0.0
type: guides
order: 3
badges:
- content: Architecture
backgroundColor: green
textColor: green
---
BookWorm enforces strict bounded-context isolation so every business fact has one authoritative owner, every derived view can be rebuilt safely, and every cross-service interaction uses an explicit versioned contract. These principles prevent shared-database coupling and keep operational work (scheduling and email delivery) cleanly separated from core commerce state.
## Context and motivation
As a microservices platform grows, reading or mutating another service's database table directly is the fastest way to create hidden coupling and data corruption. BookWorm eliminates shared-table shortcuts by pairing clear domain ownership rules with automated verification in CI (`ArchUnitNET.TUnit`, Pact consumer/provider tests, `buf breaking`, and `turbo boundaries`).
## How it works
This diagram summarizes the four boundary rules governing data ownership and cross-context communication in BookWorm.
### Four guiding principles
- **One authoritative source of truth:** Each business record belongs to one bounded context—books to [[domain|catalog]], baskets to [[domain|shopping]], accepted orders to [[domain|ordering]], and individual reviews to [[domain|reviews]].
- **Derived views are disposable and rebuildable:** Catalog rating summaries, Qdrant vector indexes, FusionCache entries, and Marten `OrderSummary` views exist for fast reads and search. They never replace authoritative records and can be regenerated if they drift.
- **Explicit contracts over shared storage:** Services never read or write another context's database. Cross-context communication uses versioned REST (`/api/v1/*`), gRPC (`book.v1`, `basket.v1`), MCP (`/mcp`), A2A gRPC, or CloudEvents Kafka topics.
- **Operational work never mutates business state:** Scheduled jobs (`ProcessVectorBatchJob`, `HeartbeatJob`) and email delivery (`Notification` with MailKit resilience and Kafka DLQs) never alter authoritative `Order` or `Book` business status.
### Ownership matrix
| Bounded context | Authoritative ownership | Explicitly out of scope |
| :----------------------------- | :--------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------- |
| **[[domain\|catalog]]** | Book metadata, taxonomies, pricing, availability, cover blobs, and derived search/rating views | Individual customer reviews, baskets, and accepted order snapshots |
| **[[domain\|shopping]]** | Customer-scoped mutable baskets (`Redis`) and pre-order shopping intent | Accepted orders, order lifecycle state, and product master data |
| **[[domain\|ordering]]** | `Buyer` profiles, `Order` records, purchase-time item snapshots, and lifecycle transitions | Mutable baskets, live catalog descriptions, and external payment settlement |
| **[[domain\|reviews]]** | Individual `Feedback` documents (`Cosmos DB`) and AI feedback summaries | Authoritative book metadata and Catalog's derived rating summary |
| **[[domain\|conversational]]** | AG-UI session state (`chatting-blob`), routing decisions, and agent orchestration | Catalog book records, baskets, billing, and authoritative orders |
| **[[domain\|platform]]** | Quartz schedules (`schedulerdb`), notification idempotency (`Redis`), and SMTP submission | Business records owned by Catalog, Shopping, Ordering, or Reviews |
### Automated boundary enforcement
BookWorm validates these principles automatically in CI rather than relying on manual code review alone:
- **Backend architecture rules:** `tests/BookWorm.ArchTests` (`ArchUnitNET.TUnit`) checks cross-service dependency isolation, domain entity/value-object rules, and handler conventions.
- **Asynchronous message contracts:** Pact.NET consumer and provider tests (`tests/pacts/`) verify Kafka CloudEvents compatibility across producer/consumer pairs.
- **gRPC compatibility:** `buf lint` and `buf breaking --against lock.binpb` protect `book.v1` and `basket.v1` Protobuf schemas.
- **Frontend layer boundaries:** `bun run boundaries` (`turbo boundaries` in `src/Clients`) enforces the 4-tier dependency graph (`config` → `foundation` → `domain` → `app`).
### Three-question pre-change boundary gate
Before implementing any cross-context feature, answer three questions:
1. Which bounded context owns the authoritative state?
2. Which explicit versioned contract carries the interaction?
3. Is every downstream copy classified as derived (rebuildable) rather than authoritative?
## Design trade-offs
| Decision | Benefits | Costs and limits |
| :---------------------------------- | :-------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------- |
| **No cross-service database reads** | Services deploy and change schemas independently without breaking neighbors | Cross-context displays require gRPC enrichment (Basket → Catalog) or asynchronous projections (Reviews → Catalog) |
| **Anti-pattern prohibition** | Prevents hidden coupling, status conflation, and non-rebuildable caches | Requires upfront contract design and Pact/Buf updates when schemas evolve |
### Anti-patterns prohibited in BookWorm
- Querying another service's PostgreSQL, Cosmos DB, or Redis store directly.
- Treating a rating summary, Qdrant vector, or cache entry as authoritative truth.
- Treating Finance saga timeout or SMTP acceptance as proof of `Order` completion or customer inbox delivery.
- Embedding business-state mutations inside Quartz jobs or Notification workers.
## Alternatives considered
- **Shared relational database with cross-schema joins:** Reduces initial query boilerplate but couples every service release to a single schema and removes independent scaling (Cosmos DB for Reviews, Redis for Basket).
## Related documentation
- [[doc|development/001-developer-onboarding]] — High-level contributor guide.
- [[doc|development/000-local-quickstart]] — End-to-end local quickstart tutorial.
- [[domain|bookworm]] — Context map and service inventory.
- [[doc|arc42/12-glossary]] — Canonical terms and ownership notes.
- ADR-BW-001: Capability-aligned boundaries — Architectural decision record for bounded-context decomposition.
---
title: Consistency and data ownership
summary: Authoritative stores, derived projections, transactional boundaries, and propagation guarantees in Catalog.
version: 1.0.0
type: engineering
order: 1
badges:
- content: Architecture
backgroundColor: green
textColor: green
---
## Purpose & Scope
This document defines data ownership, transactional boundaries, cache invalidation, and eventual consistency guarantees for the [[domain|catalog]] subdomain, governing [[service|catalog-api]] and [[service|catalog-ingestion]]. Use it to reason about which stores are authoritative systems of record versus replayable projections before modifying write paths, search indexing, or cross-domain rating handlers.
## Visual Reference
The visual below illustrates how catalog mutations, scheduled vector indexing, and cross-domain rating events propagate across authoritative and derived stores.
_Catalog Write, Cache Invalidation, and Index Propagation Pipeline_
## Core Invariants & Design Rules
- **Authoritative vs. derived separation:** [[container|catalog-database]] (PostgreSQL) is the sole system of record for [[entity|book]], [[entity|author]], [[entity|category]], and [[entity|publisher]] state, while [[container|catalog-blob]] owns binary cover artwork referenced by URN. Both [[container|catalog-cache]] (Redis) and [[container|catalog-vector]] (Qdrant) are disposable projections that can be cleared or rebuilt without data loss.
- **Transactional index queuing:** Mutations to [[entity|book]] records in [[container|catalog-database]] atomically upsert affected book identifiers into an internal pending-update queue via database triggers, coalescing repeated edits under a fresh `revision` UUID and timestamp.
- **Advisory-locked batch ingestion:** [[service|catalog-ingestion]] processes queued updates under PostgreSQL advisory lock `740031001` in batches of up to `200` items, acknowledging only rows whose `(book_id, revision)` pair still matches the batch snapshot so concurrent writes are never lost.
- **Soft-delete propagation:** Deleting a [[entity|book]] sets `is_deleted = true`, triggers the pending-update queue, and causes [[service|catalog-ingestion]] to remove the corresponding UUID from [[container|catalog-vector]].
- **Taxonomy deletion rules:** Deleting a [[entity|category]] or [[entity|publisher]] preserves associated books by clearing the reference, whereas deleting an [[entity|author]] with active books is rejected.
- **Discount price invariant:** A book's discount price must always remain non-negative and less than or equal to its original price.
:::warning
**Never use derived stores for purchase or checkout decisions.** [[service|order-api]] and [[service|basket-api]] must resolve prices and book existence exclusively through gRPC queries backed by [[container|catalog-database]]—never from [[container|catalog-vector]] or stale client caches.
:::
## Boundaries & Guarantees
| Concern | Strategy & Guarantee | Failure / Edge-Case Behavior | Related Resources |
| :-------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Persistence** | catalog-database provides ACID transactions for catalog entities, pending vector updates, and Wolverine outbox/inbox tables; catalog-blob stores cover images with expiring read-only SAS URLs (`1h` default). | Uncommitted writes never enqueue vector updates or outbox messages; missing blobs surface as unavailable cover URLs without corrupting book records. | catalog-database, catalog-blob, adr-001-postgresql-system-of-record, adr-005-blob-storage-for-book-images |
| **Caching** | catalog-cache uses FusionCache L1/L2 with a Redis backplane and `2h` fail-safe; book detail (`book:{id}`) and summary (`book:summary:{id}`) keys expire in `30m` and are actively invalidated on write; dashboard metrics (`catalog:dashboard:v1`) expire every `15s`. | List (`books:list`) and search (`books:search`) keys are tag-invalidated; if Redis is unavailable, FusionCache falls back to L1/fail-safe or direct database reads. | catalog-cache, adr-004-fusioncache-redis-for-catalog-reads |
| **Messaging** | scheduler-service triggers catalog-ingestion every `5m` UTC via ProcessVectorBatchIntegrationEvent; catalog-api consumes FeedbackCreatedIntegrationEvent and FeedbackDeletedIntegrationEvent to project `average_rating` and `total_reviews`. | Missing books on feedback creation emit BookUpdatedRatingFailedIntegrationEvent for compensation; missing books on feedback deletion complete as a no-op; exhausted retries route to `bookworm.{env}.catalog.dead-letter-queue`. | ProcessVectorBatchIntegrationEvent, FeedbackCreatedIntegrationEvent, FeedbackDeletedIntegrationEvent, BookUpdatedRatingFailedIntegrationEvent, `bookworm.{env}.catalog.dead-letter-queue` |
| **Concurrency** | catalog-ingestion uses PostgreSQL advisory lock `740031001` and `(book_id, revision)` optimistic matching; inbound rating events use a `24h` Redis integration-event idempotency guard; Qdrant upserts are idempotent by book UUID. | Duplicate rating events within `24h` are ignored; concurrent book edits during an ingestion batch advance `revision` and are automatically picked up on the next run. | product-ingestion, adr-003-database-queue-for-vector-indexing, adr-006-reviews-rating-projection-on-book |
[[service|rating-api]] is the authoritative owner of individual [[entity|feedback]] records.
[[service|catalog-api]] maintains only derived `average_rating` and `total_reviews` columns on
[[entity|book]]. If [[event|FeedbackCreatedIntegrationEvent]] arrives for a nonexistent or
deleted book, [[service|catalog-api]] emits [[event|BookUpdatedRatingFailedIntegrationEvent]] so
[[service|rating-api]] can revert the orphaned feedback.
Because [[container|catalog-vector]] is a pure projection of [[container|catalog-database]], any
schema or embedding-model change can be recovered by re-enqueuing all active books into the
pending-update queue and letting [[service|catalog-ingestion]] overwrite Qdrant points
deterministically by UUID.
## Safe Change & Verification Checklist
- Keep searchable attributes synchronized between PostgreSQL pending-update triggers and [[service|catalog-ingestion]] embedding text generation, and plan a full vector re-index when indexed fields change.
- Invalidate `book:{id}`, `book:summary:{id}`, and affected `books:list` / `books:search` tags on every book mutation, and bump versioned cache key prefixes (`v1`) if cached DTO shapes change.
- Preserve `snake_case` naming for all [[container|catalog-database]] schema migrations and keep all Qdrant upserts idempotent by book UUID.
- Verify downstream gRPC compatibility with [[service|basket-api]], [[service|order-api]], and [[service|mcp-server]], and confirm Pact contract tests pass for all rating and scheduler events.
## Related Resources
- [[service|catalog-api]] — Authoritative catalog REST/gRPC API and rating projection consumer
- [[service|catalog-ingestion]] — Scheduled vector indexing worker
- [[flow|product-ingestion]] — End-to-end vector indexing and advisory-lock workflow
- [[adr|adr-001-postgresql-system-of-record]], [[adr|adr-002-hybrid-vector-search-qdrant]], [[adr|adr-003-database-queue-for-vector-indexing]], [[adr|adr-004-fusioncache-redis-for-catalog-reads]], [[adr|adr-006-reviews-rating-projection-on-book]]
- [[doc|platform/006-api-and-contracts]] — Consolidated HTTP, gRPC, and Kafka contracts
---
title: Change checklist
summary: Pre-merge engineering checklist for Catalog API, schema, caching, search, and integration contract changes.
version: 1.0.0
type: engineering
order: 2
badges:
- content: Architecture
backgroundColor: green
textColor: green
---
## Purpose & Scope
This checklist defines the mandatory verification steps for engineers modifying [[service|catalog-api]] or [[service|catalog-ingestion]] within the [[domain|catalog]] subdomain. Use it before merging changes to HTTP v1 endpoints, gRPC contracts, [[container|catalog-database]] schemas, [[container|catalog-cache]] keys, [[container|catalog-vector]] indexing, or Kafka integration events.
## Core Invariants & Design Rules
- **Backward-compatible contract evolution:** Keep REST (`/api/v1/{books,authors,categories,publishers}`), gRPC (`book.v1.BookGrpcService`), and CloudEvents schemas additive; version breaking changes explicitly under `ApiVersions` or a new protobuf package version.
- **Authorization & rate-limit boundaries:** Preserve Microsoft Entra ID policies (`catalog_read` default, `business_user` for catalog mutations, `admin` for dashboard and privileged routes) and endpoint rate-limiting middleware.
- **End-to-end traceability:** Keep book-identity, pricing, and availability mutations traceable by `BookId` in OpenTelemetry traces and structured logs.
- **No direct cross-domain writes:** Never allow external services to write to [[container|catalog-database]], and never bypass [[service|catalog-api]] when mutating catalog state.
:::note
Checked-in OpenAPI and SQL schema documentation assets in the catalog are not auto-regenerated by CI. Update them in the same pull request whenever HTTP contracts or [[container|catalog-database]] tables change.
:::
## Boundaries & Guarantees
| Concern | Strategy & Guarantee | Failure / Edge-Case Behavior | Related Resources |
| :-------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Persistence** | EF Core migrations for catalog-database must use `snake_case` identifiers and preserve database triggers feeding the pending vector-update queue. | Missing triggers or mismatched column names silently drop book edits from catalog-vector indexing. | catalog-database, book, author, category, publisher |
| **Caching** | Book mutations must invalidate `book:{id}`, `book:summary:{id}`, `books:list`, and `books:search` in catalog-cache; DTO shape changes require bumping the `v1` key version. | Failing to bump versioned keys causes deserialization errors or stale shapes across rolling deployments. | catalog-cache, adr-004-fusioncache-redis-for-catalog-reads |
| **Messaging** | Integration events (FeedbackCreatedIntegrationEvent, FeedbackDeletedIntegrationEvent, BookUpdatedRatingFailedIntegrationEvent, ProcessVectorBatchIntegrationEvent) must remain Pact-verified. | Breaking schema changes fail consumer-driven contract tests or route payloads to `bookworm.{env}.catalog.dead-letter-queue`. | `bookworm.{env}.rating.feedback-create`, `bookworm.{env}.rating.feedback-delete`, `bookworm.{env}.catalog.book-update-rating-failed`, scheduler.process-vector-batch |
| **Concurrency** | Preserve discount price bounds (`0 <= DiscountPrice <= OriginalPrice`), `DeleteBehavior.Restrict` on authors with books, and `24h` Redis idempotency on rating event handlers. | Removing idempotency guards allows duplicate Kafka deliveries to double-count `average_rating` and `total_reviews`. | catalog-api, catalog-ingestion, adr-006-reviews-rating-projection-on-book |
## Safe Change & Verification Checklist
Confirm additive compatibility across REST endpoints, `book.v1.BookGrpcService` (consumed by
[[service|basket-api]], [[service|order-api]], and [[service|mcp-server]]), and all Pact
contract suites with [[service|rating-api]] and [[service|scheduler-service]].
Ensure any [[container|catalog-database]] migration preserves `snake_case` naming, updates
pending-update triggers if searchable attributes changed, and plans a
[[container|catalog-vector]] rebuild when indexed text changes.
Confirm write paths invalidate affected [[container|catalog-cache]] keys/tags, DTO changes bump
key versions, and Entra ID policies (`catalog_read`, `business_user`, `admin`) remain enforced.
Execute `mise run format`, `mise run build`, and `mise run test` to verify Catalog unit tests,
architecture tests, and Pact contract tests pass with zero warnings.
## Related Resources
- [[service|catalog-api]] — Authoritative catalog REST/gRPC API
- [[service|catalog-ingestion]] — Scheduled vector indexing worker
- [[flow|product-ingestion]] — Vector indexing and advisory-lock pipeline
- [[query|GetBook]], [[query|GetBooksGrpc]], [[query|GetBookDetailsGrpc]], [[query|ListBooks]] — Key read and gRPC contracts
- [[doc|platform/006-api-and-contracts]] — Consolidated HTTP, gRPC, and Kafka contracts
---
title: Managing catalog data
summary: How catalog administrators and integrators create and maintain books, authors, categories, and publishers.
version: 1.0.0
type: guides
order: 1
badges:
- content: Guide
backgroundColor: teal
textColor: teal
---
**Audience & Outcome:** This guide is for catalog administrators and API integrators who create, update, or retire merchandising records. By following these rules, you will maintain valid taxonomy links, accurate promotional pricing, and reliable cover artwork across Storefront, [[service|basket-api]], and [[service|order-api]].
[[service|catalog-api]] is the authoritative owner of BookWorm's [[entity|book]], [[entity|author]], [[entity|category]], and [[entity|publisher]] records, pricing, and cover image references. Store administrators manage these records through Backoffice or authenticated REST calls requiring Microsoft Entra ID `business_user` or `admin` roles with `read` and `write` scopes.
## Context and motivation
Books depend on supporting taxonomy records (a category, a publisher, and one or more authors), carry promotional pricing rules, reference binary cover artwork in [[container|catalog-blob]], and display derived customer ratings from Reviews. Without strict domain invariants at the [[service|catalog-api]] boundary, invalid discounts, orphaned author attributions, expired image links, or manual rating overrides would corrupt merchandising data across customer experiences.
## How it works
Every catalog write enters [[service|catalog-api]], validates domain invariants before committing to [[container|catalog-database]], and triggers downstream cache invalidation in [[container|catalog-cache]] and background vector indexing in [[container|catalog-vector]].
This visual shows the relationships between Catalog's core records, cover artwork storage, and external Reviews and Ordering boundaries.
### Entity creation order
Because a [[entity|book]] references supporting taxonomy records, create entities in dependency order:
Create [[entity|publisher]] and [[entity|category]] records first. Names must be unique within [[container|catalog-database]].
Create [[entity|author]] records independently before linking them to books.
Submit the book with its category, publisher, and author IDs via multipart form data (`POST /catalog/api/v1/books`). Direct reads reflect the saved book immediately, while free-text search becomes discoverable after the next scheduled [[service|catalog-ingestion]] batch runs.
### Domain invariants
:::warning
Never attempt to bypass [[service|catalog-api]] or manually edit `average_rating` and `total_reviews` in [[container|catalog-database]]. Rating summaries are read-only projections updated asynchronously from [[service|rating-api]].
:::
| Rule | Behavior | Downstream Impact |
| :-------------------------------- | :------------------------------------------------------------------------- | :------------------------------------------------------------------------------ |
| **Discount bounds** | Discount price must be between `0` and the original price | Prevents negative or inflated promotional pricing at checkout |
| **Category / publisher deletion** | Preserves associated books and clears their foreign-key reference | Keeps catalog titles intact during taxonomy reorganization |
| **Author deletion protection** | Blocked while any [[entity\|book]] still references the [[entity\|author]] | Prevents orphaned author attributions; unlink or retire books first |
| **Book soft deletion** | Marks the book deleted, hides it from listings, and queues vector removal | Preserves historical [[entity\|order]] references while removing search results |
| **Read-only rating summaries** | Updated only via integration events from [[service\|rating-api]] | Keeps Reviews authoritative and prevents manual score tampering |
### Cover artwork and post-change propagation
- **Multipart uploads and short-lived SAS URLs:** Upload cover artwork (`image/jpeg`, `image/png`, or `image/webp`) with the book create or update request. [[service|catalog-api]] stores only an internal URN in [[container|catalog-database]] and generates read-only, time-limited SAS URLs (1-hour default) on read. Clients must never persist temporary SAS URLs as permanent image identifiers.
- **Immediate direct reads vs. eventual search:** Book writes invalidate [[container|catalog-cache]] entries so direct lookups return current values immediately, while database triggers enqueue updates for asynchronous [[container|catalog-vector]] indexing via [[flow|product-ingestion]].
- **Immutable accepted orders:** [[service|basket-api]] and [[service|order-api]] re-validate current prices over gRPC at checkout. Editing a book's price in Catalog never retroactively alters an already accepted [[entity|order]].
| Decision | Benefits | Costs and limits |
| :-------------------------------------------------------------- | :--------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------- |
| **Restrict author deletion; allow category/publisher deletion** | Protects author attribution integrity while keeping taxonomy reorganization low-friction | Removing an author requires unlinking or retiring their books first |
| **Soft-delete books** | Preserves historical book identity and order-audit traceability | Deleted rows remain in [[container\|catalog-database]] and require filtering in queries |
| **Store internal URN and sign short-lived SAS URLs on read** | Prevents public blob scraping and decouples clients from storage internals | Clients caching payloads beyond the SAS expiry encounter HTTP `403` until re-fetch |
| **Read-only rating summary updated asynchronously** | Keeps Reviews authoritative and prevents manual tampering | Rating changes appear in Catalog after brief Kafka propagation lag |
**Rejected alternatives:**
- **Hard-deleting books:** Breaks historical references in accepted orders and complicates vector cleanup.
- **Public anonymous blob URLs:** Exposes storage containers to unauthenticated scraping instead of Managed Identity delegation keys.
- **Direct rating edits in Catalog:** Violates Reviews ownership of individual [[entity|feedback]] records.
## Related documentation
- [[flow|product-ingestion]] — How [[service|scheduler-service]] and [[service|catalog-ingestion]] synchronize [[container|catalog-vector]].
- [[adr|adr-001-postgresql-system-of-record]] — Why [[container|catalog-database]] is the single authoritative store for Catalog.
- [[adr|adr-005-blob-storage-for-book-images]] — Why cover artwork uses internal URNs and short-lived SAS URLs.
---
title: Search and discovery
summary: How book search works, what consistency to expect, and how to use filters.
version: 1.0.0
type: guides
order: 2
badges:
- content: Guide
backgroundColor: teal
textColor: teal
---
**Audience & Outcome:** This guide is for frontend developers, AI agent builders, and operators integrating with BookWorm's catalog discovery endpoints. You will learn how structured browsing and free-text search execute, what consistency guarantees apply, and how to isolate search symptoms.
[[service|catalog-api]] serves book discovery through two complementary query paths: structured browsing against [[container|catalog-database]] and free-text discovery combining [[container|catalog-vector]] candidate retrieval with authoritative PostgreSQL hydration. Both Storefront and [[service|mcp-server]] share this architecture so displayed prices, availability, and cover links always come from the primary database.
## Context and motivation
Customers discover books in two distinct ways: navigating structured facets (categories, authors, publishers, price ranges, sorting) and entering natural-language search queries. Relational SQL filtering handles exact facets well but misses semantic intent, while serving prices directly from a search index risks exposing stale commercial data during price updates or book retirements.
BookWorm combines relational accuracy with vector recall by treating [[container|catalog-vector]] as a **candidate-ranking projection** and [[container|catalog-database]] as the **authoritative hydration source**.
## How it works
Every discovery request enters [[service|catalog-api]] (via REST for Storefront or internal gRPC from [[service|mcp-server]] for conversational AI) and branches based on whether a free-text search term is present.
This visual shows how structured browsing queries the primary database directly while free-text search embeds the query, ranks candidates in the vector store, and hydrates authoritative rows from PostgreSQL.
### Query paths
| Discovery mode | Entry condition | Execution path | Authoritative data source |
| :-------------------------- | :-------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------- |
| **Structured browse** | Category, publisher, author, price bounds, sort, or page parameters with no search term | Queries [[container\|catalog-database]] directly and caches pages in [[container\|catalog-cache]] | [[container\|catalog-database]] |
| **Free-text hybrid search** | Search term provided (with optional facets and paging) | Embeds query via Microsoft Foundry, runs hybrid vector + keyword search in [[container\|catalog-vector]] for candidate book IDs, hydrates rows from [[container\|catalog-database]], applies filters/paging, and caches results | [[container\|catalog-vector]] candidates hydrated from [[container\|catalog-database]] |
### Consistency expectations
:::note
New or edited books appear in direct lookups and structured browse immediately, but appear in free-text search only after [[service|catalog-ingestion]] processes the pending queue (triggered every 5 minutes by [[service|scheduler-service]]).
:::
- **Authoritative commercial details:** Prices, discount prices, availability, rating summaries, and freshly signed cover SAS URLs always come from [[container|catalog-database]] and [[container|catalog-blob]], never from vector index payloads.
- **Brief deletion transition window:** When a [[entity|book]] is soft-deleted, [[container|catalog-vector]] may still return its ID as a candidate until the next [[service|catalog-ingestion]] batch removes the vector. Hydration against [[container|catalog-database]] filters out soft-deleted books so retired titles never appear in returned results.
### Separating discovery symptoms
Because discovery touches [[container|catalog-vector]], [[container|catalog-cache]], and expiring [[container|catalog-blob]] SAS URLs, isolate symptoms before escalating:
- **New or edited book missing from text search only:** Indicates ingestion lag — follow the Vector Index Lag runbook.
- **Old price or metadata shown after an update:** Indicates stale cache — follow the Stale Cache or Redis Outage runbook.
- **Book cover image returns HTTP `403` or `404`:** Indicates an expired SAS URL or missing blob — follow the Broken Book Images runbook.
| Decision | Benefits | Costs and limits |
| :------------------------------------------------- | :---------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------- |
| **Vector candidate lookup + PostgreSQL hydration** | Guarantees authoritative prices, soft-delete filtering, and live SAS URLs on every search response | Adds a relational lookup step after vector retrieval |
| **Asynchronous background vector indexing** | Keeps catalog writes fast and shields [[service\|catalog-api]] from embedding or vector store outages | Creates a brief lag window before new or edited books appear in free-text search |
| **Hashed cache keys for list and search pages** | Reduces repeated embedding and database load on popular queries | Cached pages can reflect brief staleness until tag invalidation or TTL expiry (30m) |
**Rejected alternatives:**
- **PostgreSQL full-text search alone:** Struggles with semantic and conversational discovery queries from Storefront and [[service|chat-api]].
- **Serving book prices directly from vector payloads:** Risks displaying outdated prices or retired books due to eventual consistency.
## Related documentation
- [[flow|product-ingestion]] — How [[service|scheduler-service]], Kafka, and [[service|catalog-ingestion]] keep [[container|catalog-vector]] synchronized.
- [[flow|agent-orchestration]] — How [[service|chat-api]] queries Catalog discovery through [[service|mcp-server]].
- [[adr|adr-002-hybrid-vector-search-qdrant]] — Architectural decision for hybrid vector and keyword search.
---
title: Vector index lag
summary: Diagnose and recover when new or edited books do not appear in text search.
version: 1.0.0
type: runbooks
order: 1
badges:
- content: Runbook
backgroundColor: orange
textColor: orange
---
## Trigger / Symptom & Blast Radius
Newly created, edited, or deleted books appear in direct lookups and structured browse, but are missing or outdated in free-text search. [[service|catalog-ingestion]] is an internal background worker triggered every 5 minutes by [[service|scheduler-service]] over [[channel|scheduler.process-vector-batch]] to sync up to 200 queued rows per batch from [[container|catalog-database]] into [[container|catalog-vector]]. Blast radius is limited to free-text search discovery; checkout and authoritative catalog browsing remain unaffected.
Run a full index rebuild only after confirmed vector store data loss or an indexed-field schema
change. Never manually delete pending queue rows from [[container|catalog-database]] to hide a
backlog.
## Pre-Flight Check
Verify [[service|catalog-ingestion]] container health and check pending queue depth in [[container|catalog-database]]:
```bash
az containerapp show --name --resource-group --query "properties.runningStatus" -o tsv
```
```sql
SELECT count(*) AS pending_books, min(updated_at) AS oldest_pending_update, clock_timestamp() - min(updated_at) AS oldest_pending_age
FROM pending_vector_updates;
```
## Quick Recovery Procedure
Open Quartz Dashboard at `/quartz` (requires `admin` role) and confirm the 5-minute vector batch job is firing without errors, then inspect consumer lag on [[channel|scheduler.process-vector-batch]]:
```bash
az containerapp logs show --name --resource-group --tail 100
```
If running locally in Aspire, ensure the [[service|scheduler-service]] resource is started manually in the Aspire Dashboard.
If [[service|catalog-ingestion]] logs show skipped runs (`0` processed items), check whether an orphaned session holds the ingestion advisory lock (`740031001`) in [[container|catalog-database]]:
```sql
SELECT l.pid, a.usename, a.application_name, a.state, a.query_start
FROM pg_locks l
JOIN pg_stat_activity a ON a.pid = l.pid
WHERE l.locktype = 'advisory' AND l.objid = 740031001;
```
Terminate only a verified dead or hung session:
```sql
SELECT pg_terminate_backend();
```
Check [[service|catalog-ingestion]] logs for Microsoft Foundry embedding errors or [[container|catalog-vector]] connection timeouts. Unacknowledged rows remain safely queued in [[container|catalog-database]] and retry automatically on the next 5-minute cycle.
Once dependencies are healthy, trigger the vector batch job in Quartz Dashboard to drain a large backlog faster. Only if [[container|catalog-vector]] suffered data loss, re-enqueue all books:
```sql
INSERT INTO pending_vector_updates (book_id)
SELECT id FROM books
ON CONFLICT (book_id) DO UPDATE SET revision = gen_random_uuid(), updated_at = clock_timestamp();
```
## Verification
Re-run the pending queue query in [[container|catalog-database]] and confirm `pending_books` trends to `0`:
```sql
SELECT count(*) AS pending_books FROM pending_vector_updates;
```
Expected output:
```text
pending_books
---------------
0
```
## Rollback / Escalation
- **Rollback:** If a full rebuild saturates embedding quotas, pause the trigger in Quartz Dashboard (`/quartz`) until quota recovers, then resume.
- **Escalation:** Escalate persistent embedding, vector store, or ingestion failures to [[team|platform-engineering-team]] or [[team|catalog-experience-team]] with queue age and sanitized logs.
| Symptom | Cause | Fix |
| :----------------------------------------- | :--------------------------------------------------------------- | :----------------------------------------------------------- |
| `pending_books` is `0` but search is stale | Search result is cached in [[container\|catalog-cache]] | Wait for cache expiry or follow the stale cache runbook |
| Jobs never fire locally | [[service\|scheduler-service]] requires explicit start in Aspire | Start [[service\|scheduler-service]] in the Aspire Dashboard |
| Batch aborts with incomplete embeddings | Microsoft Foundry rate limit or auth failure | Verify Managed Identity RBAC and Foundry quota |
## Related documentation
- [[flow|product-ingestion]] — End-to-end vector indexing pipeline.
- [[adr|adr-003-database-queue-for-vector-indexing]] — Why Catalog uses a transactional database queue.
---
title: Stale cache or Redis outage
summary: Handle stale book data and Redis unavailability affecting Catalog reads.
version: 1.0.0
type: runbooks
order: 2
badges:
- content: Runbook
backgroundColor: orange
textColor: orange
---
## Trigger / Symptom & Blast Radius
[[service|catalog-api]] returns outdated book details after a database update, Backoffice dashboard totals lag, or Redis connectivity errors increase read latency. [[container|catalog-cache]] is disposable—[[container|catalog-database]] is always the source of truth—and [[service|catalog-api]] falls back to PostgreSQL or its 2-hour fail-safe during Redis outages.
Never run `FLUSHDB` or `FLUSHALL` on BookWorm's shared Redis instance. The same Redis cluster
stores customer baskets ([[container|basket-database]]), distributed locks
([[container|order-cache]]), and 24-hour idempotency keys across services.
## Pre-Flight Check
Confirm Redis responsiveness and check the authoritative record in [[container|catalog-database]]:
```bash
redis-cli -u "" PING
```
```sql
SELECT id, name, price_original_price, price_discount_price, average_rating, total_reviews, is_deleted
FROM books
WHERE id = '';
```
## Quick Recovery Procedure
Fetch the book through the API Gateway and compare it to the SQL result:
```bash
curl -sS "https:///catalog/api/v1/books/"
```
If they match, the cache is not stale.
For a single stale book, delete only its detail and summary keys (never flush the database):
```bash
redis-cli -u "" UNLINK "book:" "book:summary:"
```
For wide Catalog staleness after a bulk change or schema update, evict only Catalog-prefixed keys using non-blocking `SCAN` + `UNLINK`:
```bash
redis-cli -u "" --scan --pattern "catalog:*" | xargs -r redis-cli -u "" UNLINK
redis-cli -u "" --scan --pattern "book:*" | xargs -r redis-cli -u "" UNLINK
```
During a Redis outage, [[service|catalog-api]] automatically falls back to [[container|catalog-database]]. Monitor PostgreSQL CPU and connection saturation, restore Azure Managed Redis connectivity, and scale [[service|catalog-api]] or enforce rate limits if database load spikes.
## Verification
Re-fetch the book through the API Gateway and confirm it returns the authoritative PostgreSQL values:
```bash
curl -sS "https:///catalog/api/v1/books/"
```
Expected output:
```json
{
"id": "",
"name": "",
"price": 29.99
}
```
## Rollback / Escalation
- **Rollback:** Cache eviction is safe and self-healing; entries repopulate automatically on next read.
- **Escalation:** Escalate persistent Redis connectivity or backplane invalidation failures to [[team|platform-engineering-team]].
| Symptom | Cause | Fix |
| :------------------------------------------- | :-------------------------------------------------- | :---------------------------------------------------------------------------------- |
| Single book still stale after Redis `UNLINK` | Replica serving in-process L1 memory cache | Trigger a no-op update via [[service\|catalog-api]] or restart the affected replica |
| Dashboard totals lag by a few seconds | Dashboard cache uses a 15-second TTL | Wait 15 seconds and re-fetch; no manual eviction needed |
| Rising [[container\|catalog-database]] CPU | Redis unreachable; reads falling back to PostgreSQL | Restore Azure Managed Redis connectivity and monitor DB connections |
## Related documentation
- [[adr|adr-004-fusioncache-redis-for-catalog-reads]] — Cache architecture and fail-safe design.
- [[adr|adr-001-postgresql-system-of-record]] — Authoritative role of [[container|catalog-database]].
---
title: Missing or broken book images
summary: Resolve book images that fail to load or whose blob is missing.
version: 1.0.0
type: runbooks
order: 3
badges:
- content: Runbook
backgroundColor: orange
textColor: orange
---
## Trigger / Symptom & Blast Radius
A book cover image returns HTTP `403` or `404` in Storefront or Backoffice, or [[service|catalog-api]] logs URN resolution errors. [[service|catalog-api]] stores an internal URN in [[container|catalog-database]] and signs short-lived, read-only SAS URLs (1-hour default) for [[container|catalog-blob]]. Blast radius is limited to cover image rendering; catalog metadata and checkout remain unaffected.
Do not hand-edit the `image` column in [[container|catalog-database]] unless executing an approved
migration remediation. Manual edits bypass URN validation and can orphan blobs in
[[container|catalog-blob]].
## Pre-Flight Check
Fetch a fresh book payload to rule out a client-cached expired SAS URL, and inspect the stored URN in [[container|catalog-database]]:
```bash
IMAGE_URL=$(curl -sS "https:///catalog/api/v1/books/" | jq -r '.imageUrl')
curl -I "$IMAGE_URL"
```
```sql
SELECT id, name, image, is_deleted FROM books WHERE id = '';
```
## Quick Recovery Procedure
Extract `` (the fourth colon-delimited segment of the stored URN) and check [[container|catalog-blob]]:
```bash
az storage blob exists \
--account-name \
--container-name catalog-blob \
--name \
--auth-mode login
```
If a freshly generated SAS URL returns `403`, confirm the [[service|catalog-api]] Managed Identity holds `Storage Blob Data Contributor` and `Storage Blob Delegator` roles on ``.
**Backup available:** Restore the blob to the exact same ``, `catalog-blob` container, and `` so the existing URN works without database changes.
**Blob unrecoverable:** Upload a replacement cover (`image/jpeg`, `image/png`, or `image/webp`) through Backoffice or `PUT /catalog/api/v1/books` so [[service|catalog-api]] writes a new blob and updates the URN atomically.
## Verification
Re-fetch the book through the API Gateway and confirm the signed SAS URL returns HTTP `200 OK`:
```bash
IMAGE_URL=$(curl -sS "https:///catalog/api/v1/books/" | jq -r '.imageUrl')
curl -I "$IMAGE_URL"
```
Expected output:
```text
HTTP/2 200
content-type: image/webp
```
## Rollback / Escalation
- **Rollback:** Re-uploading through [[service|catalog-api]] is atomic; retain the previous image file if reverting a cover change.
- **Escalation:** Escalate storage RBAC or cross-environment URN mismatch issues to [[team|platform-engineering-team]].
| Symptom | Cause | Fix |
| :---------------------------------------------- | :----------------------------------------------------------- | :------------------------------------------------------------------ |
| Image URL returns `403` after 1 hour | Client cached a short-lived SAS URL past expiry | Re-fetch the book from [[service\|catalog-api]]; fix client caching |
| `403` immediately after generation | Managed Identity lacks User Delegation Key RBAC | Grant `Storage Blob Delegator` and `Storage Blob Data Contributor` |
| `UrnException` in [[service\|catalog-api]] logs | Database restored from another environment's storage account | Align blobs and update URNs via approved remediation |
## Related documentation
- [[adr|adr-005-blob-storage-for-book-images]] — URN storage model and short-lived SAS design.
---
title: Rating summary mismatch
summary: Investigate when a book's average rating or review count disagrees with Reviews.
version: 1.0.0
type: runbooks
order: 4
badges:
- content: Runbook
backgroundColor: orange
textColor: orange
---
## Trigger / Symptom & Blast Radius
A book's `average_rating` or `total_reviews` in [[service|catalog-api]] disagrees with [[service|rating-api]], or [[event|BookUpdatedRatingFailedIntegrationEvent]] appears on `bookworm.{env}.catalog.book-update-rating-failed`. [[service|rating-api]] owns authoritative [[entity|feedback]] documents in [[container|rating-database]], while [[service|catalog-api]] maintains only a derived summary in [[container|catalog-database]].
Never invent or hand-edit `average_rating` or `total_reviews` in [[container|catalog-database]]
without deriving the exact aggregate from [[container|rating-database]]. Replaying already-applied
rating events after the 24-hour idempotency window expires will double-count ratings.
## Pre-Flight Check
Compare Catalog's derived summary in [[container|catalog-database]] against the authoritative aggregate in [[container|rating-database]] (`ratingdb` / `feedbacks`):
```sql
SELECT id, name, average_rating, total_reviews, is_deleted FROM books WHERE id = '';
```
```sql
SELECT COUNT(1) AS total_reviews, AVG(c.rating) AS average_rating FROM c WHERE c.bookId = '';
```
## Quick Recovery Procedure
Inspect `bookworm.{env}.catalog.book-update-rating-failed` for [[event|BookUpdatedRatingFailedIntegrationEvent]]. If present, [[service|catalog-api]] could not find `` and emitted the compensation event so [[service|rating-api]] deletes the orphaned feedback document.
Check consumer lag and [[service|catalog-api]] logs across `bookworm.{env}.rating.feedback-create`, `bookworm.{env}.rating.feedback-delete`, and `bookworm.{env}.catalog.dead-letter-queue`:
```bash
az containerapp logs show --name --resource-group --tail 150
```
**Unprocessed DLQ messages:** Fix the underlying database or handler fault first, then replay only unapplied messages from `bookworm.{env}.catalog.dead-letter-queue`.
**Confirmed multi-event delta drift:** Execute an approved reconciliation setting `average_rating` and `total_reviews` directly from the authoritative [[container|rating-database]] aggregate, then evict `book:` from [[container|catalog-cache]].
## Verification
Query [[service|catalog-api]] and confirm `averageRating` and `totalReviews` match [[container|rating-database]]:
```bash
curl -sS "https:///catalog/api/v1/books/" | jq '{id, averageRating, totalReviews}'
```
Expected output:
```json
{
"id": "",
"averageRating": 4.5,
"totalReviews": 12
}
```
## Rollback / Escalation
- **Rollback:** Re-run the authoritative reconciliation query from [[container|rating-database]] and evict `book:` in [[container|catalog-cache]] if a manual correction used wrong values.
- **Escalation:** Escalate persistent projection or compensation failures to [[team|catalog-experience-team]] with `` and event IDs.
| Symptom | Cause | Fix |
| :------------------------------------------------------------------------- | :-------------------------------------------------------- | :---------------------------------------------------------------------------------- |
| [[container\|catalog-database]] matches Cosmos DB, API returns old numbers | Stale entry in [[container\|catalog-cache]] | Evict `book:` using the stale cache runbook |
| `total_reviews` higher than Cosmos DB count | Duplicate event replayed after 24-hour idempotency expiry | Reconcile directly from [[container\|rating-database]] and evict cache |
| Messages accumulating in Catalog DLQ | Transient DB or handler error exhausted retries | Fix dependency in [[service\|catalog-api]] logs, then replay unapplied DLQ messages |
## Related documentation
- [[flow|feedback-publication]] — End-to-end review projection and compensation flow.
- [[adr|adr-006-reviews-rating-projection-on-book]] — Derived rating summary boundary.
---
title: Engineering Invariants and Quirks
summary: Hybrid cache invalidation, rating projection concurrency, image pre-processing, and known validation quirks for Catalog API.
version: 1.0.0
---
Engineering invariants and known contract quirks for [[service|catalog-api]].
## Caching, Persistence & Projection Invariants
- **Hybrid cache invalidation:** Read queries use FusionCache backed by Redis (`catalog-cache`). Catalog mutations and rating projection updates invalidate tagged entries across instances via the Redis backplane.
- **Derived rating projection:** [[service|catalog-api]] consumes [[event|FeedbackCreatedIntegrationEvent]] and [[event|FeedbackDeletedIntegrationEvent]] to recalculate book average ratings and review counts. If the target book does not exist, it publishes [[event|BookUpdatedRatingFailedIntegrationEvent]] so [[service|rating-api]] compensates.
- **Vector index handoff:** Book writes mark rows pending for asynchronous embedding by [[service|catalog-ingestion]] rather than calling Qdrant synchronously on the write path.
## Known Contract & Runtime Quirks
:::warning
The following contract and validation mismatches are tracked in [[doc|arc42/11-risks-and-technical-debt]].
:::
| Area | Command / Operation | Observed Behavior |
| :------------------------ | :--------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Image pre-processor** | [[command\|CreateBook]] | The image upload pre-processor expects a different multipart/form field shape than the endpoint validator under certain client payloads, causing validation mismatches. |
| **Publisher name length** | [[command\|CreatePublisher]], [[command\|UpdatePublisher]] | `CreatePublisher` and `UpdatePublisher` enforce inconsistent maximum name lengths, allowing names accepted on creation to be rejected on update (or vice versa). |
| **`404` content-type** | Resource-not-found responses | OpenAPI metadata declares `application/problem+json`, while runtime `404 Not Found` responses return `application/json`. |
---
title: Apply feedback-created integration event
summary: Catalog handler for the shared feedback-created integration event.
version: 1.0.0
type: contracts
badges:
- content: Architecture
backgroundColor: green
textColor: green
---
This reference defines the `FeedbackCreatedIntegrationEvent` Kafka integration contract consumed by **Catalog API** (`BookWorm.Catalog`) to update a book's derived `average_rating` and `total_reviews` projection in PostgreSQL (`catalogdb`) when **Rating API** (`BookWorm.Rating`) persists a new `Feedback` document in Azure Cosmos DB (`ratingdb`/`feedbacks`).
## Overview
| Property | Value |
| :-------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Owner (producer)** | Reviews bounded context — **Rating API** (`src/Services/Rating/BookWorm.Rating`) |
| **Consumer** | Catalog bounded context — **Catalog API** (`src/Services/Catalog/BookWorm.Catalog`) |
| **Source** | `src/Services/Catalog/BookWorm.Catalog/IntegrationEvents/Events/FeedbackCreatedIntegrationEvent.cs`, `EventHandlers/FeedbackCreatedIntegrationEventHandler.cs` |
| **Kafka topic** | `bookworm.{env}.rating.feedback-create` (`AppendPrefix = true`) |
| **Message identity** | `BookWorm.Contracts.FeedbackCreatedIntegrationEvent` |
| **Protocol / format** | Kafka + CloudEvents JSON (`CloudEventsOnlyKafkaMapper`), partitioned by `BookId` / `FeedbackId` |
| **Idempotency** | Redis-backed `IIntegrationEventIdempotencyGuard` (24-hour TTL keyed by `Id` + `FeedbackCreatedIntegrationEventHandler`) |
| **Contract tests** | Pact messaging tests in `BookWorm.Catalog.ContractTests` and `tests/pacts/` (`Catalog-Rating`, `Rating-Catalog`) |
## Parameters and fields
| Name | Type | Required | Default | Constraints | Description |
| :----------- | :----- | :------- | :-------- | :------------------------------------ | :----------------------------------------------------------------------------------------------------------------------- |
| `Id` | `Guid` | Yes | Generated | Inherited from `IntegrationEvent` | Unique event identifier used as the Redis idempotency key |
| `BookId` | `Guid` | Yes | — | Non-empty UUID | Target Catalog book identifier to update |
| `Rating` | `int` | Yes | — | Validated by **Rating API** (`1`-`5`) | Star rating added to the book's running summary via `Book.AddRating` |
| `FeedbackId` | `Guid` | Yes | — | Non-empty UUID | Authoritative Cosmos DB feedback identifier returned in `BookUpdatedRatingFailedIntegrationEvent` if the book is missing |
## Processing and error behavior
| Condition | Handler behavior | Recovery / downstream effect |
| :--------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- |
| **Book exists in `catalogdb`** | Calls `book.AddRating(@event.Rating)` (`((AverageRating * TotalReviews) + rating) / (TotalReviews + 1)`, `TotalReviews++`) and saves via `UnitOfWork.SaveEntitiesAsync`; returns `null` | Commits updated summary and invalidates cached book entry |
| **Book missing (`book is null`)** | Calls `UnitOfWork.SaveEntitiesAsync` and returns `BookUpdatedRatingFailedIntegrationEvent(@event.FeedbackId)` as a Wolverine cascading message | Publishes compensation event to `bookworm.{env}.catalog.book-update-rating-failed` so **Rating API** deletes the orphaned Cosmos DB feedback |
| **Duplicate event within 24 hours** | `IIntegrationEventIdempotencyGuard` skips re-execution for the same `@event.Id` | Prevents double-counting `TotalReviews` on Kafka redelivery |
| **Transient DB or infrastructure error** | Exception propagates to Wolverine | Wolverine retries (`50ms / 250ms / 1s` with full jitter), then routes to `bookworm.{env}.catalog.dead-letter-queue` |
## Examples
### Contract record (`FeedbackCreatedIntegrationEvent.cs`)
```csharp
using BookWorm.Constants.Aspire;
using Wolverine.Attributes;
namespace BookWorm.Contracts;
[IntegrationMessageOwner(ServiceName = Services.Rating, TopicName = "feedback-create")]
[MessageIdentity("BookWorm.Contracts.FeedbackCreatedIntegrationEvent")]
public sealed record FeedbackCreatedIntegrationEvent(Guid BookId, int Rating, Guid FeedbackId)
: IntegrationEvent;
```
### Catalog consumer handler (`FeedbackCreatedIntegrationEventHandler.cs`)
```csharp
using BookWorm.Chassis.EventBus.Idempotency;
using BookWorm.Contracts;
using Wolverine.Attributes;
namespace BookWorm.Catalog.IntegrationEvents.EventHandlers;
internal sealed class FeedbackCreatedIntegrationEventHandler(
IBookRepository repository,
IIntegrationEventIdempotencyGuard? idempotencyGuard = null
)
{
[WolverineHandler]
public async Task Handle(
FeedbackCreatedIntegrationEvent @event,
CancellationToken cancellationToken
)
{
return await idempotencyGuard.ExecuteAsync(
@event.Id,
nameof(FeedbackCreatedIntegrationEventHandler),
async ct =>
{
var book = await repository.GetByIdAsync(@event.BookId, ct);
if (book is null)
{
await repository.UnitOfWork.SaveEntitiesAsync(ct);
return new BookUpdatedRatingFailedIntegrationEvent(@event.FeedbackId);
}
book.AddRating(@event.Rating);
await repository.UnitOfWork.SaveEntitiesAsync(ct);
return null;
},
cancellationToken: cancellationToken
);
}
}
```
### Example JSON payload
```json
{
"id": "0193f1a2-7b4c-7d8e-9f01-23456789abcd",
"bookId": "0193f1a2-1111-7d8e-9f01-234567890001",
"rating": 5,
"feedbackId": "0193f1a2-2222-7d8e-9f01-234567890002"
}
```
## Related documentation
- Catalog feedback-deleted contract reference — Companion contract for removed feedback.
- [[flow|feedback-publication]] — End-to-end Reviews-to-Catalog projection and compensation design.
- How to resolve a Catalog rating summary mismatch — Operational runbook for rating drift and DLQ handling.
---
title: Apply feedback-deleted integration event
summary: Catalog handler for the shared feedback-deleted integration event.
version: 1.0.0
type: contracts
badges:
- content: Architecture
backgroundColor: green
textColor: green
---
This reference defines the `FeedbackDeletedIntegrationEvent` Kafka integration contract consumed by **Catalog API** (`BookWorm.Catalog`) to remove a deleted review's score from a book's derived `average_rating` and `total_reviews` projection in PostgreSQL (`catalogdb`) when **Rating API** (`BookWorm.Rating`) deletes a `Feedback` document from Azure Cosmos DB (`ratingdb`/`feedbacks`).
## Overview
| Property | Value |
| :-------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Owner (producer)** | Reviews bounded context — **Rating API** (`src/Services/Rating/BookWorm.Rating`) |
| **Consumer** | Catalog bounded context — **Catalog API** (`src/Services/Catalog/BookWorm.Catalog`) |
| **Source** | `src/Services/Catalog/BookWorm.Catalog/IntegrationEvents/Events/FeedbackDeletedIntegrationEvent.cs`, `EventHandlers/FeedbackDeletedIntegrationEventHandler.cs` |
| **Kafka topic** | `bookworm.{env}.rating.feedback-delete` (`AppendPrefix = true`) |
| **Message identity** | `BookWorm.Contracts.FeedbackDeletedIntegrationEvent` |
| **Protocol / format** | Kafka + CloudEvents JSON (`CloudEventsOnlyKafkaMapper`), partitioned by `BookId` / `FeedbackId` |
| **Idempotency** | Redis-backed `IIntegrationEventIdempotencyGuard` (24-hour TTL keyed by `Id` + `FeedbackDeletedIntegrationEventHandler`) |
| **Contract tests** | Pact messaging tests in `BookWorm.Catalog.ContractTests` and `tests/pacts/` (`Catalog-Rating`, `Rating-Catalog`) |
## Parameters and fields
| Name | Type | Required | Default | Constraints | Description |
| :----------- | :----- | :------- | :-------- | :-------------------------------- | :--------------------------------------------------------------------------- |
| `Id` | `Guid` | Yes | Generated | Inherited from `IntegrationEvent` | Unique event identifier used as the Redis idempotency key |
| `BookId` | `Guid` | Yes | — | Non-empty UUID | Target Catalog book identifier to adjust |
| `Rating` | `int` | Yes | — | `1`-`5` | Original star rating of the deleted feedback removed via `Book.RemoveRating` |
| `FeedbackId` | `Guid` | Yes | — | Non-empty UUID | Identifier of the deleted Cosmos DB feedback record for traceability |
## Processing and error behavior
| Condition | Handler behavior | Recovery / downstream effect |
| :--------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------ |
| **Book exists (`TotalReviews > 1`)** | Calls `book.RemoveRating(@event.Rating)` (`((AverageRating * TotalReviews) - rating) / (TotalReviews - 1)`, `TotalReviews--`) and commits via `UnitOfWork.SaveEntitiesAsync` | Updates `catalogdb` summary and invalidates cached book entry |
| **Book exists (`TotalReviews <= 1`)** | `book.RemoveRating` resets `AverageRating = 0` and `TotalReviews = 0` and commits | Prevents divide-by-zero or negative review counts |
| **Book missing (`book is null`)** | Returns without writing or publishing any compensation event | Safe no-op; no local rating projection exists to adjust |
| **Duplicate event within 24 hours** | `IIntegrationEventIdempotencyGuard` skips re-execution for the same `@event.Id` | Prevents double-decrementing `TotalReviews` on Kafka redelivery |
| **Transient DB or infrastructure error** | Exception propagates to Wolverine | Wolverine retries (`50ms / 250ms / 1s` with full jitter), then routes to `bookworm.{env}.catalog.dead-letter-queue` |
## Examples
### Contract record (`FeedbackDeletedIntegrationEvent.cs`)
```csharp
using BookWorm.Constants.Aspire;
using Wolverine.Attributes;
namespace BookWorm.Contracts;
[IntegrationMessageOwner(ServiceName = Services.Rating, TopicName = "feedback-delete")]
[MessageIdentity("BookWorm.Contracts.FeedbackDeletedIntegrationEvent")]
public sealed record FeedbackDeletedIntegrationEvent(Guid BookId, int Rating, Guid FeedbackId)
: IntegrationEvent;
```
### Catalog consumer handler (`FeedbackDeletedIntegrationEventHandler.cs`)
```csharp
using BookWorm.Chassis.EventBus.Idempotency;
using BookWorm.Contracts;
using Wolverine.Attributes;
namespace BookWorm.Catalog.IntegrationEvents.EventHandlers;
internal sealed class FeedbackDeletedIntegrationEventHandler(
IBookRepository repository,
IIntegrationEventIdempotencyGuard? idempotencyGuard = null
)
{
[WolverineHandler]
public async Task Handle(
FeedbackDeletedIntegrationEvent @event,
CancellationToken cancellationToken
)
{
await idempotencyGuard.ExecuteAsync(
@event.Id,
nameof(FeedbackDeletedIntegrationEventHandler),
async ct =>
{
var book = await repository.GetByIdAsync(@event.BookId, ct);
if (book is null)
{
return;
}
book.RemoveRating(@event.Rating);
await repository.UnitOfWork.SaveEntitiesAsync(ct);
},
cancellationToken: cancellationToken
);
}
}
```
### Example JSON payload
```json
{
"id": "0193f1a2-7b4c-7d8e-9f01-23456789abce",
"bookId": "0193f1a2-1111-7d8e-9f01-234567890001",
"rating": 4,
"feedbackId": "0193f1a2-2222-7d8e-9f01-234567890002"
}
```
## Related documentation
- Catalog feedback-created contract reference — Companion contract for new feedback and missing-book compensation.
- [[flow|feedback-publication]] — End-to-end Reviews-to-Catalog projection design.
- How to resolve a Catalog rating summary mismatch — Operational runbook for rating drift and Cosmos DB reconciliation.
---
title: Catalog DLQ Inspection and Replay
summary: CLI-first procedure to inspect and safely replay failed rating projection events from the Catalog dead-letter queue.
version: 1.0.0
---
Operational runbook for [[channel|bookworm.{env}.catalog.dead-letter-queue]] owned by [[service|catalog-api]].
```bash
kcat -C -b "$KAFKA_BOOTSTRAP" -t "bookworm.${ENV}.catalog.dead-letter-queue" -o -20 -e -f '%t [%p] offset=%o key=%k headers=%h\n%s\n---\n'
```
Confirm the target `bookId` exists in [[service|catalog-api]] via [[query|GetBook]]. If the book
was deleted, do not replay—[[service|rating-api]] handles missing-book compensation via
[[event|BookUpdatedRatingFailedIntegrationEvent]].
For transient database or concurrency failures on [[event|FeedbackCreatedIntegrationEvent]] or
[[event|FeedbackDeletedIntegrationEvent]], re-publish the original CloudEvents payload with the
`bookId` partition key to `bookworm.${ENV}.rating.feedback-create` or `bookworm.${ENV}
.rating.feedback-delete`.
---
title: Engineering Invariants and Quirks
summary: Unprefixed Kafka batch trigger, Qdrant upsert idempotency, and PostgreSQL pending-queue semantics for Catalog Ingestion.
version: 1.0.0
---
Engineering invariants and known contract quirks for [[service|catalog-ingestion]].
## Ingestion & Vector Indexing Invariants
- **Unprefixed batch trigger topic:** [[service|catalog-ingestion]] is triggered by [[event|ProcessVectorBatchIntegrationEvent]] on [[channel|scheduler.process-vector-batch]]. Unlike `bookworm.{env}.*` domain topics, this topic name is intentionally unprefixed and shared across the scheduler-to-ingestion boundary.
- **Idempotent Qdrant batch upsert:** Pending book records are read from [[container|catalog-database]], embedded, and upserted into [[container|catalog-vector]] (Qdrant) using deterministic book identifiers so replayed batch triggers safely overwrite existing vectors without creating duplicates.
- **Queue-backed resilience:** Because pending embedding state remains in PostgreSQL until marked processed, transient batch failures do not require a separate Kafka dead-letter queue—the next scheduled trigger picks up remaining pending rows.
---
title: Vector Re-Index and Lag Recovery
summary: CLI-first runbook to verify pending embedding backlog in PostgreSQL and Qdrant collection health.
version: 1.0.0
---
Operational runbook for [[service|catalog-ingestion]] when semantic search results lag behind [[service|catalog-api]] writes.
Check point counts and collection status in [[container|catalog-vector]]:
```bash
curl -sS "$QDRANT_URL/collections" | jq .
```
Confirm [[service|catalog-ingestion]] is actively consuming [[channel|scheduler.process-vector-batch]] without rebalance loops.
Use the [[service|scheduler-service]] manual batch trigger runbook to emit [[event|ProcessVectorBatchIntegrationEvent]] once Qdrant connectivity and embedding model quotas are healthy.
---
title: Conversation architecture and boundaries
summary: Workflow layers, session persistence tiers, governance controls, and domain boundaries for Chat API and MCP Tools.
version: 1.0.0
type: engineering
order: 1
badges:
- content: Architecture
backgroundColor: green
textColor: green
---
## Purpose & Scope
This document defines the runtime workflow stages, three-tier session and memory model, governance controls, and cross-domain boundaries for [[service|chat-api]] and [[service|mcp-server]] in the [[domain|conversational]] subdomain. Use it to verify where Conversational responsibilities start and end relative to [[domain|catalog]], [[domain|shopping]], [[domain|ordering]], and [[domain|reviews]].
## Visual Reference
The visual below shows how storefront chat requests traverse the API Gateway and [[service|chat-api]] workflow layers to reach Microsoft Foundry, [[container|chat-session-blob]], [[service|presidio-api]], [[service|mcp-server]], and [[service|rating-api]].
_Conversational Workflow, Governance, and Integration Boundaries_
## Core Invariants & Design Rules
- **No relational database, cache, or message broker:** [[service|chat-api]] uses **no** PostgreSQL, Redis, or Kafka. All state is split across durable AG-UI session blobs in [[container|chat-session-blob]], ephemeral container-local research scratchpads, and user-scoped Microsoft Foundry preference memory.
- **Strict read-only domain boundaries:** [[service|chat-api]] and [[service|mcp-server]] never mutate backend domain state. Catalog access is read-only via [[service|mcp-server]] over gRPC to [[service|catalog-api]]; review summarization is read-only via A2A gRPC to [[agent|rating-agent]] on [[service|rating-api]]; store-policy answers come strictly from static policy skills with zero live access to [[service|basket-api]] or [[service|order-api]].
- **Client-side basket isolation:** Any user-confirmed basket UI actions (`addToBasket`, `viewBasket`, `showBasketSummary`) execute strictly in the Storefront browser client, never as server-side mutations in [[service|chat-api]].
- **Layered safety & confidence gating:**
- **Input validation:** Enforces non-empty prompts, truncates inputs over `2000` characters to `1900` characters, and rejects prompt-injection patterns before model routing (bypassing pure tool-result resume turns).
- **Decision routing & HITL disambiguation:** Evaluates safety, English language, and in-scope confidence (`< 0.5` rejects) plus route confidence (`< 0.6` pauses for human-in-the-loop disambiguation across `book`, `qa`, and `rating`).
- **Response formatting:** Strips leaked system-prompt markers, passes empty strings on tool-call-only turns, and falls back to a safe rephrase prompt if no assistant text remains.
- **Constrained specialist handoffs:** [[agent|book-agent]] may hand off to [[agent|rating-agent]] (only when a single book UUID is resolved; terminal—cannot hand back) or to [[agent|qa-agent]] (for store-policy questions); [[agent|qa-agent]] may hand off book-specific portions to [[agent|book-agent]]. Emotional book feedback is handled inline by [[agent|book-agent]] without persisting Reviews [[entity|feedback]].
:::warning
**Tool governance is default-deny.** Any new MCP tool, skill tool, Storefront UI tool, or handoff tool fails silently or returns a governance denial unless explicitly allowlisted for the calling agent identity, and `qa-agent` must remain explicitly denied access to Catalog tools.
:::
## Boundaries & Guarantees
| Concern | Strategy & Guarantee | Failure / Edge-Case Behavior | Related Resources |
| :--------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Persistence** | AG-UI transcripts persist durably in chat-session-blob (`ag-ui/` prefix) with claims-based per-user isolation; Foundry memory stores cross-session reading preferences by Entra ID subject; working file memory is container-local. | Container restarts preserve AG-UI transcripts and Foundry preferences but discard ephemeral working file scratchpads unless backed by persistent storage. | chat-session-blob, adr-006-user-scoped-episodic-and-semantic-memory |
| **Caching & Transport** | mcp-server operates as a stateless Streamable HTTP (`/mcp`) adapter backed by catalog-api gRPC; chat-api exposes `/ag-ui` and `/agents` with `PerUserRateLimit`. | Rate-limit exhaustion returns `429 Too Many Requests` with `Retry-After`; missing Catalog attributes are reported as unavailable rather than guessed. | mcp-server, adr-001-mcp-read-only-domain-adapter, adr-002-stateless-streamable-http-transport |
| **Messaging & Protocols** | No Kafka messaging; chat-api uses HTTP (`/ag-ui`), MCP Streamable HTTP (`/mcp`), and A2A gRPC (`2m` timeout with Entra Agent Identity token exchange to rating-api). | Unavailable downstream MCP or A2A gRPC calls surface partial-evidence or fallback responses without fabricating catalog or review data. | chat-api, rating-agent, adr-003-separate-interactive-and-agent-protocols |
| **Concurrency & Governance** | Per-user token-bucket rate limiting (`30` token limit, `20` per `10s`, queue `5`) plus global concurrency limits; Presidio PII middleware redacts sensitive entities on specialist turns; conversation guardian bounds turns (`30`) and retry cycles (`3`). | Guardrail, injection, or threshold violations short-circuit the turn with a structured rejection message before invoking specialist tools. | presidio-api, adr-002-fail-closed-pii-middleware, adr-005-govern-agent-tools-per-agent |
[[agent|book-agent]] can delegate multi-step catalog and recommendation lookups concurrently to
[[agent|book-catalog-researcher]] and [[agent|book-recommendation-researcher]], synthesizing and
deduplicating results while surfacing partial-evidence gaps transparently.
When route confidence is below `0.6`, execution pauses at the disambiguation interrupt with
three choices (`book`, `qa`, `rating`). Both structured tool-result responses and plain-text
customer replies (such as `1`/`book`, `2`/`qa`, `3`/`rating`) are normalized to resume the
selected specialist at `1.0` confidence.
## Safe Change & Verification Checklist
- Preserve read-only boundaries across [[service|chat-api]] and [[service|mcp-server]]; never introduce PostgreSQL, Redis, Kafka, or direct backend write clients.
- Update per-agent governance allowlists whenever adding MCP, skill, harness, or Storefront UI tools, keeping `qa-agent` denied from Catalog tools.
- Keep Presidio PII middleware, Entra ID `customer` authorization (`chatting_read` / `chatting_write`), claims-based session isolation, and Entra Agent Identity token exchange intact.
- Verify prompt validation, routing thresholds (`0.5` / `0.6`), HITL disambiguation resume, specialist handoff preconditions, and session persistence in Chat unit tests via `mise run test`.
## Related Resources
- [[service|chat-api]] — Conversational workflow host and AG-UI endpoint
- [[service|mcp-server]] — Stateless read-only Catalog MCP adapter
- [[agent|book-agent]], [[agent|book-catalog-researcher]], [[agent|book-recommendation-researcher]], [[agent|qa-agent]], [[agent|rating-agent]] — Conversational specialists
- [[flow|agent-orchestration]] — End-to-end conversational orchestration flow
- [[adr|adr-001-chat-agent-orchestration-boundary]], [[adr|adr-002-fail-closed-pii-middleware]], [[adr|adr-005-govern-agent-tools-per-agent]], [[adr|adr-007-system-one-decision-model-routing-and-tool-selection]]
- [[doc|misc/001-ms-decisions-model-use-case-and-lessons-learned]] — Routing decision model design and lessons learned
---
title: Agent and workflow change checklist
summary: Pre-merge engineering checklist for Conversational agents, routing guardrails, governance policies, and MCP/A2A contracts.
version: 1.0.0
type: engineering
order: 2
badges:
- content: Architecture
backgroundColor: green
textColor: green
---
## Purpose & Scope
This checklist defines the mandatory pre-merge verification steps for engineers modifying [[service|chat-api]], [[service|mcp-server]], or any specialist agent in the [[domain|conversational]] subdomain. Use it whenever changing agent instructions, routing thresholds, governance policies, MCP tool signatures, or A2A gRPC integrations.
## Core Invariants & Design Rules
- **Preserve domain ownership:** [[service|catalog-api]], [[service|basket-api]], [[service|order-api]], and [[service|rating-api]] remain the sole authoritative owners of catalog, basket, order, and [[entity|feedback]] state.
- **Grounding & uncertainty:** [[agent|book-agent]], [[agent|book-catalog-researcher]], and [[agent|book-recommendation-researcher]] must cite only [[service|mcp-server]] results and report missing prices, availability, or ratings as unavailable rather than guessing.
- **Inline sentiment without persistence:** Emotional book feedback is handled inline by [[agent|book-agent]] without adding a separate sentiment agent or implying that a Reviews [[entity|feedback]] record was persisted.
- **Policy-only support:** [[agent|qa-agent]] must answer strictly from static store-policy guidance and never claim live access to customer accounts, baskets, or orders.
:::warning
**Governance rules default to deny.** Adding a tool to an agent prompt or [[service|mcp-server]] without updating the corresponding agent's governance allowlist will silently block or reject tool execution at runtime.
:::
## Boundaries & Guarantees
| Concern | Strategy & Guarantee | Failure / Edge-Case Behavior | Related Resources |
| :--------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Persistence** | AG-UI sessions persist in chat-session-blob (`ag-ui/`) per Entra ID user; Foundry memory stores reading preferences; local file memory is ephemeral. | Session blobs survive container restarts; local research scratchpads do not. | chat-session-blob, adr-006-user-scoped-episodic-and-semantic-memory |
| **Caching & Contracts** | mcp-server tool schemas (`search_catalog`, `get_book`, `list_categories`, `list_authors`) must stay aligned with agent definitions and catalog-api gRPC contracts. | Schema drift between mcp-server and agent definitions breaks tool invocation or degrades research synthesis. | mcp-server, adr-004-use-domain-apis-as-mcp-backends |
| **Messaging & Protocols** | Handoff to rating-agent uses A2A gRPC (`2m` timeout, Entra Agent Identity token exchange); Storefront UI tools execute client-side with user confirmation. | Unresolved book IDs must block `Book -> Rating` handoff; `Rating` remains terminal with no back-handoff. | chat-api, rating-agent, adr-003-separate-interactive-and-agent-protocols |
| **Concurrency & Governance** | Input truncation (`> 2000` → `1900`), decision guardrails (`< 0.5` reject, `< 0.6` HITL pause), Presidio PII redaction, and `PerUserRateLimit` protect every turn. | Multi-turn injection patterns or turn/retry limits (`30` turns / `3` retries) halt execution safely before tool misuse. | presidio-api, adr-002-fail-closed-pii-middleware, adr-005-govern-agent-tools-per-agent |
## Safe Change & Verification Checklist
Confirm whether the change affects input validation, decision routing/disambiguation, specialist
sub-workflows, or response formatting, and verify no backend write clients or databases were
introduced.
Add explicit allow rules in the agent governance policy for any new tools, preserve `qa-agent`
Catalog tool denials, and keep Presidio PII middleware, Entra ID `customer` authorization, and
`PerUserRateLimit` active.
Confirm [[service|mcp-server]] tool signatures match specialist definitions and
[[service|rating-api]] A2A gRPC token exchange remains intact.
Run `mise run format`, `mise run build`, and `mise run test` to verify input validation,
decision thresholds (`0.5` / `0.6`), HITL resume normalization, handoff preconditions,
formatting fallbacks, and [[container|chat-session-blob]] round-trips.
## Related Resources
- [[service|chat-api]] — Conversational workflow host
- [[service|mcp-server]] — Read-only Catalog MCP server
- [[agent|book-agent]], [[agent|qa-agent]], [[agent|rating-agent]] — Primary conversational specialists
- [[flow|agent-orchestration]] — End-to-end conversational orchestration flow
- [[adr|adr-001-chat-agent-orchestration-boundary]], [[adr|adr-005-govern-agent-tools-per-agent]], [[adr|adr-007-system-one-decision-model-routing-and-tool-selection]]
---
title: Route customer requests
summary: How the Chat workflow validates requests and chooses a BookWorm specialist.
version: 1.0.0
type: guides
order: 1
badges:
- content: Guide
backgroundColor: teal
textColor: teal
---
**Audience & Outcome:** This guide is for AI engineers and backend developers working on [[service|chat-api]]. You will learn how incoming conversational messages are validated, classified, disambiguated, and routed across BookWorm's specialist agents.
[[service|chat-api]] routes every interactive message through a deterministic three-layer workflow rather than an open-ended LLM router. The pipeline validates and truncates input first, evaluates safety, language, scope, and specialist intent with `Microsoft-Decision-1`, pauses for human-in-the-loop (HITL) disambiguation when confidence is low, and coordinates bounded handoffs across [[agent|book-agent]], [[agent|qa-agent]], and [[agent|rating-agent]].
## Context and motivation
Customer chat messages span distinct domains—book discovery, store policies, and review analysis—alongside empty, non-English, off-topic, or prompt-injection inputs. Sending unscreened messages straight to a general LLM router wastes inference budget, increases latency, and makes routing behavior nondeterministic.
By separating deterministic input hygiene, calibrated classification, explicit low-confidence confirmation, and scoped specialist sub-workflows, BookWorm rejects invalid traffic early and keeps routing observable and testable.
## How it works
The visual below traces a customer message through input validation, `Microsoft-Decision-1` routing, HITL disambiguation, specialist handoffs, and final response formatting.
### Three-layer routing pipeline
**Disambiguation resume normalization:** If an unanswered disambiguation prompt exists and the user replies in plain text (`1`/`book`, `2`/`qa`/`support`/`policy`, `3`/`rating`/`review`), the workflow normalizes the reply into a structured tool result so both rich UI clients and plain-text clients resume cleanly.
**Deterministic hygiene & safety:** Tool-result resume turns bypass text validation. For user text turns, the pipeline trims whitespace, rejects empty prompts, screens for prompt-injection and XSS markers, and applies governance prompt-safety policies. Accepted prompts longer than `2,000` characters are truncated to `1,900` characters.
The decision router evaluates four structured questions in order via `Microsoft-Decision-1`:
| Decision check | Threshold / rule | Outcome when triggered |
| :----------------------------------- | :--------------------- | :---------------------------------------------------------- |
| **`is_safe`** | `P(is_safe) < 0.5` | Short-circuits with an unsafe-input rejection |
| **`is_english`** | `P(is_english) < 0.5` | Short-circuits with an English-only notice |
| **`is_in_scope`** | `P(is_in_scope) < 0.5` | Short-circuits with an out-of-scope bookstore notice |
| **`route` (`Book`, `QA`, `Rating`)** | Confidence `< 0.6` | Pauses for user disambiguation between Book, QA, and Rating |
| **`route` (`Book`, `QA`, `Rating`)** | Confidence `>= 0.6` | Forwards directly to the selected specialist |
:::note
If `Microsoft-Decision-1` returns a partial response, omitted binary guardrails default to `1.0` and an unanswered route choice defaults to [[agent|book-agent]] so transient partial responses degrade predictably.
:::
If the assistant turn carries a pending client-side UI tool call with empty text, the formatter preserves the tool call without overwriting it. Otherwise, it strips any leaked system markers, collapses excessive blank lines, ensures terminal punctuation, and falls back to a safe rephrase message if no usable text remains.
### Specialist selection and handoffs
| Customer intent | Initial specialist | Follow-up handoff behavior |
| :----------------------------------------------------------------------------------- | :---------------------- | :---------------------------------------------------------------------------------------------------------------------------- |
| Book search, recommendations, catalog details, or review questions without a book ID | [[agent\|book-agent]] | Hands off to [[agent\|rating-agent]] once a single book ID is resolved, or to [[agent\|qa-agent]] for store-policy follow-ups |
| Store policies, shipping, returns, refunds, accounts, orders, or billing | [[agent\|qa-agent]] | Hands off book-specific portions of mixed requests to [[agent\|book-agent]]; never claims live account or order lookup |
| Review summaries or rating analysis when a book catalog ID is already present | [[agent\|rating-agent]] | Calls [[service\|rating-api]] over A2A gRPC; terminal specialist (cannot search the catalog or hand back) |
| Decision | Benefits | Costs and limits |
| :------------------------------------------------------------ | :--------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------- |
| **Use `Microsoft-Decision-1` instead of an LLM router agent** | Produces calibrated probabilities at lower latency and cost than full chat completions | Requires maintaining explicit binary/choice questions and thresholds |
| **Separate Layer 1 validation from Layer 2 semantic routing** | Blocks empty messages, injections, and oversized payloads before any model call | Truncating prompts over `2,000` characters can clip a trailing book UUID |
| **Pause for disambiguation when route confidence `< 0.6`** | Prevents misrouting ambiguous requests to the wrong specialist | Adds one interactive turn before answering ambiguous prompts |
| **Keep [[agent\|rating-agent]] terminal and ID-gated** | Avoids duplicating [[service\|mcp-server]] catalog search inside [[service\|rating-api]] | Title-only review requests always route through [[agent\|book-agent]] first |
**Rejected alternatives:**
- **Single LLM supervisor agent:** Lacks calibrated probability distributions for a deterministic `< 0.6` HITL threshold and increases per-turn latency.
- **Per-specialist rejection:** Duplicating safety, language, and scope prompts across three specialists increases drift and wastes tool invocations.
## Related documentation
- [[flow|agent-orchestration]] — End-to-end orchestration flow for [[service|chat-api]].
- [[adr|adr-007-system-one-decision-model-routing-and-tool-selection]] — Decision record for `Microsoft-Decision-1` routing.
- [[adr|adr-001-chat-agent-orchestration-boundary]] — Orchestration boundary within [[system|chat-system]].
---
title: Handle book discovery requests
summary: Guidance for direct book answers, recommendations, and delegated research.
version: 1.0.0
type: guides
order: 2
badges:
- content: Guide
backgroundColor: teal
textColor: teal
---
**Audience & Outcome:** This guide is for AI engineers and catalog integrators working with [[agent|book-agent]] inside [[service|chat-api]]. You will learn how [[agent|book-agent]] balances direct catalog lookups, concurrent sub-agent research, Plan Mode approvals, and strict catalog grounding.
BookWorm handles catalog search, title lookups, and tailored recommendations through [[agent|book-agent]]. Rather than running a heavy multi-step research pipeline on every turn, [[agent|book-agent]] answers simple lookups directly via read-only [[service|mcp-server]] tools, delegates complex multi-criteria requests to two concurrent specialist researchers, and enforces explicit catalog grounding so missing facts are never invented.
## Context and motivation
Customer book discovery spans a wide complexity spectrum—from single-step factual questions (_"Do you have books by Frank Herbert?"_) to open-ended, multi-constraint recommendations (_"Find two short science-fiction novels under \$20 similar to Dune and verify which authors are in stock"_).
Running multi-agent research on simple queries adds unnecessary latency and token cost, while answering complex queries with a single shallow lookup produces incomplete or hallucinated recommendations. BookWorm resolves this tension by combining direct MCP tool calls, optional Plan Mode approval, concurrent sub-agent delegation, and strict catalog-only grounding.
## How it works
The visual below shows how [[agent|book-agent]] retrieves catalog facts through [[service|mcp-server]], fans out complex queries to parallel researchers, and coordinates handoffs or rich UI rendering.
### Five core discovery mechanisms
1. **Read-only MCP catalog grounding:** [[agent|book-agent]] and both researchers call only four read-only tools exposed by [[service|mcp-server]] (`search_catalog`, `get_book`, `list_categories`, `list_authors`), backed by [[service|catalog-api]] over gRPC. When a price, rating, or availability fact is absent from tool output, [[agent|book-agent]] states that the detail is unavailable instead of guessing.
2. **Direct handling vs. concurrent researcher delegation:** For single-step lookups or preference clarifications, [[agent|book-agent]] calls MCP tools directly. For complex requests combining factual verification and preference curation, it invokes [[agent|book-catalog-researcher]] (low temperature `0.2` for factual precision) and [[agent|book-recommendation-researcher]] (temperature `0.4` for curation) concurrently, then synthesizes and deduplicates their findings.
3. **Plan Mode and Execute Mode harness:** For multi-step research, **Plan Mode** decomposes the work into tracked todos, optionally persists the plan, and waits for customer approval before switching to **Execute Mode**. Single-step lookups bypass planning and approval.
4. **User-scoped memory and compaction:** Episodic and semantic memory recalls user-scoped reading preferences (keyed by Microsoft Entra ID user claims) without inferring demographics or stereotypes. Context compaction preserves multi-step research findings across long conversations.
5. **Client-side UI tools and specialist handoffs:** When Storefront supplies client-side UI tools, [[agent|book-agent]] invokes rich cards or basket actions (enforcing browser-side user confirmation); otherwise it falls back to Markdown. For review analysis, it resolves a single book ID before handing off to [[agent|rating-agent]]; for store policies, it hands off to [[agent|qa-agent]].
:::note
All [[agent|book-agent]] and researcher tool calls pass through [[service|presidio-api]] PII middleware, guardrail middleware, decision-based tool selection, and default-deny governance policies.
:::
| Decision | Benefits | Costs and limits |
| :-------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------- |
| **Conditional delegation to two specialized researchers** | Keeps simple lookups fast while pairing factual verification with recommendation curation on complex queries | Adds synthesis and deduplication logic when one branch returns partial results |
| **Plan Mode approval gate for multi-step research** | Prevents wasted tool calls when criteria are ambiguous and keeps steps transparent | Adds an extra conversational turn if the customer has not approved the plan |
| **Strict catalog-only grounding** | Eliminates fabricated titles, authors, prices, or stock states | Produces narrower answers when catalog metadata or vector matches are incomplete |
| **Client-side Storefront basket tools** | Lets customers inspect or add books without giving [[service\|chat-api]] direct write authority over [[service\|basket-api]] | Rich cards and basket actions depend on Storefront tool registration |
**Rejected alternatives:**
- **Running parallel researchers on every query:** Doubles latency and token usage on simple title or author lookups without improving accuracy.
- **Exposing [[service|catalog-api]] gRPC directly inside [[service|chat-api]]:** Bypassed central MCP governance, inspector debugging, and reuse across [[system|chat-system]] and [[system|rating-system]].
## Related documentation
- [[flow|agent-orchestration]] — End-to-end orchestration flow for [[service|chat-api]].
- [[adr|adr-005-govern-agent-tools-per-agent]] — Per-agent tool governance and least-privilege rules.
- [[adr|adr-006-user-scoped-episodic-and-semantic-memory]] — User-scoped memory isolation for [[agent|book-agent]].
---
title: Answer store and customer-support questions
summary: How the QA Agent responds to store questions using supplied policy context and clear limits.
version: 1.0.0
type: guides
order: 3
badges:
- content: Guide
backgroundColor: teal
textColor: teal
---
**Audience & Outcome:** This guide is for AI engineers and support-domain architects working on [[agent|qa-agent]] inside [[service|chat-api]]. You will learn how [[agent|qa-agent]] grounds answers in version-controlled policy skills while remaining structurally isolated from transactional customer data.
BookWorm routes store-policy and customer-support questions to [[agent|qa-agent]], an isolated specialist inside [[service|chat-api]]. [[agent|qa-agent]] grounds every answer in version-controlled store-policy skill documents and hands off book-specific follow-ups to [[agent|book-agent]], while structural governance rules prevent it from reading or mutating live customer accounts, baskets, or orders.
## Context and motivation
Customers regularly ask conversational questions about shipping speeds, return windows, refund timelines, gift cards, and order cancellations. In a microservices architecture, those topics sit adjacent to sensitive transactional domains—[[service|basket-api]] and [[service|order-api]].
If a conversational agent blends general policy guidance with live transactional lookups or writes, two failure modes emerge:
- **False transaction confirmation:** An LLM can phrase a generic return or cancellation policy as if it verified the customer's personal order status.
- **Over-privileged attack surface:** Granting a general support agent direct access to [[service|basket-api]], [[service|order-api]], or catalog search tools increases prompt-injection blast radius and blurs bounded-context ownership.
## How it works
When the decision router classifies an in-scope English request as a support or policy question—or when [[agent|book-agent]] transfers a policy question—[[agent|qa-agent]] executes under strict policy grounding and tool isolation.
The visual below shows how [[agent|qa-agent]] loads policy context from the store-policies skill, enforces governance and privacy middleware, and hands off mixed book requests to [[agent|book-agent]].
### Four architectural invariants
:::warning
[[agent|qa-agent]] has zero network path to [[service|basket-api]] or [[service|order-api]]. It must never claim to have checked a live order, refund, or account balance.
:::
- **Skill-based policy grounding:** [[agent|qa-agent]] loads version-controlled store-policy skill documents covering shipping tiers, 30-day returns and refunds, account and order guidance (such as the 1-hour cancellation window), gift cards, BookPoints loyalty, wishlists, and pre-orders. When the skill files do not answer a question, it directs the customer to human support rather than inventing policies.
- **Structural tool isolation via governance:** Default-deny governance rules permit [[agent|qa-agent]] to invoke only skill-loading tools and `handoff_to_book`, while explicitly denying catalog tools (`search_catalog`, `get_book`, `list_categories`, `list_authors`). [[service|chat-api]] registers no Basket or Ordering clients.
- **Privacy, guardrails, and lightweight compaction:** Every model call runs through [[service|presidio-api]] PII filtering, guardrail middleware, decision-based tool selection, and lightweight context compaction.
- **Bidirectional mixed-intent handoffs:** [[agent|qa-agent]] hands book-specific portions of a mixed inquiry to [[agent|book-agent]] after resolving the policy portion, and [[agent|book-agent]] can hand policy follow-ups back to [[agent|qa-agent]].
| Decision | Benefits | Costs and limits |
| :---------------------------------------------------------------------- | :------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------- |
| **Policy-only skill grounding without live Ordering or Basket clients** | Eliminates unauthorized account lookups, order mutations, and false confirmations | Customers asking for real-time order tracking must use Commerce or contact human support |
| **Explicit catalog-tool denial on [[agent\|qa-agent]]** | Enforces separation of concerns and prevents ungrounded book searches | Mixed support-and-book messages incur an extra handoff hop to [[agent\|book-agent]] |
| **Version-controlled Markdown policy skills** | Policy updates go through Git review and deploy deterministically with [[service\|chat-api]] | Policy changes require a [[service\|chat-api]] redeployment rather than live CMS edits |
**Rejected alternatives:**
- **Granting [[agent|qa-agent]] read-only OBO access to [[service|order-api]] and [[service|basket-api]]:** Expands PII exposure and prompt-injection risk; customers already manage baskets and order history directly in Commerce.
- **Merging store policies into [[agent|book-agent]]:** Degrades prompt focus and prevents enforcing distinct per-agent tool governance policies.
## Related documentation
- [[flow|agent-orchestration]] — How `Microsoft-Decision-1` selects [[agent|qa-agent]] and coordinates handoffs.
- [[adr|adr-005-govern-agent-tools-per-agent]] — Per-agent tool governance and explicit denials.
- [[adr|adr-002-fail-closed-pii-middleware]] — Fail-closed PII filtering across agent inputs and outputs.
---
title: Handle book feedback in conversation
summary: Set expectations when a customer shares an opinion or feedback about a book with an agent.
version: 1.0.0
type: guides
order: 4
badges:
- content: Guide
backgroundColor: teal
textColor: teal
---
**Audience & Outcome:** This guide is for AI engineers and product owners working on [[service|chat-api]] and Reviews integration. You will learn how conversational feedback is kept strictly separate from authoritative [[entity|feedback]] records and Catalog rating summaries.
When a customer shares praise, criticism, or an opinion about a book during chat, [[agent|book-agent]] responds empathetically inside the conversation without creating, modifying, or deleting any official review record. Authoritative [[entity|feedback]] records live exclusively in [[service|rating-api]], and BookWorm keeps conversational discussion strictly separate from persisted review writes.
## Context and motivation
Customers naturally blend three different intents in bookstore conversations:
1. **Sharing an informal opinion** (_"I loved the pacing of Dune, give me something similar"_).
2. **Asking for an analysis of existing reviews** (_"What do readers say about Dune?"_).
3. **Submitting, editing, or deleting a public review** that affects a book's rating summary.
Treating informal chat comments as official reviews creates silent data-integrity bugs and misleads customers into believing a casual message updated a book's public rating. BookWorm separates empathetic conversational handling, read-only review summarization, and authoritative review persistence into three distinct paths.
## How it works
The visual below contrasts the two read-only Conversational paths against the separate authoritative Reviews write path through [[service|rating-api]] and Kafka.
### Four architectural invariants
:::warning
[[service|chat-api]] has no Kafka producer, no [[container|rating-database]] connection, and no review write tools. [[agent|book-agent]] must never claim that a chat comment was saved, published, or used to update a book's rating.
:::
- **Inline sentiment inference with no Sentiment Agent:** [[agent|book-agent]] infers customer sentiment from emotional book feedback, acknowledges it naturally, and uses it to shape follow-up recommendations without exposing raw sentiment labels unless asked. BookWorm has no separate sentiment agent or microservice.
- **Zero write path from Chat to Reviews:** Governance rules permit [[agent|book-agent]] to call `handoff_to_rating` for read-only analysis only, never to create or delete [[entity|feedback]] records.
- **ID-gated read-only review summarization:** When a customer asks to summarize reviews without providing a book ID, the decision router sends the request to [[agent|book-agent]]. It resolves the exact catalog ID via [[service|mcp-server]] (`search_catalog`) and hands off to [[agent|rating-agent]] over A2A gRPC. [[agent|rating-agent]] is terminal and read-only.
- **Formal reviews stay in Reviews and project asynchronously:** Customers who want to submit or remove an official review use the Storefront review flow backed by [[service|rating-api]], which persists [[entity|feedback]] in [[container|rating-database]] and publishes [[event|FeedbackCreatedIntegrationEvent]] or [[event|FeedbackDeletedIntegrationEvent]] so [[service|catalog-api]] updates its derived rating summary.
| Decision | Benefits | Costs and limits |
| :--------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------- |
| **Keep chat feedback non-persistent and read-only** | Prevents accidental review publication and preserves auditability in Reviews | Customers wishing to publish an opinion must submit a formal review in Storefront |
| **Handle emotional sentiment inline in [[agent\|book-agent]]** | Avoids the latency and operational cost of a dedicated sentiment agent | Sentiment inference is scoped to the conversational turn rather than persisted |
| **Require a resolved single book ID before [[agent\|rating-agent]] handoff** | Keeps [[agent\|rating-agent]] focused strictly on review analysis without duplicating catalog search | Title-only review questions take an extra catalog-resolution step before handoff |
**Rejected alternatives:**
- **Adding a dedicated Sentiment Agent:** Foundation models invoked by [[agent|book-agent]] already infer conversational sentiment reliably inline.
- **Adding a review write tool to [[agent|book-agent]]:** Persisting public reviews requires explicit customer intent, structured validation, and authenticated Reviews ownership.
## Related documentation
- [[flow|agent-orchestration]] — How `Microsoft-Decision-1` selects specialists and coordinates handoffs.
- [[flow|feedback-publication]] — How formal reviews persist in [[service|rating-api]] and project to [[service|catalog-api]].
- [[adr|adr-004-read-only-governed-feedback-summarization]] — Decision record for read-only, governed feedback summarization.
---
title: Chat request does not return a usable response
summary: Triage an interactive request that fails to return a useful assistant response.
version: 1.0.0
type: runbooks
order: 1
badges:
- content: Runbook
backgroundColor: orange
textColor: orange
---
## Trigger / Symptom & Blast Radius
A customer sends a chat message through Storefront and receives an HTTP error (`401`, `403`, `429`, `5xx`), a stalled stream, an empty reply, or the generic rephrase fallback. Blast radius is isolated to interactive [[service|chat-api]] conversations; catalog browsing, basket, and checkout remain unaffected.
Never include raw customer prompts, names, email addresses, or personal data in incident tickets
or logs. Record only the request category, stage outcomes, and correlation IDs.
## Pre-Flight Check
Verify [[service|chat-api]] container status and stream recent logs in ``:
```bash
az containerapp show --name --resource-group --query "properties.runningStatus" -o tsv
az containerapp logs show --name --resource-group --tail 200
```
## Quick Recovery Procedure
Confirm the request targeted `/chatting/ag-ui` (forwarded to `/ag-ui` on [[service|chat-api]]). Interpret HTTP status codes:
**`401` / `403`:** Missing/invalid Entra ID token or missing `customer` role / `chatting_read` + `chatting_write` scopes.
**`429`:** Per-user rate limit exceeded; honor `Retry-After`.
**`5xx` or `200` with fallback text:** Continue to dependency and trace checks.
Inspect the trace in Aspire Dashboard (local) or Azure Log Analytics (``):
**Input validation:** Confirm whether the turn was accepted or rejected as empty/unsafe.
**Decision router:** Confirm `Microsoft-Decision-1` selected [[agent|book-agent]], [[agent|qa-agent]], or [[agent|rating-agent]].
**Specialist & formatter:** Confirm the selected specialist produced text or a client UI tool call (an empty text string with a tool call is expected for Storefront cards).
Look for failed spans or timeouts across:
**Microsoft Foundry:** Model errors, throttling, or `CognitiveServicesUser` RBAC failures.
**[[service|presidio-api]]:** PII analyzer/anonymizer failures.
**[[service|mcp-server]]:** Catalog tool errors during [[agent|book-agent]] execution.
**[[service|rating-api]]:** A2A gRPC timeouts (2-minute client timeout) or Entra Agent Identity token exchange errors.
[[service|chat-api]] persists conversation transcripts in [[container|chat-session-blob]]. Confirm the Storage Account (or local Azurite) is reachable and the [[service|chat-api]] Managed Identity holds `Storage Blob Data Contributor`.
## Verification
Replay an equivalent sanitized request against `/chatting/ag-ui` and confirm HTTP `200` with a non-fallback assistant response or expected UI tool call in the trace:
```bash
az containerapp logs show --name --resource-group --tail 50
```
Expected trace progression:
```text
1. /ag-ui returns 200 with an event stream
2. Input validation -> accepted
3. Decision router -> selected specialist ()
4. Specialist -> assistant text or client UI tool call
```
## Rollback / Escalation
- **Rollback:** If a recent [[service|chat-api]] deployment introduced regressions in prompts, routing, or middleware, roll back to the previous Container App revision in ``.
- **Escalation:** Escalate repeated fallbacks or dependency faults to [[team|ai-capabilities-team]] (code/prompts) or [[team|platform-engineering-team]] (Foundry/RBAC/Storage).
## Related documentation
- [[flow|agent-orchestration]] — End-to-end conversational workflow.
- [[adr|adr-002-fail-closed-pii-middleware]] — Fail-closed PII filtering behavior.
---
title: Unexpected request routing or rejection
summary: Diagnose whether an unexpected outcome came from validation, Decision Router classification, or specialist handoffs.
version: 1.0.0
type: runbooks
order: 2
badges:
- content: Runbook
backgroundColor: orange
textColor: orange
---
## Trigger / Symptom & Blast Radius
A [[service|chat-api]] request is rejected, receives an English-only or out-of-scope reply, pauses with a disambiguation prompt, reaches the wrong specialist, or only partially answers a mixed request. Blast radius is limited to conversational routing quality; transactional services remain unaffected.
Prompts exceeding `2,000` characters are truncated to the first `1,900` characters before routing.
A book UUID or primary question at the end of a long prompt may be clipped, causing misrouting.
## Pre-Flight Check
Stream recent [[service|chat-api]] logs in `` to inspect routing and guardrail decisions:
```bash
az containerapp logs show --name --resource-group --tail 300
```
## Quick Recovery Procedure
| Reply text | Gate | Cause |
| :-------------------------------------------------- | :------------------ | :-------------------------------------------------------------------------- |
| `Your message appears to be empty.` | Input validation | Prompt empty after trimming |
| `I can't process that request...` | Safety guardrail | Matched suspicious pattern, governance safety policy, or `P(is_safe) < 0.5` |
| `BookWorm Chat currently supports English only...` | Language guardrail | `P(is_english) < 0.5` |
| `I can only help with BookWorm bookstore topics...` | Scope guardrail | `P(is_in_scope) < 0.5` |
| `Which area best fits your request?` | Disambiguation port | Route confidence below `0.6` |
Filter [[service|chat-api]] logs around the request timestamp for `Decision router` entries (`P(is_safe)`, `P(is_english)`, `P(is_in_scope)`, and selected target `Book`, `QA`, or `Rating` with confidence score). Compare against expected routing:
**[[agent|book-agent]]:** Book search, recommendations, catalog details, or review questions without a book ID.
**[[agent|qa-agent]]:** Store policies, shipping, returns, accounts, orders, or billing.
**[[agent|rating-agent]]:** Review summaries or rating analysis when a book catalog ID is already present.
If paused for disambiguation, confirm the follow-up turn sent a tool result or recognized plain-text choice (`1`/`book`, `2`/`qa`/`policy`, `3`/`rating`/`review`). For mixed requests, confirm the trace shows `handoff_to_book`, `handoff_to_qa`, or `handoff_to_rating`.
## Verification
Replay a sanitized equivalent prompt and confirm the trace logs the expected specialist selection (`confidence >= 0.6`) and handoff completion:
```text
Decision router selected (confidence >= 0.600)
```
## Rollback / Escalation
- **Rollback:** If a recent `Microsoft-Decision-1` configuration or prompt-policy update caused false rejections, revert the policy/revision in ``.
- **Escalation:** Log false-positive regex/guardrail rejections (without raw PII) and escalate to [[team|ai-capabilities-team]].
## Related documentation
- [[flow|agent-orchestration]] — Routing thresholds and handoff rules.
- [[adr|adr-007-system-one-decision-model-routing-and-tool-selection]] — Decision model routing architecture.
---
title: Book research is incomplete or inconsistent
summary: Triage incomplete or conflicting findings from direct book handling or delegated research.
version: 1.0.0
type: runbooks
order: 3
badges:
- content: Runbook
backgroundColor: orange
textColor: orange
---
## Trigger / Symptom & Blast Radius
A [[agent|book-agent]] answer in [[service|chat-api]] drops stated preferences, returns only facts or only a shortlist, repeats titles, or makes unsupported claims. Blast radius is limited to conversational book discovery quality; [[service|catalog-api]] and checkout remain unaffected.
Never paste raw customer prompts, names, email addresses, or order details into incident tickets.
Keep escalation data sanitized to the same PII-redacted level enforced by
[[service|presidio-api]].
## Pre-Flight Check
Stream recent logs for [[service|chat-api]] and [[service|mcp-server]] in ``:
```bash
az containerapp logs show --name --resource-group --tail 200
```
## Quick Recovery Procedure
Inspect the trace for [[agent|book-agent]]:
**No delegate calls:** Simple lookups intentionally bypass sub-agent delegation.
**Plan Mode active:** If the agent presented a plan without switching to Execute Mode, it is waiting for customer approval (not stalled).
**Delegated calls present:** Verify both [[agent|book-catalog-researcher]] and [[agent|book-recommendation-researcher]] completed with findings.
Governance uses default-deny rules and returns `Blocked by governance policy: ` as a tool result when an agent calls an unpermitted tool or delegate. Verify the agent's allowlist covers the required catalog tools or researcher delegations.
Follow `search_catalog` and `get_book` spans from [[service|chat-api]] to [[service|mcp-server]] and [[service|catalog-api]] over gRPC. Check for `401`/`403` scope errors (`mcptools_read`), gRPC errors, or stale [[container|catalog-vector]] search results.
## Verification
Replay an equivalent sanitized multi-criteria request and confirm both researcher spans complete and return grounded findings:
```text
1. Decision router -> Book
2. Book Agent -> delegate_book_catalog_researcher + delegate_book_recommendation_researcher
3. Both researcher spans complete with catalog IDs
4. Response formatter returns non-fallback grounded text
```
## Rollback / Escalation
- **Rollback:** If a recent agent prompt or governance policy change caused denials or ungrounded claims, revert the [[service|chat-api]] revision in ``.
- **Escalation:** Escalate prompt grounding defects or missing researcher merges to [[team|ai-capabilities-team]]; escalate Entra ID scope or Foundry issues to [[team|platform-engineering-team]].
| Symptom | Cause | Fix |
| :----------------------------------- | :------------------------------------------ | :---------------------------------------------------------------------- |
| Plan presented, nothing happens | Waiting for customer approval in Plan Mode | Ask customer to approve the plan to enter Execute Mode |
| `search_catalog` returns `401`/`403` | Token lacks `mcptools_read` scope | Verify Entra ID app registration and scopes for [[service\|mcp-server]] |
| Known title missing from search | [[container\|catalog-vector]] lag | Follow the Catalog vector index lag runbook |
| Earlier research findings lost | Container-local file memory lost on restart | Expected after restart; ask customer to re-confirm criteria |
## Related documentation
- [[flow|agent-orchestration]] — Sub-agent delegation and grounding workflow.
- [[adr|adr-005-govern-agent-tools-per-agent]] — Default-deny per-agent tool governance.
---
title: Order consistency and data ownership
summary: Authoritative stores, checkout price snapshotting, Redis coordination, and Ordering vs. Finance boundaries.
version: 1.0.0
type: engineering
order: 1
badges:
- content: Architecture
backgroundColor: green
textColor: green
---
## Purpose & Scope
This document defines data ownership, transactional outbox guarantees, checkout snapshotting, and Redis coordination rules for [[service|order-api]] and [[service|order-orchestration]] in the [[domain|ordering]] subdomain. Use it when modifying order creation, Marten projections, Redis locks/idempotency, or cross-service checkout orchestration.
## Visual Reference
The visual below illustrates how [[service|order-api]] and [[service|order-orchestration]] isolate backing stores while coordinating via gRPC queries and Kafka messages.
_Ordering and Finance Data Ownership and Messaging Boundaries_
## Core Invariants & Design Rules
- **Authoritative order state:** [[container|order-database]] (PostgreSQL) is the sole system of record for [[entity|buyer]], [[entity|order]], and [[entity|order-item]] aggregates, Marten audit event streams (`DaemonLockId = 44444`), and Wolverine outbox/inbox tables. Marten projections (`OrderSummary`, `OrderSummaryView`) are derived views and never replace the `Order` aggregate.
- **Deterministic checkout snapshot:** During `POST /api/v1/orders`, [[service|order-api]] reads the customer's basket via [[query|GetBasketGrpc]], resolves every distinct `BookId` via [[query|GetBooksGrpc]] (aborting with `404 Not Found` if any book is missing), locks in `PriceSale ?? Price` per [[entity|order-item]], and persists the sum as the immutable order total. Subsequent [[service|catalog-api]] or [[service|basket-api]] changes never rewrite accepted orders.
- **Strict status vs. orchestration separation:** Only explicit HTTP transitions (`POST /api/v1/orders`, `PATCH .../complete`, `PATCH .../cancel`) mutate an order's `Status` (`New` → `Completed` or `New` → `Cancelled`). [[service|order-orchestration]] maintains an independent saga state in Azure Durable Task Scheduler (`finance-taskhub`) and never calls [[service|order-api]] to cancel an order.
- **Soft delete vs. cancellation:** [[command|DeleteBasketFailedCommand]] triggers soft deletion (`IsDeleted = true`) to hide the order from standard queries without setting `Status` to `Cancelled`. [[command|DeleteBasketCompleteCommand]] is logged and leaves `Status` as `New`.
- **Bounded saga retries:** When [[service|order-orchestration]] exhausts its bounded retry budget (`MaxAttempts: 3` at `30m` timer intervals), it transitions its own orchestration state to `Cancelled` and emits [[command|CancelOrderCommand]] to [[service|notification-api]].
:::warning
**Never flush Redis broadly during incidents.** [[container|order-cache]] holds active HTTP idempotency markers (`{METHOD}:{PATH}:{x-request-id}`, `3600s` TTL) and buyer creation locks (`order-create:{userId}`, `60s` TTL) alongside FusionCache read entries. Broadly flushing Redis exposes concurrent checkouts to duplicate order creation.
:::
## Boundaries & Guarantees
| Concern | Strategy & Guarantee | Failure / Edge-Case Behavior | Related Resources |
| :---------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Persistence** | order-database commits `Order` aggregates, Marten event streams, and Wolverine outbox messages in a single ACID transaction; order-orchestration persists saga state in `finance-taskhub` (no PostgreSQL). | Uncommitted writes never publish Kafka events; Marten async projections recover automatically from the authoritative event stream. | order-database, order, order-item, adr-001-postgresql-order-system-of-record, adr-001-finance-persisted-order-saga |
| **Caching** | order-cache provides FusionCache L1/L2 (`2h` fail-safe) for Catalog lookups and dashboard reads. | Safe to invalidate individual cache keys without losing order or buyer state. | order-cache, adr-002-preserve-checkout-purchase-snapshot |
| **Messaging** | order-api emits UserCheckedOutIntegrationEvent, OrderStatusChangedToCompleteIntegrationEvent, and OrderStatusChangedToCancelIntegrationEvent partitioned by `OrderId`; consumes DeleteBasketCompleteCommand and DeleteBasketFailedCommand. | Exhausted retries route to `bookworm.{env}.ordering.dead-letter-queue`; notification-api delivery never proves authoritative order status. | `bookworm.{env}.ordering.user-checked-out`, `bookworm.{env}.finance.delete-basket-complete`, `bookworm.{env}.finance.delete-basket-failed`, `bookworm.{env}.ordering.dead-letter-queue` |
| **Concurrency & Idempotency** | `POST`/`PATCH` endpoints require `x-request-id` (`{METHOD}:{PATH}:{x-request-id}`, `3600s` TTL, returns `409 Conflict` on duplicate, cleared on exception or `>= 500`); `order-create:{userId}` (`60s` TTL) serializes buyer writes after gRPC lookups; inbound Kafka handlers use a `24h` Redis idempotency guard. | Concurrent checkout attempts for the same buyer fail fast with conflict/lock error; duplicate `x-request-id` does **not** replay a cached response body. | CreateOrder, user-checkout, adr-003-separate-order-status-from-finance-saga, adr-005-finance-separate-workflow-and-order-status |
## Safe Change & Verification Checklist
- Keep [[entity|order-item]] purchase prices (`PriceSale ?? Price`) immutable after checkout; allow read-time Catalog enrichment for display titles only.
- Preserve `x-request-id` idempotency, `order-create:{userId}` buyer write locking, and `24h` integration-event idempotency guards.
- Keep `Order.Status` transitions (`New` → `Completed` | `Cancelled`), soft deletion (`IsDeleted`), and `finance-taskhub` orchestration states strictly decoupled.
- Verify Pact contracts (`Ordering-Finance`, `Finance-Ordering`) and run `mise run format`, `mise run build`, and `mise run test`.
## Related Resources
- [[service|order-api]] — Authoritative Ordering REST API and Marten/Wolverine host
- [[service|order-orchestration]] — Durable Task Scheduler post-checkout saga
- [[flow|order-lifecycle]], [[flow|user-checkout]] — End-to-end checkout and lifecycle flows
- [[adr|adr-001-postgresql-order-system-of-record]], [[adr|adr-002-preserve-checkout-purchase-snapshot]], [[adr|adr-003-separate-order-status-from-finance-saga]], [[adr|adr-004-finance-bounded-scheduled-retries]]
- [[doc|platform/006-api-and-contracts]] — Consolidated HTTP, gRPC, and Kafka contracts
---
title: Order change checklist
summary: Pre-merge engineering checklist for Ordering API, Finance orchestration, persistence, and contract changes.
version: 1.0.0
type: engineering
order: 2
badges:
- content: Architecture
backgroundColor: green
textColor: green
---
## Purpose & Scope
This checklist defines the mandatory contract, lifecycle, persistence, concurrency, and verification checks for engineers modifying [[service|order-api]] or [[service|order-orchestration]] in the [[domain|ordering]] subdomain. Review it before merging changes to HTTP v1 routes, Kafka messages, [[container|order-database]] schemas, or Redis coordination.
## Visual Reference
The visual below contrasts authoritative [[service|order-api]] status transitions with independent [[service|order-orchestration]] saga states.
_Order Status and Finance Orchestration State Transitions_
## Core Invariants & Design Rules
- **Terminal status immutability:** Only a `New` [[entity|order]] can transition to `Completed` or `Cancelled`; terminal states can never reopen or switch.
- **Locked purchase snapshot:** Each [[entity|order-item]] stores `BookId`, a positive quantity, and checkout unit price (`PriceSale ?? Price`), with the order total equal to the sum of recorded line totals.
- **Authorization & rate-limit boundaries:** Preserve Microsoft Entra ID `customer` and `admin` policies (`ordering_read`, `ordering_write` scopes, admin-only delete and summary endpoints) and `PerUserRateLimit`.
- **Privacy & correlation:** Keep buyer street addresses and personal data out of routine logs and error payloads; correlate checkout and saga traces by `OrderId` and W3C trace context.
:::warning
**Do not conflate soft deletion or saga timeout with `Order.Status = Cancelled`.** [[command|DeleteBasketFailedCommand]] soft-deletes the order while leaving `Status` as `New`, and Finance timeout exhaustion cancels only the `finance-taskhub` orchestration.
:::
## Boundaries & Guarantees
| Concern | Strategy & Guarantee | Failure / Edge-Case Behavior | Related Resources |
| :------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Persistence** | EF Core migrations in order-database use `snake_case` identifiers; Marten event streams and Wolverine outbox/inbox tables commit atomically with `Order` writes. | Missing migrations or unaligned Marten event types break audit history (`GET /api/v1/orders/{id}/history`) and projections (`OrderSummary`, `OrderSummaryView`). | order-database, order, buyer |
| **Caching & Locks** | `order-create:{userId}` (`60s` TTL) guards PostgreSQL `Order` writes; `{METHOD}:{PATH}:{x-request-id}` (`3600s` TTL) deduplicates `POST`/`PATCH` calls. | Duplicate `x-request-id` returns `409 Conflict`; unhandled exceptions or `>= 500` responses clear the idempotency marker so clients can safely retry. | order-cache, CreateOrder |
| **Messaging** | Outbound events (UserCheckedOutIntegrationEvent, OrderStatusChangedToCompleteIntegrationEvent, OrderStatusChangedToCancelIntegrationEvent) and inbound basket-cleanup commands are partitioned by `OrderId` and Pact-verified. | Breaking CloudEvents schemas fail `Ordering-Finance` or `Finance-Ordering` Pact suites or route messages to `bookworm.{env}.ordering.dead-letter-queue`. | `bookworm.{env}.ordering.user-checked-out`, `bookworm.{env}.ordering.order-status-change-to-complete`, `bookworm.{env}.ordering.order-status-change-to-cancel`, `bookworm.{env}.ordering.dead-letter-queue` |
| **Concurrency** | Buyer-scoped distributed lock prevents concurrent checkout races; `24h` Redis idempotency guard deduplicates inbound Kafka commands. | Lock contention aborts the competing checkout attempt cleanly without creating duplicate orders. | order-api, order-orchestration, adr-003-separate-order-status-from-finance-saga |
## Safe Change & Verification Checklist
Update OpenAPI v1 metadata for any changes to `/api/v1/orders`, `/api/v1/buyers`, or
`/api/v1/dashboard`, and confirm compatibility with [[query|GetBasketGrpc]]
([[service|basket-api]]) and [[query|GetBooksGrpc]] ([[service|catalog-api]]).
Keep CloudEvents schemas partitioned by `OrderId` and verify both `Ordering-Finance` and
`Finance-Ordering` Pact contracts for checkout, completion, cancellation, and basket-cleanup
messages.
Confirm `New` → `Completed` | `Cancelled` immutability, checkout price snapshotting,
`snake_case` migrations in [[container|order-database]], Marten projection compatibility, and
`x-request-id` / `order-create:{userId}` guards.
Execute `mise run format`, `mise run build`, and `mise run test` to verify Ordering unit tests,
architecture tests, and Pact contract tests pass.
## Related Resources
- [[service|order-api]] — Authoritative Ordering REST API
- [[service|order-orchestration]] — Finance post-checkout saga
- [[command|CreateOrder]], [[command|CompleteOrder]], [[command|CancelOrder]], [[command|DeleteOrder]] — Order lifecycle commands
- [[query|GetOrder]], [[query|ListOrders]], [[query|GetBuyer]], [[query|ListBuyers]] — Order and buyer queries
- [[flow|order-lifecycle]], [[diagram|order-lifecycle]] — Order lifecycle flow and visual model
- [[doc|platform/006-api-and-contracts]] — Consolidated HTTP, gRPC, and Kafka contracts
---
title: Create and manage Orders
summary: Create an Order from the current basket, retrieve it, and request a valid lifecycle transition.
version: 1.0.0
type: guides
order: 1
badges:
- content: Guide
backgroundColor: teal
textColor: teal
---
**Audience & Outcome:** This guide is for frontend developers, API integrators, and backend engineers working with [[service|order-api]]. You will learn how checkout locks purchase snapshots, enforces idempotency, and governs one-way order status transitions.
[[service|order-api]] converts a customer's mutable shopping basket into a durable, price-locked purchase record in [[container|order-database]] and governs its commercial lifecycle (`New`, `Completed`, or `Cancelled`). Separating order acceptance from downstream basket cleanup and email notifications keeps checkout fast while preserving an authoritative audit trail.
## Context and motivation
Checkout crosses four bounded contexts: Shopping holds mutable pre-order items, Catalog owns live book metadata and pricing, Ordering records accepted commercial commitments, and Finance coordinates asynchronous post-checkout cleanup and notification requests.
Without strict boundaries at checkout, three failure modes occur:
- **Price drift:** Subsequent catalog discounts or price updates alter the total of an already accepted [[entity|order]].
- **Duplicate orders:** Retried HTTP requests after network timeouts or double-clicks create multiple purchases for the same checkout attempt.
- **Conflated status:** Callers assume a `201 Created` response confirms basket deletion, payment settlement, or email delivery—none of which occur synchronously inside [[service|order-api]].
## How it works
Customers interact with checkout through the Commerce microfrontend, which routes authenticated requests through the API Gateway to [[service|order-api]]. Every order endpoint requires a valid Microsoft Entra ID JWT (`customer` or `admin` role with `ordering_read`/`ordering_write` scopes) and applies per-user token-bucket rate limiting (`30` token limit, `20` tokens per `10s`, returning `429 Too Many Requests`).
The visual below shows synchronous checkout validation, order persistence, and asynchronous handoff to [[service|order-orchestration]].
### Order creation and snapshot locking
When a customer submits `POST /api/v1/orders` with a unique `x-request-id` header, [[service|order-api]] derives the [[entity|buyer]] strictly from the authenticated Entra ID token and stores a 1-hour idempotency marker in [[container|order-cache]]. Reusing the same `x-request-id` returns `409 Conflict` (unless an unhandled error clears the marker for safe retry).
[[service|order-api]] reads the [[entity|basket]] from [[service|basket-api]] over gRPC, resolves every [[entity|book]] via [[service|catalog-api]] gRPC, locks in each item's unit price, and calculates the order total from those recorded line totals.
A 1-minute distributed lock in [[container|order-cache]] serializes concurrent writes for the same buyer before persisting the [[entity|order]] in [[container|order-database]] with status `New` and publishing [[event|UserCheckedOutIntegrationEvent]] through the transactional outbox.
:::note
Returning `201 Created` confirms only that [[service|order-api]] accepted and persisted the order snapshot. Basket deletion and email notifications run asynchronously under [[service|order-orchestration]].
:::
### Order status lifecycle and event history
[[service|order-api]] enforces a strict one-way state machine for business status:
- **Terminal states:** Only a `New` order can transition to `Completed` or `Cancelled`, and both `PATCH` endpoints require a unique `x-request-id`. Neither terminal state can reopen or move to the other terminal state.
- **Downstream status events:** Successful transitions publish [[event|OrderStatusChangedToCompleteIntegrationEvent]] or [[event|OrderStatusChangedToCancelIntegrationEvent]] to Kafka so [[service|order-orchestration]] updates its workflow and requests the corresponding customer email.
- **Read and audit views:** Customers query orders scoped to their own buyer ID, while administrators can filter across buyers and inspect chronological audit history or point-in-time summaries.
- **Administrative soft delete:** Administrator deletion and [[command|DeleteBasketFailedCommand]] mark an order as soft-deleted, hiding it from standard queries without changing its business `Status` to `Cancelled`.
| Decision | Benefits | Costs and limits |
| :---------------------------------------------------------- | :------------------------------------------------------------------------------ | :------------------------------------------------------------------------------ |
| **Price snapshot at checkout** | Protects customers and financial records from retroactive catalog price edits | Catalog corrections require explicit customer reconciliation |
| **Asynchronous post-checkout handoff** | Keeps order creation latency low and isolates checkout from Basket/SMTP outages | `201 Created` does not confirm basket deletion or email delivery |
| **Irreversible terminal states (`Completed`, `Cancelled`)** | Produces a clean, auditable financial and event-sourced history | Correcting an accidental transition requires creating a new order |
| **Pre-execution idempotency marker** | Blocks duplicate submissions atomically without storing full HTTP payloads | Client timeouts after persistence leave a 1-hour marker without a cached replay |
**Rejected alternatives:**
- **Synchronous distributed transaction across Ordering, Basket, and Notification:** Couples order acceptance to non-critical email availability.
- **Referencing live Catalog prices on read:** Causes historical order totals to drift whenever book prices change.
- **Treating soft deletion as `Cancelled`:** Conflates operational cleanup failure with explicit commercial cancellation.
## Related documentation
- [[flow|user-checkout]] — End-to-end checkout flow across Shopping, Ordering, and Finance.
- [[flow|order-lifecycle]] — Order status transitions and downstream event propagation.
- [[adr|adr-002-preserve-checkout-purchase-snapshot]] — Why checkout locks unit prices and item details.
- [[adr|adr-003-separate-order-status-from-finance-saga]] — Separation between commercial status and Finance workflow state.
---
title: Understand Order and Finance status
summary: Distinguish the Order's business status from Finance's checkout saga, basket cleanup, and notification outcomes.
version: 1.0.0
type: guides
order: 2
badges:
- content: Guide
backgroundColor: teal
textColor: teal
---
**Audience & Outcome:** This guide is for support engineers, operators, and backend developers debugging post-checkout state. You will learn how [[service|order-api]] commercial status differs from [[service|order-orchestration]] workflow state and how to interpret cross-service outcomes.
BookWorm separates every checkout into two independent state machines: [[service|order-api]] owns the authoritative commercial status of an [[entity|order]] in [[container|order-database]], while [[service|order-orchestration]] coordinates post-checkout basket cleanup and notification commands using Azure Functions and Azure Durable Task Scheduler.
:::warning
Never infer an order's business status from basket contents, [[service|order-orchestration]] state, or delivered emails.
:::
## Context and motivation
After a customer submits checkout, three asynchronous activities occur outside the original HTTP request: clearing the customer's shopping basket, tracking retry timers if cleanup stalls, and sending lifecycle emails. When a cleanup command fails, a retry timer expires, or a customer receives a cancellation email, support engineers can mistake those operational signals for changes to the commercial order record.
Keeping Ordering's domain model strictly isolated from Finance's workflow engine prevents transient infrastructure failures or retry exhaustion from corrupting commercial order records.
## How it works
[[service|order-api]] publishes [[event|UserCheckedOutIntegrationEvent]] when an order is created, triggering [[service|order-orchestration]]. From that point onward, the two services maintain independent state stores and communicate exclusively over Kafka.
The visual below shows how [[service|order-api]], [[service|order-orchestration]], [[service|basket-api]], and [[service|notification-api]] exchange events and commands across separate state boundaries.
### Two independent state models
| Dimension | [[service\|order-api]] ([[container\|order-database]]) | [[service\|order-orchestration]] (Durable Task Scheduler) |
| :------------------ | :--------------------------------------------------------------- | :------------------------------------------------------------------- |
| **Authority** | Authoritative commercial order status and purchase snapshot | Post-checkout workflow coordination and compensation only |
| **Status values** | `New`, `Completed`, `Cancelled` (plus separate soft-delete flag) | `Placed`, `Completed`, `Cancelled`, `BasketDeletionFailed`, `Failed` |
| **Persisted store** | PostgreSQL via EF Core + Marten event store | Azure Durable Task Scheduler (`finance-taskhub`) |
| **How to inspect** | Orders REST endpoints (`GET /api/v1/orders/{id}`) | Durable Task orchestration custom status |
### Interpreting cross-service outcomes
- **Basket deletion succeeds:** [[service|basket-api]] publishes [[event|BasketDeletedCompleteIntegrationEvent]]. [[service|order-orchestration]] records completion and sends [[command|DeleteBasketCompleteCommand]] to [[service|order-api]], which logs the event and leaves the order status `New`.
- **Basket deletion fails:** [[service|basket-api]] publishes [[event|BasketDeletedFailedIntegrationEvent]]. [[service|order-orchestration]] marks its orchestration `BasketDeletionFailed` and sends [[command|DeleteBasketFailedCommand]] to [[service|order-api]], which soft-deletes the matching order without changing `Status` to `Cancelled`.
- **Finance retry timers expire:** If an open orchestration exhausts its configured retry window (`30m` timeout, `3` attempts), [[service|order-orchestration]] marks its own state `Cancelled` and publishes [[command|CancelOrderCommand]] to [[service|notification-api]]. It never cancels the commercial order in [[service|order-api]], so Ordering can still report `New`.
- **Explicit order completion or cancellation:** When [[service|order-api]] accepts a completion or cancellation request, it publishes [[event|OrderStatusChangedToCompleteIntegrationEvent]] or [[event|OrderStatusChangedToCancelIntegrationEvent]]. [[service|order-orchestration]] transitions accordingly and publishes [[command|CompleteOrderCommand]] or [[command|CancelOrderCommand]].
- **Customer email sent or missing:** [[service|notification-api]] is a stateless delivery worker. Sending or skipping an email never proves or alters an order's business status.
| Decision | Benefits | Costs and limits |
| :----------------------------------------------------- | :------------------------------------------------------------------------------------------ | :-------------------------------------------------------------------------------------- |
| **Independent Durable Functions orchestration** | Isolates long-running timers, retries, and compensations from [[container\|order-database]] | Finance orchestration status can diverge from Ordering `Status` after retry exhaustion |
| **Soft deletion on explicit basket-cleanup failure** | Removes broken checkouts from active listings without recording a false cancellation | Operators must inspect both Ordering visibility and Finance status for the full picture |
| **Bounded retry window (`3` attempts, `30m` timeout)** | Prevents orphaned orchestrations from running indefinitely | Transient outages longer than the retry window require operational investigation |
**Rejected alternatives:**
- **Letting Finance mutate Ordering `Status` on timeout:** Infrastructure timeout exhaustion is not an explicit commercial cancellation.
- **Persisting Finance saga state in PostgreSQL:** Durable Task Scheduler natively manages durable timers and replay-safe orchestration history for Azure Functions.
## Related documentation
- [[flow|order-lifecycle]] — Order status transitions and downstream event propagation.
- [[adr|adr-005-finance-separate-workflow-and-order-status]] — Why Finance workflow outcomes stay separate from Order status.
- [[doc|arc42]] — System-wide architecture overview.
---
title: Checkout basket cleanup stalled or failed
summary: Investigate Finance basket-cleanup retries without confusing saga progress with Order status.
version: 1.0.0
type: runbooks
order: 1
badges:
- content: Runbook
backgroundColor: orange
textColor: orange
---
## Trigger / Symptom & Blast Radius
An [[entity|order]] exists in [[service|order-api]] but the customer's [[entity|basket]] remains populated, [[service|order-orchestration]] has not reported a cleanup outcome, a cancellation email arrived for a `New` order, or an order disappeared after a basket-deletion failure. Blast radius is post-checkout cleanup and notification consistency; never infer commercial order status from basket contents, Finance state, or emails.
Do not manually transition orders in [[service|order-api]] or edit [[container|order-database]]
rows to match a timed-out [[service|order-orchestration]] state. Do not copy customer emails or
PII into incident tickets.
## Pre-Flight Check
Query the authoritative order status in [[service|order-api]] and check [[service|order-orchestration]] container health:
```bash
curl -sS -H "Authorization: Bearer " "https:///ordering/api/v1/orders/"
az containerapp show --name --resource-group --query "properties.runningStatus" -o tsv
```
## Quick Recovery Procedure
Inspect OpenTelemetry traces and logs for `` across [[service|order-api]] and [[service|order-orchestration]]:
Confirm [[event|UserCheckedOutIntegrationEvent]] was published to `bookworm.{env}.ordering.user-checked-out`.
Inspect the Durable Task orchestration custom status (`OrderId`, `Status`, `BasketDeleted`, `TimeoutRetryCount`, `FailureReason`).
Check consumer lag and DLQ depth across `bookworm.{env}.finance.place-order`, `bookworm.{env}.basket.delete-complete`, `bookworm.{env}.basket.delete-failed`, and per-service DLQs (`bookworm.{env}.basket.dead-letter-queue`, `bookworm.{env}.ordering.dead-letter-queue`, `bookworm.{env}.notification.dead-letter-queue`).
**`BasketDeleted: true` and `Status: Placed`:** Cleanup succeeded; [[service|order-api]] keeps the order `New` until explicit completion or cancellation.
**`Status: BasketDeletionFailed`:** [[service|order-api]] soft-deleted the order upon receiving [[command|DeleteBasketFailedCommand]] without changing `Status` to `Cancelled`.
**Retry timer exhausted (`3` attempts, `30m` each):** Finance marked its own state `Cancelled` and sent [[command|CancelOrderCommand]] to [[service|notification-api]] without canceling the commercial order in [[service|order-api]].
Restore any unhealthy dependency ([[service|basket-api]], [[container|basket-database]], [[service|order-orchestration]], or Kafka) so pending messages drain naturally.
## Verification
Confirm the authoritative order endpoint returns HTTP `200` (for active orders) and DLQ depth has stopped growing:
```bash
curl -sS -o /dev/null -w "%{http_code}\n" -H "Authorization: Bearer " "https:///ordering/api/v1/orders/"
```
Expected output:
```text
200
```
## Rollback / Escalation
- **Rollback:** No manual state rollback is required once broker/service connectivity is restored; consumers drain queued events idempotently.
- **Escalation:** Escalate repeated [[command|PlaceOrderCommand]] dispatches or soft-delete discrepancies to [[team|commerce-fulfillment-team]] with `` and orchestration timestamps.
| Symptom | Cause | Fix |
| :----------------------------------------------------------- | :--------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------- |
| Order is `New`, basket still populated, retries incrementing | [[service\|basket-api]] or Redis unavailable, or message in Basket DLQ | Restore dependency and follow the Basket cleanup failure runbook |
| Cancellation email sent, order still `New` | Finance exhausted 30m retry loop without canceling Ordering | Confirm commercial intent with customer; do not assume order is cancelled |
| Order returns `404` after checkout | Basket deletion failed and triggered soft delete | Confirm `BasketDeletionFailed` in Finance and escalate to [[team\|commerce-fulfillment-team]] |
## Related documentation
- [[flow|user-checkout]] — End-to-end checkout and cleanup flow.
- [[adr|adr-005-finance-separate-workflow-and-order-status]] — Why Finance saga state is separate from Order status.
---
title: Order creation conflict or failure
summary: Safely investigate failed or repeated Order creation requests and Redis coordination issues.
version: 1.0.0
type: runbooks
order: 2
badges:
- content: Runbook
backgroundColor: orange
textColor: orange
---
## Trigger / Symptom & Blast Radius
`POST /api/v1/orders` returns `409 Conflict`, times out with an ambiguous outcome, fails during concurrent buyer checkouts, or encounters [[container|order-cache]] connectivity errors. Blast radius is active checkout submissions; committed orders in [[container|order-database]] remain safe.
Never flush [[container|order-cache]] or bulk-delete idempotency or lock keys during an incident.
Clearing Redis removes active duplicate-request markers and buyer write locks, risking duplicate
orders across concurrent checkouts.
## Pre-Flight Check
Before retrying any checkout, query [[service|order-api]] to verify whether the order was already persisted in [[container|order-database]], and check Redis responsiveness:
```bash
curl -sS -H "Authorization: Bearer " "https:///ordering/api/v1/orders?buyerId=&pageIndex=1&pageSize=10"
redis-cli -u "" PING
```
## Quick Recovery Procedure
Record ``, `x-request-id`, UTC timestamp, ``, and HTTP status code. Exclude street addresses, emails, and other PII from incident tickets.
Stream [[service|order-api]] logs filtered by `` and ``:
```bash
az containerapp logs show --name --resource-group --tail 150
```
**`409 Conflict`:** A 1-hour idempotency marker already exists for ``. If the order exists in Step 1, return its `orderId`; if no order exists, verify whether the original request is still in flight before retrying.
**Concurrent write lock error:** Another checkout for `` holds the 1-minute buyer write lock. Wait for it to finish and re-query `GET /api/v1/orders`.
**`400 Bad Request`:** Client omitted the required `x-request-id` header.
**`429 Too Many Requests`:** Per-user rate limit exceeded; honor `Retry-After`.
If logs show Redis timeouts, restore Azure Managed Redis connectivity without flushing keys, then re-verify [[container|order-database]] before advising the customer to retry.
## Verification
Confirm [[service|order-api]] responds with HTTP `200` and only a single order exists for the checkout attempt:
```bash
curl -sS -o /dev/null -w "%{http_code}\n" -H "Authorization: Bearer " "https:///ordering/api/v1/orders?buyerId=&pageIndex=1&pageSize=1"
```
Expected output:
```text
200
```
## Rollback / Escalation
- **Rollback:** Do not manually delete persisted orders; use standard administrative cancellation (`PATCH /api/v1/orders/{id}/cancel`) if a duplicate order was created externally.
- **Escalation:** Escalate persistent Redis outages to [[team|platform-engineering-team]]; escalate idempotency or lock bugs to [[team|commerce-fulfillment-team]].
## Related documentation
- [[flow|user-checkout]] — Checkout validation and snapshot locking.
- [[adr|adr-001-postgresql-order-system-of-record]] — Authoritative role of [[container|order-database]].
---
title: Engineering Invariants and Quirks
summary: Durable Functions saga keying, LIFO compensation semantics, and Kafka trigger error handling for Order Orchestration.
version: 1.0.0
---
Engineering invariants and known contract quirks for [[service|order-orchestration]].
## Saga & Compensation Invariants
- **Deterministic instance keying:** Consumes [[event|UserCheckedOutIntegrationEvent]] and starts a Durable Functions orchestration keyed by `OrderId` so duplicate event deliveries do not spawn parallel sagas.
- **LIFO compensation:** Dispatches [[command|PlaceOrderCommand]] to [[service|basket-api]] and [[service|notification-api]]. If [[service|basket-api]] emits [[event|BasketDeletedFailedIntegrationEvent]], the saga issues [[command|DeleteBasketFailedCommand]] to [[service|order-api]] to compensate; otherwise [[event|BasketDeletedCompleteIntegrationEvent]] advances the workflow via [[command|DeleteBasketCompleteCommand]].
- **Order lifecycle notifications:** Consumes [[event|OrderStatusChangedToCompleteIntegrationEvent]] and [[event|OrderStatusChangedToCancelIntegrationEvent]] to dispatch [[command|CompleteOrderCommand]] and [[command|CancelOrderCommand]] respectively.
- **Nullable contact tolerance:** Customer `email` and `fullName` may be `null` on checkout events; the saga still executes basket cleanup and delegates email-skipping to [[service|notification-api]].
## Runtime & Dead-Letter Behavior
:::note
[[service|order-orchestration]] runs on Azure Functions Kafka triggers rather than Wolverine's Kafka transport. Failed trigger executions are retried by the Functions host and recorded in the Durable Task Hub rather than routed to a dedicated Finance Kafka dead-letter topic.
:::
---
title: Durable Orchestration Inspection and Termination
summary: CLI-first runbook to inspect, diagnose, or terminate stuck checkout saga instances in Order Orchestration.
version: 1.0.0
---
Operational runbook for [[service|order-orchestration]] when a checkout saga stalls or enters a failed state.
Use the Azure Functions Durable Task status endpoint (instance ID equals `OrderId`):
```bash
curl -sS -H "x-functions-key: $FUNCTIONS_MASTER_KEY" \
"$ORDER_ORCHESTRATION_URL/runtime/webhooks/durabletask/instances/$ORDER_ID?showHistory=true" | jq '{runtimeStatus, customStatus, createdTime, lastUpdatedTime}'
```
If an instance is permanently stuck after manual remediation of [[service|order-api]] and [[service|basket-api]], terminate it cleanly:
```bash
curl -sS -X POST -H "x-functions-key: $FUNCTIONS_MASTER_KEY" \
"$ORDER_ORCHESTRATION_URL/runtime/webhooks/durabletask/instances/$ORDER_ID/terminate?reason=ManualOperatorIntervention"
```
---
title: Engineering Invariants and Quirks
summary: Transactional outbox guarantees, idempotency locks, Marten event-store rules, and known runtime contract quirks for Order API.
version: 1.0.0
---
Engineering invariants and known contract quirks for [[service|order-api]].
## Persistence & Messaging Invariants
- **Transactional outbox:** Order state mutations in PostgreSQL and outgoing integration events ([[event|UserCheckedOutIntegrationEvent]], [[event|OrderStatusChangedToCompleteIntegrationEvent]], [[event|OrderStatusChangedToCancelIntegrationEvent]]) commit atomically via the Marten + Wolverine transactional outbox.
- **Idempotency & distributed locking:** Mutating order endpoints require an `x-request-id` header tracked in Redis (`3600s` TTL, returning `409 Conflict` on replay and cleared on `5xx`). [[command|CreateOrder]] additionally acquires a `1`-minute per-buyer Redis lock (`order-create:{userId}`).
- **Optimistic concurrency:** Status transitions ([[command|CompleteOrder]], [[command|CancelOrder]]) enforce event-stream concurrency and return `412 Precondition Failed` on conflicting concurrent writes.
- **Buyer-linked basket mapping:** [[event|UserCheckedOutIntegrationEvent]] populates `basketId` with the order's `BuyerId`; downstream consumers must not treat `basketId` as an independently resolved [[service|basket-api]] record.
## Known Contract & Runtime Quirks
:::warning
The following runtime behaviors diverge from idealized OpenAPI expectations and are tracked in [[doc|arc42/11-risks-and-technical-debt]].
:::
| Area | Command / Operation | Observed Behavior |
| :------------------------ | :--------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Empty basket checkout** | [[command\|CreateOrder]] | [[query\|GetBasketGrpc]] returns an empty response rather than `NotFound` when no basket exists; `CreateOrder` does not reject an empty item list and can persist an empty order (`201 Created`). |
| **Duplicate buyer** | [[command\|CreateBuyer]] | Creating a buyer with an existing identifier surfaces a database duplicate-key violation as `500 Internal Server Error` instead of `409 Conflict`. |
| **Buyer deletion FK** | [[command\|DeleteBuyer]] | Deleting a buyer that still owns orders triggers an `ON DELETE SET NULL` foreign-key constraint conflict against non-nullable `buyer_id`, failing at runtime. |
| **Non-`New` transition** | [[command\|CancelOrder]], [[command\|CompleteOrder]] | Customers targeting their own already-`Cancelled` or `Completed` order receive `500 Internal Server Error`, whereas administrators receive `404 Not Found`. |
| **`404` content-type** | Resource-not-found responses | OpenAPI metadata declares `application/problem+json`, while runtime `404 Not Found` responses return `application/json` with `{ "detail": "..." }`. |
---
title: Ordering DLQ Inspection and Replay
summary: CLI-first procedure to inspect and safely replay failed messages from the Ordering dead-letter queue.
version: 1.0.0
---
Operational runbook for inspecting and replaying failed messages in [[channel|bookworm.{env}.ordering.dead-letter-queue]] for [[service|order-api]].
:::warning
Never replay poison records with invalid UUIDs or schema mismatches before fixing or filtering the payload. Always verify current [[entity|order]] status first.
:::
Read recent records and CloudEvents headers (`messagetype`, `requestid`, exception headers) from the Ordering DLQ:
```bash
kcat -C -b "$KAFKA_BOOTSTRAP" -t "bookworm.${ENV}.ordering.dead-letter-queue" -o -20 -e -f '%t [%p] offset=%o key=%k headers=%h\n%s\n---\n'
```
Confirm whether the target order is still in `New` status or has already transitioned (`Completed` or `Cancelled`) via [[query|GetOrder]] so compensation is not applied twice.
For transient failures (database or broker timeout) on [[command|DeleteBasketCompleteCommand]] or [[command|DeleteBasketFailedCommand]], re-produce the validated JSON payload with its original `OrderId` partition key to the target topic (`bookworm.${ENV}.finance.delete-basket-complete` or `bookworm.${ENV}.finance.delete-basket-failed`).
---
title: Platform integration boundaries
summary: Scheduling, outbox durability, idempotent notification delivery, and failure boundaries across Platform services.
version: 1.0.0
type: engineering
order: 1
badges:
- content: Architecture
backgroundColor: green
textColor: green
---
## Purpose & Scope
This document defines the runtime ownership, transactional outbox guarantees, idempotency semantics, and failure boundaries for [[service|scheduler-service]] and [[service|notification-api]] in the [[domain|platform]] subdomain. Neither service is exposed through the public API Gateway; use this guide when modifying scheduled jobs, Kafka consumers, or SMTP delivery pipelines.
## Visual Reference
The visual below shows how [[service|scheduler-service]] triggers [[service|catalog-ingestion]] via Kafka and how [[service|notification-api]] consumes order commands from [[service|order-orchestration]] to dispatch emails.
_Platform Scheduling, Outbox, and Notification Delivery Boundaries_
## Core Invariants & Design Rules
- **Strict storage isolation:** [[service|scheduler-service]] reads and writes only [[container|scheduler-database]] (Quartz persistent store with 30-day / 100k execution history and Wolverine outbox/inbox). It never queries or mutates Catalog, Ordering, or Qdrant stores. [[service|notification-api]] is a stateless worker with **no SQL database**, using Redis solely for FusionCache and `24h` integration-event idempotency.
- **Trigger completion vs. downstream completion:** A completed vector-batch job proves only that [[event|ProcessVectorBatchIntegrationEvent]] was durably enqueued via the PostgreSQL outbox to [[channel|scheduler.process-vector-batch]]—never that [[service|catalog-ingestion]] finished updating [[container|catalog-vector]].
- **SMTP handoff vs. business status:** [[service|notification-api]] renders email templates and hands payloads to [[service|sendgrid-api]] (or Mailpit in development) over SMTP port `587`. SMTP acceptance proves only relay handoff, never inbox delivery or authoritative order status.
- **Blank recipient safety:** Commands with null, empty, or whitespace recipient email addresses are skipped cleanly without throwing or poisoning the consumer queue.
- **Confidentiality in telemetry:** Customer email addresses and rendered HTML bodies must never appear in logs or traces; emit only order IDs, message IDs, counts, timestamps, and sanitized exception types.
:::warning
**Preserve unprefixed topic routing for `scheduler.process-vector-batch`.** [[service|catalog-ingestion]] binds its Kafka trigger directly to the unprefixed topic name [[channel|scheduler.process-vector-batch]]. Adding an environment prefix or renaming the topic breaks scheduled vector indexing silently.
:::
## Boundaries & Guarantees
| Concern | Strategy & Guarantee | Failure / Edge-Case Behavior | Related Resources |
| :------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Persistence** | scheduler-service persists Quartz triggers and Wolverine outbox/inbox in scheduler-database; notification-api persists no domain state. | scheduler-service outbox guarantees at-least-once publication after job commit; notification-api relies on Kafka offsets and Redis idempotency. | scheduler-database, adr-001-postgresql-quartz-persistence, adr-002-notification-postgresql-email-outbox |
| **Caching & Idempotency** | notification-api wraps PlaceOrderCommand, CompleteOrderCommand, and CancelOrderCommand handlers in a `24h` Redis integration-event idempotency guard keyed by `message.Id` and handler name. | Duplicate Kafka deliveries of the same `message.Id` are skipped; distinct retried commands from order-orchestration carry new message IDs and are processed independently. | PlaceOrderCommand, CompleteOrderCommand, CancelOrderCommand, adr-001-notification-kafka-command-intake |
| **Messaging & Resilience** | notification-api applies a Polly resilience pipeline (`CircuitBreaker`, exponential `Retry` with jitter, `30s` `Timeout`) around SMTP submission, plus Wolverine retries (`50ms / 250ms / 1s` with full jitter). | Messages exhausting both Polly and Wolverine retries route to `bookworm.{env}.notification.dead-letter-queue` for inspection and replay. | `bookworm.{env}.finance.place-order`, `bookworm.{env}.finance.complete-order`, `bookworm.{env}.finance.cancel-order`, `bookworm.{env}.notification.dead-letter-queue` |
| **Concurrency & Misfires** | Vector-batch jobs enforce `[DisallowConcurrentExecution]` and UTC `FireOnceNow` misfire handling; Dashboard Agent restricts remote execution to registered Platform job types. | Missed intervals coalesce into a single catch-up run rather than replaying every missed tick; overlapping executions are blocked at the Quartz lock level. | scheduler-service, ProcessVectorBatchIntegrationEvent, adr-002-scheduler-invocation-boundary, adr-003-idempotent-misfire-aware-jobs |
## Safe Change & Verification Checklist
- Keep authoritative business state in its owning bounded context; never treat SMTP handoff or Notification telemetry as order status.
- Preserve unprefixed topic routing on [[channel|scheduler.process-vector-batch]] and `OrderId` partitioning on Finance notification commands.
- Keep SMTP credentials, HMAC keys, and connection strings in runtime secrets/parameters—never in source control or job definitions.
- Ensure customer email addresses and rendered email bodies remain redacted from logs and error payloads.
- Run `mise run format`, `mise run build`, and `mise run test` to verify Platform unit tests and Pact contracts (`Notification-Finance`, `Catalog-Scheduler`).
## Related Resources
- [[service|scheduler-service]] — Quartz.NET scheduler and outbox producer
- [[service|notification-api]] — Stateless Kafka-to-SMTP notification worker
- [[service|sendgrid-api]] — External SMTP relay provider
- [[flow|notification-delivery]], [[flow|product-ingestion]] — End-to-end delivery and ingestion workflows
- [[adr|adr-001-postgresql-quartz-persistence]], [[adr-003-idempotent-misfire-aware-jobs]], [[adr-003-notification-smtp-provider-boundary]], [[adr-005-notification-confidential-data-boundary]]
- [[doc|platform/006-api-and-contracts]] — Consolidated HTTP, gRPC, and Kafka contracts
---
title: Scheduled work and email notifications
summary: A practical guide to Platform schedules, target-system ownership, and the durable email workflow.
version: 1.0.0
type: guides
order: 1
badges:
- content: Guide
backgroundColor: teal
textColor: teal
---
**Audience & Outcome:** This guide is for platform engineers and operators working with [[service|scheduler-service]] and [[service|notification-api]]. You will learn how recurring jobs trigger catalog indexing and how stateless transactional email delivery guarantees reliability without a notification database.
BookWorm's Platform subdomain separates recurring time-based orchestration from transactional email dispatch into two independent services: [[service|scheduler-service]] runs recurring Quartz.NET jobs backed by [[container|scheduler-database]], while [[service|notification-api]] operates as a stateless Kafka and SMTP worker with no database.
## Context and motivation
Two distinct operational needs exist across BookWorm's business domains:
- **Periodic batch triggers:** Catalog books change continuously, and generating embeddings plus updating [[container|catalog-vector]] is more efficient in scheduled batches than inside synchronous HTTP book writes.
- **Decoupled customer emails:** Order creation, completion, and cancellation should never block on external SMTP server latency or fail when an email provider is temporarily unreachable.
Separating these capabilities into dedicated Platform services keeps domain services focused on business invariants while avoiding cross-domain database coupling.
## How it works
The visual below illustrates the two independent Platform pipelines—[[service|scheduler-service]] triggering [[service|catalog-ingestion]] on a UTC cadence, and [[service|notification-api]] delivering order emails over SMTP.
### Recurring work in Scheduler
[[service|scheduler-service]] persists Quartz state, 30-day execution history, and its transactional outbox in [[container|scheduler-database]]. **Quartz Dashboard** (exposed at `/quartz` behind Microsoft Entra ID `admin` role) provides operational visibility.
| Job | Cron (UTC) | Cadence | Behavior |
| :---------------------- | :--------------- | :--------------- | :--------------------------------------------------------------------------------------------------------------------- |
| `ProcessVectorBatchJob` | `0 0/5 * * * ?` | Every 5 minutes | Non-concurrent; publishes [[event\|ProcessVectorBatchIntegrationEvent]] to [[channel\|scheduler.process-vector-batch]] |
| `HeartbeatJob` | `0/30 * * * * ?` | Every 30 seconds | Emits structured heartbeat logs and OpenTelemetry telemetry |
Both jobs use `FireOnceNow` misfire handling so a missed run triggers one immediate catch-up execution rather than replaying every missed interval. When `ProcessVectorBatchJob` succeeds, [[service|scheduler-service]] guarantees only that the Kafka event was published. [[service|catalog-ingestion]] independently consumes [[channel|scheduler.process-vector-batch]] to update [[container|catalog-vector]].
### Stateless email delivery in Notification
[[service|notification-api]] consumes Finance's Kafka order commands (`bookworm.{env}.finance.place-order`, `bookworm.{env}.finance.complete-order`, and `bookworm.{env}.finance.cancel-order`), partitioned by `OrderId`:
Each handler checks a 24-hour Redis idempotency guard keyed by message ID and handler name, skipping duplicate deliveries. Messages with blank or whitespace recipient emails return cleanly without error.
The worker renders the MJML order email template into HTML and delivers it over SMTP (Mailpit locally, [[service|sendgrid-api]] in Azure) through a resilience pipeline with circuit breaking, exponential retry with jitter, and a 30-second timeout.
If transient SMTP failures exhaust both resilience and broker retries, failed messages route to `bookworm.{env}.notification.dead-letter-queue` for operator investigation and replay.
:::note
SMTP acceptance proves only that the relay server accepted the message; it never proves inbox delivery or commercial order status.
:::
| Decision | Benefits | Costs and limits |
| :------------------------------------------------------------- | :-------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------- |
| **Stateless Notification worker (Kafka + Redis + DLQ)** | Removes a database, migrations, and hourly resend jobs; uses native Kafka durability | Replaying failed emails requires Kafka DLQ tooling rather than SQL queries |
| **At-least-once Kafka delivery with message ID deduplication** | Prevents lost order emails during transient network or SMTP outages | Ambiguous SMTP timeouts or reissued commands can still produce duplicate emails |
| **Kafka event trigger from Scheduler to Catalog Ingestion** | Eliminates synchronous HTTP coupling and token management between Scheduler and Catalog | Operators must inspect both Scheduler history and [[container\|catalog-database]] to confirm indexing |
| **`FireOnceNow` misfire instruction** | Prevents catch-up storms after Scheduler downtime | Intermediate missed windows are skipped |
**Rejected alternatives:**
- **PostgreSQL email outbox with hourly Quartz resend jobs:** Retired because maintaining a dedicated database and sweeping jobs duplicated Kafka's native durable log, retry, and dead-letter queue capabilities.
- **Direct HTTP calls from Scheduler to Catalog:** Coupled ingestion availability directly to Scheduler execution.
## Related documentation
- [[flow|notification-delivery]] — End-to-end notification delivery flow.
- [[flow|product-ingestion]] — End-to-end scheduled vector ingestion flow.
- [[service|scheduler-service]] — Detailed Scheduler service reference.
- [[service|notification-api]] — Detailed Notification service reference.
---
title: Notification delivery backlog
summary: Diagnose and safely recover when unsent email records accumulate or stop progressing.
version: 1.0.0
type: runbooks
order: 1
badges:
- content: Runbook
backgroundColor: orange
textColor: orange
---
## Trigger / Symptom & Blast Radius
Order emails are delayed, Kafka consumer lag grows on Finance order command topics, messages accumulate in `bookworm.{env}.notification.dead-letter-queue`, or [[service|notification-api]] logs SMTP or Redis failures. Blast radius is transactional email delivery only; commercial order state in [[service|order-api]] is unaffected.
Never flush BookWorm's shared Redis instance during an outage, and never copy recipient email
addresses or rendered HTML bodies into incident tickets.
## Pre-Flight Check
Verify [[service|notification-api]] container status and stream recent logs in ``:
```bash
az containerapp show --name --resource-group --query "properties.runningStatus" -o tsv
az containerapp logs show --name --resource-group --tail 150
```
## Quick Recovery Procedure
Inspect consumer lag for the `notification` consumer group across `bookworm.{env}.finance.place-order`, `bookworm.{env}.finance.complete-order`, and `bookworm.{env}.finance.cancel-order`, plus depth on `bookworm.{env}.notification.dead-letter-queue`. Record only lag counts, timestamps, and order/message IDs.
Check [[service|notification-api]] logs for:
**Circuit breaker open / 30s timeouts:** [[service|sendgrid-api]] (or local Mailpit) unreachable or throttling on port `587`.
**SMTP auth failures:** Invalid SMTP username, password, or unverified sender address.
**Redis errors:** Idempotency store unreachable (24-hour deduplication guard).
**Blank recipient email:** Commands with blank/whitespace email addresses are intentionally skipped without error or DLQ entry.
Fix the failing dependency (SMTP credentials/egress, Redis connectivity, or Kafka broker). Active lag drains automatically. For messages in `bookworm.{env}.notification.dead-letter-queue`, verify provider delivery logs first to minimize duplicates after ambiguous SMTP timeouts, then replay recoverable messages to their original Finance topic.
## Verification
Confirm consumer lag on all three Finance command topics trends to `0`, no new messages enter `bookworm.{env}.notification.dead-letter-queue`, and container logs show successful SMTP handoffs:
```bash
az containerapp logs show --name --resource-group --tail 50
```
## Rollback / Escalation
- **Rollback:** If a recent [[service|notification-api]] deployment introduced template rendering or SMTP config regressions, roll back to the previous Container App revision in ``.
- **Escalation:** Escalate SMTP provider/credential issues to [[team|platform-engineering-team]]; escalate template or handler defects to [[team|platform-engineering-team]].
## Related documentation
- [[flow|notification-delivery]] — End-to-end notification delivery flow.
- [[adr|adr-003-notification-smtp-provider-boundary]] — SMTP provider boundary and resilience.
---
title: Scheduled job failure
summary: Investigate missed, failing, or apparently successful jobs in the Platform Scheduler.
version: 1.0.0
type: runbooks
order: 2
badges:
- content: Runbook
backgroundColor: orange
textColor: orange
---
## Trigger / Symptom & Blast Radius
A Quartz.NET job in [[service|scheduler-service]] misses its UTC schedule, appears paused or failed in Quartz Dashboard (`/quartz`), or reports success while [[service|catalog-ingestion]] makes no vector indexing progress. Blast radius is limited to scheduled background jobs (5-minute vector batching and 30-second heartbeat); transactional APIs and email notifications are unaffected.
Never edit [[container|catalog-database]] rows through [[container|scheduler-database]], and never
copy connection strings or credentials into incident notes.
## Pre-Flight Check
Verify [[service|scheduler-service]] container status, stream logs, and check pending vector queue depth in [[container|catalog-database]]:
```bash
az containerapp show --name --resource-group --query "properties.runningStatus" -o tsv
```
```sql
SELECT COUNT(*) AS pending_count, MIN(updated_at) AS oldest_updated_at FROM pending_vector_updates;
```
## Quick Recovery Procedure
In local Aspire runs, [[service|scheduler-service]] requires an explicit manual start in the Aspire Dashboard. In all environments, open `/quartz` (requires Entra ID `admin` role) and confirm triggers for `ProcessVectorBatchJob` (every 5 minutes UTC) and `HeartbeatJob` (every 30 seconds UTC) are in `NORMAL` state rather than `PAUSED`, `ERROR`, or `BLOCKED`.
If jobs fail with execution exceptions, inspect [[service|scheduler-service]] logs for [[container|scheduler-database]] or Kafka connectivity errors publishing [[event|ProcessVectorBatchIntegrationEvent]] to [[channel|scheduler.process-vector-batch]]:
```bash
az containerapp logs show --name --resource-group --tail 100
```
A successful job run confirms only that the Kafka trigger was published. Check consumer lag on [[channel|scheduler.process-vector-batch]] and inspect [[service|catalog-ingestion]] logs for advisory lock contention, Microsoft Foundry embedding errors, or [[container|catalog-vector]] errors.
Restore [[container|scheduler-database]], Kafka, or downstream [[service|catalog-ingestion]] dependencies. Resume any paused trigger in `/quartz` under approved change procedures and allow the next 5-minute cycle (or `FireOnceNow` catch-up) to drain the queue.
## Verification
Confirm `HeartbeatTrigger` and `ProcessVectorBatchTrigger` show `Succeeded` runs in `/quartz` and `pending_count` in [[container|catalog-database]] trends toward `0`:
```sql
SELECT COUNT(*) AS pending_count FROM pending_vector_updates;
```
Expected output:
```text
pending_count
---------------
0
```
## Rollback / Escalation
- **Rollback:** Pause the affected trigger in `/quartz` if a downstream dependency is overwhelmed, then resume once healthy.
- **Escalation:** Escalate Scheduler, [[container|scheduler-database]], or Kafka issues to [[team|platform-engineering-team]]; escalate ingestion/embedding issues to [[team|platform-engineering-team]].
## Related documentation
- [[flow|product-ingestion]] — End-to-end scheduled vector ingestion flow.
- [[adr|adr-001-postgresql-quartz-persistence]] — Quartz persistence in [[container|scheduler-database]].
---
title: Notification DLQ Inspection and Replay
summary: CLI-first procedure to inspect and safely replay failed email delivery commands from the Notification dead-letter queue.
version: 1.0.0
---
Operational runbook for [[channel|bookworm.{env}.notification.dead-letter-queue]] owned by [[service|notification-api]].
:::warning
Replaying [[command|PlaceOrderCommand]] to the shared [[channel|bookworm.{env}.finance.place-order]] topic will also trigger [[service|basket-api]]. Verify whether the customer already received the email before replaying, and check the `24`-hour Redis deduplication key (`id`).
:::
```bash
kcat -C -b "$KAFKA_BOOTSTRAP" -t "bookworm.${ENV}.notification.dead-letter-queue" -o -20 -e -f '%t [%p] offset=%o key=%k headers=%h\n%s\n---\n'
```
Confirm SMTP relay connectivity and credentials are healthy before replaying messages. Blank or
`null` `email` payloads do not require replay.
For transient SMTP outages on [[command|CompleteOrderCommand]] or
[[command|CancelOrderCommand]], re-publish to `bookworm.${ENV}.finance.complete-order` or
`bookworm.${ENV}.finance.cancel-order`. If replaying within `24` hours with the same message
`id`, clear or rotate the `id` only after confirming no email was delivered.
---
title: Manual Vector Batch Trigger and Quartz Inspection
summary: CLI-first runbook to inspect Quartz scheduler state and manually trigger a vector batch event.
version: 1.0.0
---
Operational runbook for [[service|scheduler-service]] when scheduled jobs stall or an out-of-band vector index catch-up is required.
Inspect `qrtz_triggers` to verify whether the vector batch trigger is `WAITING`, `ACQUIRED`, `PAUSED`, or `ERROR`:
```bash
psql "$SCHEDULER_DB_URL" -c "SELECT trigger_name, trigger_state, next_fire_time, prev_fire_time FROM qrtz_triggers ORDER BY trigger_name;"
```
If immediate indexing is needed without waiting for the next cron tick, publish [[event|ProcessVectorBatchIntegrationEvent]] to [[channel|scheduler.process-vector-batch]]:
```bash
echo '{"id":"'"$(uuidgen)"'","creationDate":"'"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'"}' | kcat -P -b "$KAFKA_BOOTSTRAP" -t "scheduler.process-vector-batch"
```
---
title: Feedback ownership, concurrency, and compensation
summary: Domain invariants, Cosmos DB concurrency, caching, and cross-domain compensation rules for Rating API.
version: 1.0.0
type: engineering
order: 1
badges:
- content: Architecture
backgroundColor: green
textColor: green
---
## Purpose & Scope
This document defines the data ownership, optimistic concurrency, caching, and cross-domain compensation boundaries for [[service|rating-api]] and [[agent|rating-agent]] in the [[domain|reviews]] subdomain. Use it when modifying feedback mutations, Azure Cosmos DB persistence, Kafka rating events, or read-only AI summarization.
## Visual Reference
The visual below illustrates how [[service|rating-api]] persists feedback in [[container|rating-database]], caches reads in [[container|rating-cache]], exchanges rating events with [[service|catalog-api]], and serves read-only summarization.
_Feedback Persistence, Catalog Projection, and Summarization Boundaries_
## Core Invariants & Design Rules
- **Feedback system of record:** [[service|rating-api]] owns individual [[entity|feedback]] documents in [[container|rating-database]] (Azure Cosmos DB, partitioned by `/bookId`); it uses no relational database. [[service|catalog-api]] holds only a derived `average_rating` and `total_reviews` projection on [[entity|book]].
- **Rating & PII constraints:** Every feedback rating must be an integer between `0` and `5` inclusive (enforced at both request validation and domain construction). Reviewer names are tagged as PII for automatic log redaction.
- **Post-commit event publication:** [[event|FeedbackCreatedIntegrationEvent]] and [[event|FeedbackDeletedIntegrationEvent]] are published only after the Cosmos DB write commits, never speculatively before persistence.
- **Compensation without re-emission:** When [[service|catalog-api]] rejects a feedback event for a missing book via [[event|BookUpdatedRatingFailedIntegrationEvent]], [[service|rating-api]] reverts and deletes the orphaned feedback without emitting [[event|FeedbackDeletedIntegrationEvent]] (preventing a compensation loop).
- **Read-only AI summarization:** [[agent|rating-agent]] reads catalog context via [[service|mcp-server]] and raw feedback via [[service|rating-api]], runs behind Presidio PII middleware, and produces derived insights only—never mutating [[container|rating-database]] or [[container|catalog-database]].
:::warning
**Never emit `FeedbackDeletedIntegrationEvent` during compensation.** Deleting an orphaned feedback in response to [[event|BookUpdatedRatingFailedIntegrationEvent]] must use the revert path rather than the standard delete path; otherwise [[service|catalog-api]] would receive a spurious decrement for a book it already rejected.
:::
## Boundaries & Guarantees
| Concern | Strategy & Guarantee | Failure / Edge-Case Behavior | Related Resources |
| :---------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Persistence** | rating-database stores feedback documents partitioned by `/bookId` with Wolverine Cosmos DB persistence for durable messaging. | Missing feedback on `DELETE` returns `404 Not Found` (never masked as `204`); compensation delete for an already-absent record completes as a no-op. | rating-database, feedback, adr-001-postgresql-feedback-system-of-record |
| **Caching** | rating-cache caches paged feedback reads (`ListFeedbacks`) via FusionCache with a `10m` TTL tagged by `BookId`. | Feedback creation, deletion, or compensation invalidates the affected `BookId` tag so subsequent reads reflect the updated list. | rating-cache, ListFeedbacks |
| **Messaging** | Emits FeedbackCreatedIntegrationEvent and FeedbackDeletedIntegrationEvent partitioned by `BookId` / `FeedbackId`; consumes BookUpdatedRatingFailedIntegrationEvent. | Exhausted retries route to `bookworm.{env}.rating.dead-letter-queue`; missing-book compensation deletes the orphaned feedback cleanly. | `bookworm.{env}.rating.feedback-create`, `bookworm.{env}.rating.feedback-delete`, `bookworm.{env}.catalog.book-update-rating-failed`, `bookworm.{env}.rating.dead-letter-queue` |
| **Concurrency & Idempotency** | Cosmos DB ETag optimistic concurrency prevents lost updates on feedback documents; inbound compensation events use a `24h` Redis integration-event idempotency guard; HTTP routes enforce `PerUserRateLimit`. | Concurrent ETag conflicts fail fast rather than overwriting newer state; duplicate BookUpdatedRatingFailedIntegrationEvent deliveries within `24h` are safely ignored. | rating-api, feedback-publication, adr-003-compensate-invalid-feedback-after-catalog-rejection |
`POST /api/v1/feedbacks` and `GET /api/v1/feedbacks` are rate-limited (`PerUserRateLimit`).
`DELETE /api/v1/feedbacks/{id}` requires the `admin` policy (`admin` role +
`rating_read`/`rating_write` scopes). `GET /api/v1/feedbacks/{id}/summarize` requires an
authenticated caller, while Agent-to-Agent (A2A) gRPC calls from [[service|chat-api]] require
the `read` policy (`rating_read` scope) via Entra Agent Identity token exchange.
[[query|SummarizeFeedback]] synthesizes themes, sentiment, and confidence from current reviews
at read time. Its output is never persisted back to [[container|rating-database]] and never
overrides the deterministic `average_rating` maintained by [[service|catalog-api]].
## Safe Change & Verification Checklist
- Preserve the `/bookId` partition key and ETag optimistic concurrency configuration on [[container|rating-database]] (`feedbacks` container).
- Verify [[event|FeedbackCreatedIntegrationEvent]] and [[event|FeedbackDeletedIntegrationEvent]] emit only post-commit, and that compensation revert never emits [[event|FeedbackDeletedIntegrationEvent]].
- Confirm `BookId` cache-tag invalidation in [[container|rating-cache]] on create, delete, and compensation paths.
- Keep `0`–`5` rating validation, PII log redaction, and `admin` / `read` authorization policies intact.
- Run `mise run format`, `mise run build`, and `mise run test` to verify Rating unit tests and Pact contracts (`Rating-Catalog`, `Catalog-Rating`).
## Related Resources
- [[service|rating-api]] — Authoritative Reviews API and compensation consumer
- [[agent|rating-agent]] — Read-only review summarization agent
- [[command|CreateFeedback]], [[command|DeleteFeedback]], [[query|ListFeedbacks]], [[query|SummarizeFeedback]] — Feedback operations
- [[flow|feedback-publication]] — End-to-end feedback publication and compensation flow
- [[adr|adr-002-publish-feedback-events-for-catalog-projection]], [[adr|adr-003-compensate-invalid-feedback-after-catalog-rejection]], [[adr|adr-004-read-only-governed-feedback-summarization]]
- [[doc|platform/006-api-and-contracts]] — Consolidated HTTP, gRPC, and Kafka contracts
---
title: Feedback lifecycle
summary: How customers submit feedback and how Reviews publishes rating changes to Catalog.
version: 1.0.0
type: guides
order: 1
badges:
- content: Guide
backgroundColor: teal
textColor: teal
---
**Audience & Outcome:** This guide is for backend engineers, moderators, and integrators working with [[service|rating-api]] and [[service|catalog-api]]. You will learn how customer reviews are persisted, summarized by AI, projected asynchronously to Catalog, and compensated when a target book is missing.
BookWorm separates customer review storage from product catalog browsing across two independent bounded contexts: [[service|rating-api]] owns individual [[entity|feedback]] documents in [[container|rating-database]] (partitioned by `/bookId`), while [[service|catalog-api]] owns [[entity|book]] records in [[container|catalog-database]] and maintains only a derived rating summary (`average_rating` and `total_reviews`).
## Context and motivation
Individual customer reviews and catalog product listings have different access patterns, scaling profiles, and consistency requirements:
- **Reviews** stores append-heavy, book-partitioned documents and supports paginated browsing and AI-generated review summaries.
- **Catalog** serves high-volume browsing and search queries that only need an aggregate average score and review count per book.
Sharing a single database between Reviews and Catalog—or blocking review writes on synchronous Catalog updates—would couple deployment lifecycles and turn temporary Catalog slowdowns into customer review outages.
## How it works
The visual below traces the normal creation and deletion projection path from [[service|rating-api]] to [[service|catalog-api]] alongside the compensating delete path when a book no longer exists.
### Four lifecycle stages
A caller submits a `bookId`, reviewer name, integer rating (`0`–`5`), and optional comment to `POST /api/v1/feedbacks`. [[service|rating-api]] persists the [[entity|feedback]] document in [[container|rating-database]], returns `200 OK`, and publishes [[event|FeedbackCreatedIntegrationEvent]] to `bookworm.{env}.rating.feedback-create`.
:::note
Returning `200 OK` confirms review persistence in [[container|rating-database]]—not that [[service|catalog-api]] has finished updating its summary.
:::
Paginated reviews for a book are cached for 10 minutes in [[container|rating-cache]]. Authenticated callers can request an AI summary, which runs [[agent|rating-agent]] with [[service|presidio-api]] PII protection. The agent reads live book context through [[service|mcp-server]] and raw reviews, returning a read-only derived summary that never mutates [[container|rating-database]] or Catalog.
Authorized administrators remove a review via `DELETE /api/v1/feedbacks/{id}` (missing IDs return `404 Not Found`). Deleting an existing record removes the document from [[container|rating-database]] and publishes [[event|FeedbackDeletedIntegrationEvent]] to `bookworm.{env}.rating.feedback-delete` so Catalog decrements its projection asynchronously.
[[service|catalog-api]] consumes create and delete events with a 24-hour idempotency guard so at-least-once retries cannot double-count ratings. If a [[event|FeedbackCreatedIntegrationEvent]] arrives for a `bookId` that does not exist in [[container|catalog-database]], Catalog publishes [[event|BookUpdatedRatingFailedIntegrationEvent]] to `bookworm.{env}.catalog.book-update-rating-failed`. [[service|rating-api]]'s compensation handler invalidates [[container|rating-cache]] and deletes the orphaned document without emitting a delete event.
| Decision | Benefits | Costs and limits |
| :------------------------------------------------------- | :-------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------- |
| **Cosmos DB for Reviews vs. PostgreSQL for Catalog** | Partitioning by `/bookId` gives fast per-book queries and isolates write scaling | Two database technologies to operate; cross-domain consistency is eventual |
| **Post-commit Kafka projection with compensation** | Keeps review submissions fast and resilient even if Catalog is temporarily unavailable | Rating summaries briefly lag behind Reviews; invalid submissions clean up asynchronously |
| **Idempotent consumers** | Tolerates at-least-once Kafka redelivery without skewing Catalog totals | Requires healthy Redis alongside Kafka consumers |
| **Read-only AI summarization ([[agent\|rating-agent]])** | Provides governed, PII-filtered insights without risking corruption of customer ratings | Summary generation incurs live LLM and MCP lookup latency |
**Rejected alternatives:**
- **Synchronous gRPC check against Catalog before saving feedback:** A book can still be deleted between check and projection, and synchronous validation couples Reviews write availability to Catalog uptime.
- **Storing feedback in PostgreSQL inside [[container|catalog-database]]:** Breaks bounded-context isolation between Reviews and Catalog.
## Related documentation
- [[flow|feedback-publication]] — End-to-end feedback publication, projection, and compensation flow.
- [[adr|adr-002-publish-feedback-events-for-catalog-projection]] — Decision record for asynchronous feedback projection.
- [[adr|adr-003-compensate-invalid-feedback-after-catalog-rejection]] — Compensation when Catalog rejects a missing book ID.
- [[doc|arc42]] — System-wide bounded contexts and data stores.
---
title: Recover a failed Catalog rating projection
summary: Investigate and compensate when Catalog cannot apply a feedback rating change because the Book is missing.
version: 1.0.0
type: runbooks
order: 1
badges:
- content: Runbook
backgroundColor: orange
textColor: orange
---
## Trigger / Symptom & Blast Radius
[[service|catalog-api]] publishes [[event|BookUpdatedRatingFailedIntegrationEvent]] on `bookworm.{env}.catalog.book-update-rating-failed`, or a created [[entity|feedback]] record in [[service|rating-api]] fails to project onto a [[entity|book]] in [[service|catalog-api]]. Blast radius is limited to orphaned review cleanup for a missing book; never communicate this compensation to customers as a manual deletion.
Never delete feedback records by `bookId` alone. Compensation targets only the exact `FeedbackId`
reported by [[event|BookUpdatedRatingFailedIntegrationEvent]].
## Pre-Flight Check
Capture `FeedbackId`, correlation ID, and `` from the failure event, then verify whether `` exists in [[service|catalog-api]] and query [[container|rating-database]]:
```bash
curl -sS -o /dev/null -w "%{http_code}\n" "https:///catalog/api/v1/books/"
```
```sql
SELECT c.id, c.bookId, c.rating, c.createdAt FROM c WHERE c.id = "";
```
## Quick Recovery Procedure
If the Catalog check returns **`404 Not Found`**, the book is absent and compensation is valid. Continue to Step 2.
If the Catalog check returns **`200 OK`**, **stop immediately**. Do not delete the feedback record—this indicates a transient database or contract fault. Escalate to [[team|catalog-experience-team]].
Check lag and DLQ depth across `bookworm.{env}.rating.feedback-create`, `bookworm.{env}.catalog.book-update-rating-failed`, `bookworm.{env}.catalog.dead-letter-queue`, and `bookworm.{env}.rating.dead-letter-queue`. Stream [[service|rating-api]] logs for Cosmos DB or Redis errors:
```bash
az containerapp logs show --name --resource-group --tail 150
```
Restore any unhealthy dependency ([[container|rating-database]], Redis, or Kafka) and replay recoverable messages from `bookworm.{env}.rating.dead-letter-queue`. The compensation handler deletes the orphaned document and invalidates [[container|rating-cache]] without emitting [[event|FeedbackDeletedIntegrationEvent]].
## Verification
Re-run the [[container|rating-database]] query for `` and confirm `0` documents are returned while DLQ depth stops growing:
```sql
SELECT VALUE COUNT(1) FROM c WHERE c.id = "";
```
Expected output:
```json
[0]
```
## Rollback / Escalation
- **Rollback:** Compensation deletes only confirmed orphaned reviews for `404` books; if a book was restored, the customer must re-submit their review.
- **Escalation:** Escalate `200 OK` false-failure events or persistent DLQ errors to [[team|catalog-experience-team]].
## Related documentation
- [[flow|feedback-publication]] — End-to-end review projection and compensation flow.
- [[adr|adr-003-compensate-invalid-feedback-after-catalog-rejection]] — Compensation decision record.
---
title: Engineering Invariants and Quirks
summary: Cosmos DB partitioning, ETag concurrency, Presidio PII redaction, AI summary caching, and compensating rollback for Rating API.
version: 1.0.0
---
Engineering invariants and known contract quirks for [[service|rating-api]].
## Storage, Privacy & Caching Invariants
- **Cosmos DB partitioning & ETag concurrency:** Feedback documents are stored in [[container|rating-database]] (`ratingdb`/`feedbacks`) partitioned by `/bookId`. Deletions ([[command|DeleteFeedback]]) enforce Cosmos DB ETag concurrency (`409 Conflict` on mismatch).
- **PII log redaction & Presidio governance:** Reviewer `firstName` and `lastName` are redacted in structured logs, and [[query|SummarizeFeedback]] uses [[service|presidio-api]] to scrub PII before/after AI summarization.
- **AI summary cache invalidation:** Mutations clear cached feedback lists tagged by `bookId` and evict cached AI rating summaries when `reviewCount` is `0` or feedback is deleted.
- **Compensating rollback:** If [[service|catalog-api]] emits [[event|BookUpdatedRatingFailedIntegrationEvent]] because the target book does not exist, [[service|rating-api]] deletes the orphaned feedback document and invalidates caches.
## Known Contract & Runtime Quirks
:::note
OpenAPI metadata for [[command|DeleteFeedback]] declares `404 Not Found` as `application/problem+json`, whereas runtime responses return `application/json` with `{ "detail": "The requested resource was not found." }`.
:::
---
title: Basket consistency, enrichment, and cleanup
summary: Engineering invariants, Redis ownership, Catalog enrichment purity, and checkout cleanup idempotency for Basket API.
version: 1.0.0
type: engineering
order: 1
badges:
- content: Architecture
backgroundColor: green
textColor: green
---
## Purpose & Scope
This document defines the data ownership, consistency model, read-time enrichment rules, and asynchronous checkout cleanup guarantees for [[service|basket-api]] in the [[domain|shopping]] subdomain. Use it when modifying basket endpoints, gRPC contracts, Redis persistence, or post-checkout Kafka handlers.
## Visual Reference
The visual below shows how [[service|basket-api]] interacts with [[container|basket-database]], [[service|catalog-api]], [[service|order-api]], and [[service|order-orchestration]].
_Basket Persistence, Enrichment, and Checkout Cleanup Boundaries_
## Core Invariants & Design Rules
- **Customer-scoped identity:** [[service|basket-api]] derives the basket key (`basket:{userId}`) strictly from the authenticated Microsoft Entra ID `ClaimsPrincipal` (`customer` role with `basket_read` / `basket_write` scopes), never from caller-supplied route or body identifiers.
- **Transient pre-order intent:** [[entity|basket]] and [[entity|basket-item]] records represent mutable pre-order customer intent only; they are out of scope for order totals, payments, or fulfillment.
- **No persisted prices or titles:** [[container|basket-database]] stores only `BookId` and a strictly positive `Quantity` (`> 0`). Live titles, regular prices, and sale prices are never persisted in Redis.
- **Full-set replacement semantics:** Updating a basket replaces the entire item collection atomically rather than merging individual items, and requires at least one item.
- **Explicit missing-basket semantics:** Reading, updating, or deleting an absent `basket:{userId}` returns `404 Not Found`; missing baskets are never masked as empty `200 OK` responses.
:::warning
**Read-time enrichment must remain pure.** During `GET /api/v1/baskets`, if [[service|catalog-api]] has no record for a stored `BookId`, [[service|basket-api]] must preserve the stored [[entity|basket-item]] and omit unavailable display fields—never invent prices or mutate [[container|basket-database]] during a read.
:::
## Boundaries & Guarantees
| Concern | Strategy & Guarantee | Failure / Edge-Case Behavior | Related Resources |
| :---------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Persistence** | basket-database (Redis) is the sole authoritative store (`basket:{userId}`, camelCase JSON); no relational database is used. | Missing keys return `404 Not Found` on HTTP reads/writes and empty/absent responses over gRPC without auto-creating state. | basket-database, basket, basket-item, adr-001-redis-authoritative-basket-store |
| **Caching & Enrichment** | `GET /api/v1/baskets` resolves distinct `BookId` values on demand via GetBooksGrpc on catalog-api; basket-database also backs FusionCache. | Unavailable Catalog fields are omitted gracefully on read; order-api snapshots prices independently at checkout via GetBasketGrpc. | GetBasket, GetBasketGrpc, GetBooksGrpc, adr-004-catalog-enrichment-at-read-time |
| **Messaging** | Consumes PlaceOrderCommand partitioned by `OrderId` and emits BasketDeletedCompleteIntegrationEvent or BasketDeletedFailedIntegrationEvent to order-orchestration. | Missing basket on cleanup emits BasketDeletedFailedIntegrationEvent (signals cleanup failure only, never order/payment failure); unhandled exceptions exhaust Wolverine retries (`50ms / 250ms / 1s` with jitter) and route to `bookworm.{env}.basket.dead-letter-queue`. | PlaceOrderCommand, BasketDeletedCompleteIntegrationEvent, BasketDeletedFailedIntegrationEvent, `bookworm.{env}.basket.dead-letter-queue`, adr-005-explicit-checkout-cleanup-outcomes |
| **Concurrency & Idempotency** | `PlaceOrderCommand` handling is guarded by a `24h` Redis integration-event idempotency guard keyed by `OrderId`; all HTTP routes enforce `PerUserRateLimit`. | Duplicate `OrderId` deliveries within `24h` immediately re-emit BasketDeletedCompleteIntegrationEvent without touching Redis; exceptions release the `OrderId` guard so retries can execute cleanly. | basket-api, order-orchestration, user-checkout |
Once [[service|order-api]] commits an order, [[service|order-orchestration]] issues
[[command|PlaceOrderCommand]] asynchronously to clean up the customer's basket. If the basket
was already deleted or expired, [[service|basket-api]] emits
[[event|BasketDeletedFailedIntegrationEvent]] so the saga can record the cleanup outcome without
rolling back an already-accepted order.
Returning `false` from basket deletion (key absent) is a deterministic business outcome that
emits [[event|BasketDeletedFailedIntegrationEvent]]. Throwing a transient infrastructure
exception (e.g., Redis timeout) releases the `24h` `OrderId` idempotency guard so Wolverine
retries or DLQ replay can re-attempt deletion.
## Safe Change & Verification Checklist
- Keep customer identity derived exclusively from Entra ID claims and preserve `basket:{userId}` key isolation and `customer` authorization policies.
- Preserve full-set replacement semantics on [[command|UpdateBasket]] and non-empty, positive-quantity validation on [[command|CreateBasket]] and [[command|UpdateBasket]].
- Verify [[query|GetBasketGrpc]] remains backward-compatible for [[service|order-api]] and [[query|GetBooksGrpc]] degradation never mutates Redis on read.
- Test both [[event|BasketDeletedCompleteIntegrationEvent]] and [[event|BasketDeletedFailedIntegrationEvent]] outcomes, plus `OrderId` idempotency guard release on exception.
- Run `mise run format`, `mise run build`, and `mise run test` to verify Basket unit tests and Pact contracts (`Basket-Finance`, `Finance-Basket`).
## Related Resources
- [[service|basket-api]] — Authoritative Shopping basket service
- [[command|CreateBasket]], [[command|UpdateBasket]], [[command|DeleteBasket]], [[query|GetBasket]], [[query|GetBasketGrpc]] — Basket commands and queries
- [[command|PlaceOrderCommand]], [[event|BasketDeletedCompleteIntegrationEvent]], [[event|BasketDeletedFailedIntegrationEvent]] — Checkout cleanup contracts
- [[flow|user-checkout]] — End-to-end checkout and basket cleanup flow
- [[adr|adr-001-redis-authoritative-basket-store]], [[adr|adr-002-customer-scoped-basket-ownership]], [[adr|adr-003-replace-basket-items-as-a-set]], [[adr|adr-004-catalog-enrichment-at-read-time]], [[adr|adr-005-explicit-checkout-cleanup-outcomes]]
- [[doc|platform/006-api-and-contracts]] — Consolidated HTTP, gRPC, and Kafka contracts
---
title: Checkout lifecycle
summary: Guide to the Shopping checkout handoff and basket cleanup outcomes.
version: 1.0.0
type: guides
badges:
- content: Guide
backgroundColor: teal
textColor: teal
---
**Audience & Outcome:** This guide is for frontend developers, backend engineers, and operators working across [[service|basket-api]], [[service|order-api]], and [[service|order-orchestration]]. You will learn how mutable baskets hand off to immutable orders and how explicit basket-cleanup outcomes are reported.
BookWorm draws a strict boundary between pre-purchase shopping intent and committed commercial orders: [[service|basket-api]] owns the customer's mutable [[entity|basket]] in [[container|basket-database]], [[service|catalog-api]] supplies live titles and prices, [[service|order-api]] locks in an immutable [[entity|order]] snapshot in [[container|order-database]], and [[service|order-orchestration]] coordinates asynchronous basket deletion after checkout.
## Context and motivation
Before a customer clicks checkout, their basket changes frequently and requires low-latency reads and writes with live catalog pricing. After checkout, the purchase must become an immutable commercial record that cannot shift when catalog prices change or when the customer starts shopping again.
Separating Shopping from Ordering and Finance ensures:
- **No shared mutable state:** Ordering never shares Redis basket keys with Shopping, and Shopping never writes to [[container|order-database]] or [[container|catalog-database]].
- **Clean failure isolation:** A temporary Redis or Kafka issue during post-checkout cleanup never blocks or falsifies order status, while explicit cleanup events let Finance and Ordering react deterministically.
## How it works
Customers manage their basket and submit checkout through the Commerce microfrontend. The visual below traces a customer from basket review through checkout handoff and asynchronous post-checkout basket cleanup.
### Four checkout stages
Commerce fetches the authenticated customer's basket from [[service|basket-api]]. The service loads stored book IDs and quantities from [[container|basket-database]] and enriches them on read via [[service|catalog-api]] gRPC so the customer confirms current titles and prices.
When the customer confirms checkout, Commerce submits an order creation request with a unique `x-request-id`. [[service|order-api]] reads the basket over gRPC, resolves and locks prices via [[service|catalog-api]], persists the immutable [[entity|order]] in [[container|order-database]] with status `New`, and publishes [[event|UserCheckedOutIntegrationEvent]].
[[service|order-orchestration]] consumes [[event|UserCheckedOutIntegrationEvent]] and publishes [[command|PlaceOrderCommand]] to `bookworm.{env}.finance.place-order`.
[[service|basket-api]] acquires a 24-hour idempotency guard keyed by `OrderId` and deletes the customer's basket from [[container|basket-database]]:
**Cleanup succeeds (or already processed):** Emits [[event|BasketDeletedCompleteIntegrationEvent]] on `bookworm.{env}.basket.delete-complete`.
**Cleanup fails (key absent or not deleted):** Emits [[event|BasketDeletedFailedIntegrationEvent]] on `bookworm.{env}.basket.delete-failed`.
:::warning
Neither cleanup event proves payment settlement, order completion, or fulfillment; they report basket cleanup status only.
:::
### Rules for callers and consumers
- **Verify before retrying ambiguous checkouts:** If order creation times out, query [[service|order-api]] before retrying so the customer is not placed into a duplicate order.
- **Treat cleanup failure as distinct from deletion:** Never interpret [[event|BasketDeletedFailedIntegrationEvent]] as a successful cleanup or as a payment failure.
- **Design idempotent consumers:** Both [[service|basket-api]] and [[service|order-orchestration]] tolerate at-least-once Kafka redelivery.
| Decision | Benefits | Costs and limits |
| :-------------------------------------------------- | :---------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------- |
| **gRPC snapshot read + asynchronous Kafka cleanup** | Keeps Shopping and Ordering storage decoupled and keeps checkout latency low | Introduces a brief window after `201 Created` where cleanup is still in flight |
| **Live Catalog enrichment on basket read** | Customers always see current prices before checkout without catalog-sync jobs | Basket reads depend on [[service\|catalog-api]] gRPC availability |
| **Explicit success and failure cleanup events** | Enables deterministic Finance/Ordering reactions | Requires disciplined incident triage so cleanup errors are not misread as cancellations |
**Rejected alternatives:**
- **Deleting the basket synchronously inside order creation:** Coupling Ordering's PostgreSQL transaction to a remote Redis deletion creates dual-write failure modes.
- **Promoting the basket record directly into an Order entity:** Mutable browsing state and immutable financial history have incompatible lifecycles and retention rules.
## Related documentation
- [[flow|user-checkout]] — End-to-end checkout flow across Shopping, Ordering, and Finance.
- [[adr|adr-004-catalog-enrichment-at-read-time]] — Why basket items are enriched from Catalog at read time.
- [[adr|adr-005-explicit-checkout-cleanup-outcomes]] — Why basket cleanup emits explicit success and failure events.
---
title: Recover a failed basket cleanup
summary: Operational procedure for investigating and recovering a failed basket deletion after checkout.
version: 1.0.0
type: runbooks
badges:
- content: Runbook
backgroundColor: orange
textColor: orange
---
## Trigger / Symptom & Blast Radius
[[service|basket-api]] publishes [[event|BasketDeletedFailedIntegrationEvent]] on `bookworm.{env}.basket.delete-failed`, [[command|PlaceOrderCommand]] messages land in `bookworm.{env}.basket.dead-letter-queue`, or a customer's [[entity|basket]] remains in [[container|basket-database]] after checkout. Blast radius is post-checkout basket state; always verify the downstream [[entity|order]] in [[service|order-api]] before deleting any basket.
Never delete a customer's basket until you confirm the downstream order was accepted in
[[service|order-api]]. If the order status is ambiguous or missing, stop immediately and escalate.
## Pre-Flight Check
Verify the downstream order status in [[service|order-api]] and check [[service|basket-api]] logs in ``:
```bash
curl -sS -H "Authorization: Bearer " "https:///ordering/api/v1/orders/"
az containerapp logs show --name --resource-group --tail 150
```
## Quick Recovery Procedure
Inspect [[service|basket-api]] logs, [[container|basket-database]] key `basket:`, and Kafka topics (`bookworm.{env}.finance.place-order`, `bookworm.{env}.basket.delete-failed`, `bookworm.{env}.basket.dead-letter-queue`):
**Mode A (Key already absent):** Redis was reachable, but the basket key was already gone. Finance reacts by sending [[command|DeleteBasketFailedCommand]] to [[service|order-api]], which soft-deletes the order (`404 Not Found`).
**Mode B (Transient Redis/broker exception):** Redis failed during deletion, releasing the 24-hour `OrderId` idempotency guard and routing [[command|PlaceOrderCommand]] to the DLQ while the basket remains in Redis.
**Mode B (Order accepted and `New`, basket still in Redis):** Restore Redis / [[service|basket-api]] health, then replay [[command|PlaceOrderCommand]] from `bookworm.{env}.basket.dead-letter-queue` to `bookworm.{env}.finance.place-order` so [[event|BasketDeletedCompleteIntegrationEvent]] is emitted cleanly.
**Mode A (Order soft-deleted `404`) or ambiguous outcome:** Stop without modifying Redis or issuing manual order transitions, and escalate with ``, ``, and event timestamps.
## Verification
Confirm the basket is absent for the customer and [[event|BasketDeletedCompleteIntegrationEvent]] was emitted on `bookworm.{env}.basket.delete-complete`:
```bash
curl -sS -o /dev/null -w "%{http_code}\n" -H "Authorization: Bearer " "https:///basket/api/v1/baskets"
```
Expected output:
```text
404
```
## Rollback / Escalation
- **Rollback:** Do not restore deleted baskets after confirmed checkout; customers can add new items anytime.
- **Escalation:** Escalate Mode A soft-deleted orders or ambiguous checkout outcomes to [[team|commerce-fulfillment-team]]; escalate Redis outages to [[team|platform-engineering-team]].
## Related documentation
- [[flow|user-checkout]] — End-to-end checkout and cleanup flow.
- [[adr|adr-005-explicit-checkout-cleanup-outcomes]] — Explicit cleanup outcome events.
---
title: Engineering Invariants and Quirks
summary: Redis-only authoritative storage, OBO gRPC authentication, idempotent checkout cleanup, and empty-basket behavior for Basket API.
version: 1.0.0
---
Engineering invariants and known contract quirks for [[service|basket-api]].
## Storage, Auth & Idempotency Invariants
- **Redis-only authoritative store:** [[service|basket-api]] persists customer baskets exclusively in [[container|basket-database]] (Redis) keyed by authenticated customer identifier; there is no relational backing store.
- **On-Behalf-Of (OBO) gRPC auth:** [[query|GetBasketGrpc]] is called by [[service|order-api]] during checkout using delegated user identity so basket ownership remains strictly scoped to the authenticated buyer.
- **Checkout cleanup idempotency:** Consumes [[command|PlaceOrderCommand]] with a `24`-hour Redis idempotency lock keyed by `OrderId`. On transient Redis errors, the lock is released and retried before routing to [[channel|bookworm.{env}.basket.dead-letter-queue]].
- **Explicit cleanup outcomes:** Emits [[event|BasketDeletedCompleteIntegrationEvent]] when deletion succeeds, or [[event|BasketDeletedFailedIntegrationEvent]] when Redis deletion returns `false` so [[service|order-orchestration]] can compensate.
## Known Contract & Runtime Quirks
:::note
[[query|GetBasketGrpc]] returns an empty basket response rather than `NotFound` when no Redis key exists for the buyer. Upstream callers such as [[command|CreateOrder]] must explicitly validate item counts if empty baskets should be rejected.
:::
---
title: Basket DLQ Inspection and Replay
summary: CLI-first procedure to inspect and safely replay failed checkout cleanup messages from the Basket dead-letter queue.
version: 1.0.0
---
Operational runbook for triaging [[channel|bookworm.{env}.basket.dead-letter-queue]] for [[service|basket-api]].
:::warning
**Never replay to [[channel|bookworm.{env}.finance.place-order]]**—[[service|notification-api]] also consumes that topic and would send duplicate order confirmation emails. Replay only to a [[service|basket-api]]-scoped recovery path or verify Redis state directly.
:::
```bash
kcat -C -b "$KAFKA_BOOTSTRAP" -t "bookworm.${ENV}.basket.dead-letter-queue" -o -20 -e -f '%t [%p] offset=%o key=%k headers=%h\n%s\n---\n'
```
Verify Redis health and inspect whether the buyer's basket key or `OrderId` idempotency lock (`24h` TTL) is still present:
```bash
redis-cli -u "$REDIS_URL" EXISTS ""
```
If [[service|order-orchestration]] has already compensated the order, do not replay cleanup. Otherwise, clear any stale lock if needed and trigger basket removal or replay the [[command|PlaceOrderCommand]] payload to [[service|basket-api]] only.