A scalable, async-first e-commerce backend built with FastAPI, PostgreSQL, Redis, Celery, and Stripe. Designed to demonstrate production-grade backend engineering: clean architecture, concurrency-safe inventory, transactional order processing, and background task pipelines.
app/
├── api/v1/ # Thin HTTP handlers — no business logic
├── services/ # Business logic layer
├── repositories/ # Data access layer (repository pattern)
├── models/ # SQLAlchemy 2.0 ORM models
├── schemas/ # Pydantic v2 request/response schemas
├── core/ # Security (JWT, bcrypt), exception hierarchy
├── db/ # Engine, session factory
├── tasks/ # Celery async workers
├── middleware/ # Rate limiting
├── dependencies/ # FastAPI dependency injection (auth)
└── utils/ # Redis cache helpers, structured logging
Request flow:
Route → Dependency (auth) → Service → Repository → Database
Business logic never leaks into routes. Routes never touch the database directly.
| Layer | Technology |
|---|---|
| API Framework | FastAPI 0.115 |
| Database | PostgreSQL 16 + SQLAlchemy 2.0 (async) |
| Migrations | Alembic |
| Cache / Queue | Redis 7 |
| Background Jobs | Celery 5 + Flower |
| Payments | Stripe Checkout + Webhooks |
| Auth | JWT (access + refresh tokens) + bcrypt |
| Validation | Pydantic v2 |
| Rate Limiting | SlowAPI |
| Logging | Structlog (JSON in prod) |
| Testing | Pytest + pytest-asyncio + HTTPX |
| Containers | Docker + Docker Compose |
| Table | Purpose |
|---|---|
users |
Customers and admins with role-based access |
refresh_tokens |
Revocable refresh token store |
categories |
Self-referential product taxonomy |
products |
Inventory with SKU, pricing, stock tracking |
product_images |
Multiple images per product |
carts |
Persistent per-user cart (1:1 with user) |
cart_items |
Line items with live price snapshots |
orders |
Immutable order records with status tracking |
order_items |
Frozen product snapshots (name, SKU, price) |
coupons |
Discount codes (percentage or fixed amount) |
payments |
Stripe transaction records |
All primary keys use UUID v4. All timestamps are timezone-aware.
Stock deduction during checkout uses SELECT FOR UPDATE row-level locking:
product = await self.product_repo.get_for_update(product_id)
# Lock held — no other transaction can modify this row
product.stock_quantity -= cart_item.quantityThis prevents overselling under simultaneous checkout requests.
The entire checkout flow runs in a single database transaction:
- Validate and lock all products
- Deduct stock
- Create order + items
- Apply coupon + increment usage
- Clear cart
If any step fails, the transaction rolls back atomically.
class ProductRepository(BaseRepository[Product]):
async def get_for_update(self, product_id) -> Product | None:
# SELECT ... FOR UPDATE
async def get_filtered(self, params) -> tuple[Sequence, int]:
# Dynamic filtering, sorting, paginationPayment status is never trusted from the frontend. All payment confirmations come through Stripe webhooks with HMAC signature verification:
event = stripe.Webhook.construct_event(payload, sig_header, webhook_secret)POST /api/v1/auth/register Register new customer
POST /api/v1/auth/login Get access + refresh tokens
POST /api/v1/auth/refresh Rotate refresh token
GET /api/v1/auth/me Current user profile
GET /api/v1/products List with filtering, sorting, pagination
GET /api/v1/products/{id} Product detail
POST /api/v1/products Create product [admin]
PATCH /api/v1/products/{id} Update product [admin]
DELETE /api/v1/products/{id} Delete product [admin]
Query params: search, category_id, min_price, max_price, in_stock, sort_by, sort_order, page, page_size
GET /api/v1/cart Get current user's cart
POST /api/v1/cart/items Add item (validates stock)
PATCH /api/v1/cart/items/{id} Update quantity
DELETE /api/v1/cart/items/{id} Remove item
POST /api/v1/orders/checkout Create order from cart
GET /api/v1/orders Order history
GET /api/v1/orders/{id} Order detail
POST /api/v1/payments/create-checkout Create Stripe Checkout session
POST /api/v1/payments/webhook Stripe webhook handler
POST /api/v1/coupons Create coupon [admin]
POST /api/v1/coupons/apply Validate and preview discount
GET /api/v1/admin/orders All orders with filters
PATCH /api/v1/admin/orders/{id}/status Update order status
GET /api/v1/admin/analytics/overview Revenue and key metrics
- Docker & Docker Compose
- (Optional) Python 3.12 + PostgreSQL + Redis for local dev
# Clone and configure
git clone <repo>
cd ecom
cp .env.example .env
# Edit .env with your STRIPE_SECRET_KEY and STRIPE_WEBHOOK_SECRET
# Start all services
docker compose up --build
# Run migrations (first time)
docker compose exec api alembic upgrade head
# API available at http://localhost:8000
# Flower (Celery monitor) at http://localhost:5555
# Docs at http://localhost:8000/docs (DEBUG=true only)python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
pip install -r requirements.txt
cp .env.example .env
# Configure DATABASE_URL, REDIS_URL, STRIPE keys
# Run migrations
alembic upgrade head
# Start server
uvicorn app.main:app --reload
# Start Celery worker (separate terminal)
celery -A app.tasks.celery_app worker --loglevel=info# Create a new migration after model changes
alembic revision --autogenerate -m "describe your change"
# Apply all pending migrations
alembic upgrade head
# Rollback one migration
alembic downgrade -1
# View migration history
alembic history# Install test dependencies (included in requirements.txt)
pip install -r requirements.txt
# Run all tests (uses in-memory SQLite — no external services needed)
pytest
# With verbose output and coverage
pytest -v --tb=short
# Run specific test module
pytest app/tests/test_auth.py -vTests use an in-memory SQLite database and HTTPX async test client. No real Stripe or Redis connections are required to run the test suite.
| Variable | Description | Default |
|---|---|---|
DATABASE_URL |
PostgreSQL connection (asyncpg) | Required |
REDIS_URL |
Redis connection | redis://localhost:6379/0 |
SECRET_KEY |
JWT signing secret | Required (change in prod) |
ACCESS_TOKEN_EXPIRE_MINUTES |
Access token TTL | 30 |
REFRESH_TOKEN_EXPIRE_DAYS |
Refresh token TTL | 7 |
STRIPE_SECRET_KEY |
Stripe secret key | Required for payments |
STRIPE_WEBHOOK_SECRET |
Stripe webhook signing secret | Required for webhooks |
STRIPE_SUCCESS_URL |
Redirect after successful payment | http://localhost:3000/checkout/success |
STRIPE_CANCEL_URL |
Redirect after cancelled payment | http://localhost:3000/checkout/cancel |
CELERY_BROKER_URL |
Celery broker | redis://localhost:6379/1 |
CELERY_RESULT_BACKEND |
Celery results | redis://localhost:6379/2 |
DEBUG |
Enable debug mode + Swagger UI | false |
- Create a Stripe account and get your API keys from the Dashboard
- Set
STRIPE_SECRET_KEYin your.env - For webhooks, install the Stripe CLI and forward events locally:
stripe listen --forward-to localhost:8000/api/v1/payments/webhook
- Copy the webhook signing secret to
STRIPE_WEBHOOK_SECRET
Payment flow:
- Customer completes checkout →
POST /api/v1/orders/checkout→ order created (status:pending) - Frontend calls
POST /api/v1/payments/create-checkout→ receives Stripe Checkout URL - Customer completes payment on Stripe hosted page
- Stripe calls
POST /api/v1/payments/webhook→ order status updated topaid - Background task fires → sends confirmation email
Celery workers process two queues:
email— order confirmations, shipment notificationsorders— post-payment processing
Tasks use bind=True with max_retries=3 and exponential backoff.
Monitor tasks via Flower at http://localhost:5555.