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

<MermaidFileLoader file="mermaids/basket-api-contracts-diagram-1.mmd" />

_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**               | <ResourceLink id="basket-database" type="container">basket-database</ResourceLink> (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.                                                                                                                                                                                                                                                                                                                            | <ResourceLink id="basket-database" type="container">basket-database</ResourceLink>, <ResourceLink id="basket" type="entity">basket</ResourceLink>, <ResourceLink id="basket-item" type="entity">basket-item</ResourceLink>, <ResourceLink id="adr-001-redis-authoritative-basket-store" type="adr">adr-001-redis-authoritative-basket-store</ResourceLink>                                                                                                                                                                                                                                                       |
| **Caching & Enrichment**      | `GET /api/v1/baskets` resolves distinct `BookId` values on demand via <ResourceLink id="GetBooksGrpc" type="query">GetBooksGrpc</ResourceLink> on <ResourceLink id="catalog-api" type="service">catalog-api</ResourceLink>; <ResourceLink id="basket-database" type="container">basket-database</ResourceLink> also backs FusionCache.                                                                                                                                             | Unavailable Catalog fields are omitted gracefully on read; <ResourceLink id="order-api" type="service">order-api</ResourceLink> snapshots prices independently at checkout via <ResourceLink id="GetBasketGrpc" type="query">GetBasketGrpc</ResourceLink>.                                                                                                                                                                                            | <ResourceLink id="GetBasket" type="query">GetBasket</ResourceLink>, <ResourceLink id="GetBasketGrpc" type="query">GetBasketGrpc</ResourceLink>, <ResourceLink id="GetBooksGrpc" type="query">GetBooksGrpc</ResourceLink>, <ResourceLink id="adr-004-catalog-enrichment-at-read-time" type="adr">adr-004-catalog-enrichment-at-read-time</ResourceLink>                                                                                                                                                                                                                                                           |
| **Messaging**                 | Consumes <ResourceLink id="PlaceOrderCommand" type="command">PlaceOrderCommand</ResourceLink> partitioned by `OrderId` and emits <ResourceLink id="BasketDeletedCompleteIntegrationEvent" type="event">BasketDeletedCompleteIntegrationEvent</ResourceLink> or <ResourceLink id="BasketDeletedFailedIntegrationEvent" type="event">BasketDeletedFailedIntegrationEvent</ResourceLink> to <ResourceLink id="order-orchestration" type="service">order-orchestration</ResourceLink>. | Missing basket on cleanup emits <ResourceLink id="BasketDeletedFailedIntegrationEvent" type="event">BasketDeletedFailedIntegrationEvent</ResourceLink> (signals cleanup failure only, never order/payment failure); unhandled exceptions exhaust Wolverine retries (`50ms / 250ms / 1s` with jitter) and route to <ResourceLink id="bookworm.{env}.basket.dead-letter-queue" type="channel">`bookworm.{env}.basket.dead-letter-queue`</ResourceLink>. | <ResourceLink id="PlaceOrderCommand" type="command">PlaceOrderCommand</ResourceLink>, <ResourceLink id="BasketDeletedCompleteIntegrationEvent" type="event">BasketDeletedCompleteIntegrationEvent</ResourceLink>, <ResourceLink id="BasketDeletedFailedIntegrationEvent" type="event">BasketDeletedFailedIntegrationEvent</ResourceLink>, <ResourceLink id="bookworm.{env}.basket.dead-letter-queue" type="channel">`bookworm.{env}.basket.dead-letter-queue`</ResourceLink>, <ResourceLink id="adr-005-explicit-checkout-cleanup-outcomes" type="adr">adr-005-explicit-checkout-cleanup-outcomes</ResourceLink> |
| **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 <ResourceLink id="BasketDeletedCompleteIntegrationEvent" type="event">BasketDeletedCompleteIntegrationEvent</ResourceLink> without touching Redis; exceptions release the `OrderId` guard so retries can execute cleanly.                                                                                                                                                             | <ResourceLink id="basket-api" type="service">basket-api</ResourceLink>, <ResourceLink id="order-orchestration" type="service">order-orchestration</ResourceLink>, <ResourceLink id="user-checkout" type="flow">user-checkout</ResourceLink>                                                                                                                                                                                                                                                                                                                                                                      |

<AccordionGroup>
	<Accordion title="Why checkout cleanup failure does not fail the order">
		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.
	</Accordion>
	<Accordion title="Exception vs. absent-key handling in cleanup">
		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.
	</Accordion>
</AccordionGroup>

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