Skip to content

About

Multi-tenant order and inventory backend with RBAC, transactional workflows, concurrency control, idempotency, audit logging and automated tests.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Order Management API

A multi-tenant API for customers, products, inventory, and order lifecycles backed by PostgreSQL.

CI Python PostgreSQL License

Core Workflow

Create draft order → Confirm → Process → Ship
                     └──────────────────→ Cancel

Orders are created in draft. Confirmation validates the order, deducts inventory in the same database transaction, and writes an audit record. Cancellation restores stock only for orders that were confirmed or processing.

Reliability Guarantees

  • Inventory changes during confirmation, cancellation, and stock adjustment use PostgreSQL row locks.
  • The confirmation transaction validates stock before deduction; a failed validation is not committed.
  • Order mutations use an explicit version, so stale writes return OPTIMISTIC_LOCK_CONFLICT.
  • POST /api/v1/orders requires an Idempotency-Key; retries with the same scoped key and payload return the original order.
  • Business records are scoped to the authenticated user's organization.
  • Order changes and stock adjustments create tenant-scoped audit records.

Architecture

Architecture diagram

Router → Service → Repository → PostgreSQL

Routers parse requests and apply dependencies. Services enforce business rules and commit complete operations. Repositories provide organization-scoped queries, pagination, and row-locking operations.

More detail: Architecture.

Order State Machine

Order state machine

  • A draft order may be changed, have items added or removed, or be deleted.
  • Only a non-empty draft can be confirmed.
  • confirmed → processing → shipped is the normal fulfillment path.
  • draft, confirmed, and processing can transition to cancelled; shipped cannot.

Concurrency and Idempotency

During an inventory-changing transition, the service locks the order and then locks product rows in ascending product-ID order.

Lock order → validate state/version → lock products → validate stock
    → update inventory and order → write audit record → commit

Two confirmations competing for insufficient stock cannot both succeed. The PostgreSQL integration suite verifies that exactly one confirmation succeeds and available inventory does not become negative.

For order creation, idempotency records are scoped to organization_id, user_id, and Idempotency-Key. The request payload is hashed: an identical retry returns the existing order, while reusing the key with a different payload returns IDEMPOTENCY_CONFLICT.

Multi-Tenancy and Authorization

Bearer-token authentication resolves an active user and organization. Repository queries filter by that organization; cross-tenant objects are returned as RESOURCE_NOT_FOUND. Role checks apply after the tenant boundary is established.

Operation Owner Manager Staff Viewer
Manage users ✓
Create, update, or deactivate products ✓ ✓
Adjust stock ✓ ✓
Create or update customers ✓ ✓ ✓
Create or modify orders ✓ ✓ ✓
Delete draft orders ✓ ✓
View tenant data and audit logs ✓ ✓ ✓ ✓

Owner changes lock active owner rows and reject a change that would leave an organization with no active owner.

API

All business endpoints are under /api/v1; generated OpenAPI documentation is served at /docs.

Area Operations
Authentication Register, login, refresh, logout, current user
Users List, create, retrieve, update, deactivate
Customers List, create, retrieve, update, delete
Products List, create, retrieve, update, deactivate, adjust stock
Orders List, create, retrieve, update, delete draft, manage items
Transitions Confirm, start processing, ship, cancel
Audit List tenant and order audit records
Health GET /health, GET /ready

List endpoints use bounded pagination (page_size up to 100), supported sort fields, optional search, and date filters. Errors use a consistent JSON envelope and every response includes X-Request-ID.

Swagger UI preview

Run Locally

Docker Compose is the supported local path. Copy the example environment file, set a JWT_SECRET_KEY of at least 32 characters, then start the stack:

cp .env.example .env
docker compose up --build -d
curl --fail --show-error http://localhost:8000/ready

The API container applies Alembic migrations before Uvicorn starts. Open http://localhost:8000/docs after readiness succeeds. Set API_PORT and POSTGRES_PORT when the default host ports are unavailable.

Deployment configuration and upgrade considerations: Deployment.

Example Request

After registering, creating a customer and product, create a draft order with an idempotency key. Replace the placeholder IDs and token with values returned by the API.

curl -X POST http://localhost:8000/api/v1/orders \
  -H 'Authorization: Bearer <access-token>' \
  -H 'Idempotency-Key: order-2026-0001' \
  -H 'Content-Type: application/json' \
  -d '{
    "customer_id": "<customer-id>",
    "currency": "CHF",
    "items": [{"product_id": "<product-id>", "quantity": 2}]
  }'

Run the demo for the complete reproducible flow: registration, authentication, customer and product creation, idempotent order creation, confirmation, and stock verification.

Testing

The test suite uses PostgreSQL. It covers unit-level security and domain rules; API integration for authentication, RBAC, tenant isolation, pagination, errors, and audit data; and concurrent refresh-token and inventory-confirmation cases.

CI runs Ruff, alembic upgrade head, alembic check, and pytest with a 90% coverage threshold.

export DATABASE_URL=postgresql+psycopg://orders:orders@localhost:5432/orders_test
export JWT_SECRET_KEY=test-secret-key-with-at-least-32-characters
pytest --cov=order_api --cov-fail-under=90
ruff check src tests
ruff format --check src tests

Concurrent confirmation scenario

Real test: tests/integration/test_orders_extended.py

Operational Concerns

  • /health reports process health; /ready also checks database access.
  • Alembic manages schema changes and runs before the API process in Docker.
  • Structured request logs include request IDs and omit request bodies, passwords, and tokens.
  • Passwords use Argon2. Access tokens validate issuer, audience, expiry, type, subject, and jti; persisted refresh tokens are SHA-256 digests.
  • CORS and trusted-host policies are explicit environment settings.

Repository Structure

src/order_api/
├── api/           versioned routers and request dependencies
├── core/          configuration, database, security, errors, logging
├── models/        SQLAlchemy models
├── repositories/  tenant-scoped queries and locks
├── schemas/       request and response models
├── services/      order, authentication, and resource workflows
└── main.py

Limitations

  • Compose runs one API process and one PostgreSQL instance; it does not provide high availability or multi-region operation.
  • There is no frontend, background worker, message broker, webhook delivery, or external identity-provider integration.
  • Inventory is deducted at confirmation; expiring inventory reservations are not available.
  • Expired refresh tokens and idempotency records are not removed by a scheduled task.
  • Offset pagination and application-level request-body limits have not been extended for high-volume traffic.

Future Work

Possible next areas include inventory reservations, background processing, webhook delivery, and operational exception handling. These are not part of the current API; see V2 design notes.

Documentation

License

Released under the MIT License.

About

Multi-tenant order and inventory backend with RBAC, transactional workflows, concurrency control, idempotency, audit logging and automated tests.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages