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

<AccordionGroup>
	<Accordion title="Hosting, scaling, and environment parity">
		- **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.
	</Accordion>
</AccordionGroup>

## Architecture Visualizations

<NodeGraph />

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

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