---
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.&#123;env&#125;.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.&#123;env&#125;.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.

<NodeGraph />

<SchemaViewer file="schema.json" title="Create order schema" maxHeight="500" search="true" />


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