Design and implement a REST API method to create a resource with idempotency
Context
You are building a create endpoint for a commerce-like service. To make the problem concrete, assume the resource is an Order and clients will call POST /v1/orders to create one. The API must be safe to retry and free from race conditions.
Requirements
-
Endpoint and semantics
-
Define the REST endpoint for creating an order.
-
Specify required headers.
-
Request schema
-
Define the JSON request schema and a sample request.
-
State validation and sanitization rules.
-
Response schema
-
Define success responses and a sample response.
-
Include relevant HTTP headers (e.g., Location).
-
HTTP status codes
-
Enumerate appropriate success and error codes and when to use each.
-
Idempotency
-
Use an Idempotency-Key header.
-
Define behavior for duplicate requests (same key + same body, and same key + different body).
-
Error handling and logging
-
Define a consistent error response format.
-
Describe structured logging, correlation IDs, and PII redaction.
-
Authentication and authorization
-
Propose a scheme (e.g., OAuth2/JWT) and required scopes/roles.
-
Rate limiting
-
Describe the strategy (algorithm, limits, headers) and how it interacts with idempotent retries.
-
Data model
-
Outline database tables (orders, order_items, idempotency store) and key constraints/indexes.
-
Concurrency
-
Explain how you will prevent race conditions and handle concurrent requests using the same idempotency key.
-
Testing
-
Describe unit and integration tests, including concurrency and failure scenarios.
Make minimal, explicit assumptions as needed and keep the design pragmatic and production-oriented.