A production-ready, high-performance RESTful API for a real-time auction platform. Built with FastAPI and PostgreSQL, this system handles secure live bidding, enterprise-grade multi-device authentication with sliding-window token rotation, automated Stripe checkout workflows, transactional Brevo OTP email verification, and scheduled background jobs to process expired auctions seamlessly.
BidBazaar is engineered to solve the complex concurrency, security, and synchronization problems inherent in live auction platforms. It serves as a robust, scalable backend enabling users to list items, securely bid in real-time without refreshing, and seamlessly transition into an automated checkout flow when they win.
Whether viewed by non-technical business stakeholders evaluating enterprise reliability or senior engineers reviewing architectural patterns, BidBazaar demonstrates how modern high-frequency web applications maintain zero-trust security while delivering instantaneous user experiences.
When facilitating peer-to-peer live auctions, platforms require an impenetrable, high-concurrency infrastructure to:
- Handle High-Frequency Bidding: Stream live, concurrent bids in real-time via WebSockets without data collisions or race conditions on item prices.
- Guarantee Account & Session Security: Protect user accounts against token theft using sliding-window JWT refresh token rotation, unique token IDs (
jti), and multi-device session revocation. - Automate Password Recovery: Provide self-service account recovery via secure 6-digit One-Time Password (OTP) verification delivered reliably through the Brevo Email API.
- Manage Lifecycle Automation: Autonomously detect when auctions expire, correctly identify winning bidders, and prune expired authentication artifacts from the database without human intervention.
- Facilitate Split-Payments: Ensure transaction integrity by capturing a 5% platform fee while routing 95% of funds directly to sellers via Stripe Connect Express.
- Maintain Communication: Automatically email buyers and sellers at every critical step of the transaction lifecycle (welcome emails, winning notifications, receipts, and refund alerts).
- β‘ Real-Time Bidding Engine: WebSockets stream the highest bid live to all connected clients instantly, ensuring zero latency and eliminating stale price data.
- π Enterprise Authentication & Token Rotation: Stateless JWT access tokens paired with stateful, sliding-window refresh tokens. Supports single-session logout (
/auth/logout), universal multi-device sign-out (/auth/logout-all), and strict bcrypt password complexity hashing. - π© Brevo OTP Password Recovery: Integrated with the Brevo HTTP API to deliver secure, time-sensitive 6-digit verification codes (
/auth/forget-password). Verified OTPs issue short-lived cryptographic authorization tokens (/auth/verify-password) required to finalize password resets (/auth/reset-password). - π Background Task Automation: Integrated
APSchedulerruns dedicated background jobs that natively scan for and close expired auctions, mint secure one-time Stripe checkout tokens, and automatically purge revoked or expired refresh tokens and OTP records (clean_expired_auth_data). - π³ Stripe Connect Express Integration: End-to-end automated checkout capturing a 5% platform fee and transferring 95% of funds securely to the seller. Asynchronous webhooks automatically verify cryptographic signatures and finalize transactions.
- πΈ Refund Automation: Seamless API integration allowing verified buyers to initiate full refunds, automatically reversing Stripe payment intents, updating database records, and notifying all stakeholders.
- π§ Transactional SMTP & Brevo Emails: Automated, beautifully styled HTML email notifications with clean text fallbacks for welcome messages, winning bids, payment receipts, and password resets.
- ποΈ Strict Data Validation & ORM: Backed by
PostgreSQLandSQLModel(SQLAlchemy) with enforced foreign-key constraints, comprehensive table indexing, and strictPydanticinput sanitization. - π§ͺ 100% Automated Test Coverage: A comprehensive suite of 82 automated unit and integration tests spanning every route, service, utility, and scheduler job, verified without coverage shortcuts (
# pragma: no cover).
- Framework & Server: FastAPI (Python 3.10+) & Uvicorn (ASGI)
- Real-Time Engine: WebSockets (Bi-Directional Streaming)
- Database & Migrations: PostgreSQL & Alembic
- ORM & Data Layer: SQLModel / SQLAlchemy 2.0+
- Payment Processing: Stripe API & Webhooks
- Email Delivery Engines: Brevo API (HTTP REST) & Transactional SMTP (
httpx,smtplib) - Job Scheduling: APScheduler (
AsyncIOScheduler) - Authentication & Security: Python-JOSE (
JWT), Passlib (bcrypt), UUIDv4 Token Tracking - Testing & Quality Assurance:
pytest,pytest-cov,FastAPI TestClient,SQLiteIn-Memory Fixtures - Environment Management:
python-dotenv - Containerization & Orchestration: Docker, Docker Compose, & Kubernetes (StatefulSets, HPA, Ingress)
The codebase strictly adheres to modular separation of concerns, dividing presentation routes, core business services, database models, and security layers:
BidBazaar/
β
βββ config.py # Global Configuration & Environment Variable Loader
βββ database.py # PostgreSQL Engine & Session Dependency Generator
βββ exceptions.py # Standardized Global & Request Validation Exception Handlers
βββ scheduler.py # APScheduler Background Jobs (Auction Closures & Auth Cleanup)
βββ security.py # JWT Cryptography, Token Revocation Checks & Password Hashing
βββ models.py # SQLModel Database Entities (User, RefreshToken, OTP_Table, Item, Bid)
βββ schema.py # Pydantic Schemas for Request Payload Sanitization
βββ main.py # Application Entry Point, Lifespan Events & Router Registrations
β
βββ .env.example # Template of Required Environment Variables
βββ .gitignore # Excludes Virtual Environments, Cache, and Secrets from Git
βββ requirements.txt # Complete UTF-8 Pinned Dependencies
βββ Dockerfile # Multi-Stage Container Blueprint for the API Server
βββ docker-compose.yml # Local Development Container Orchestration
βββ kubernetes-bidbazaar.yml # Production Kubernetes Cluster Architecture (StatefulSet, HPA, Ingress)
βββ alembic.ini # Alembic Migration Configuration
β
βββ alembic/ # Database Migration Scripts & Metadata
β βββ env.py # Dynamic Connection & SQLModel Metadata Binding
β βββ versions/ # Chronological Version Control for Database Schema Changes
β
βββ routes/ # HTTP & WebSocket API Endpoint Definitions
β βββ auth.py # Signup, Login, Refresh, Logout, Logout-All, & OTP Recovery Routes
β βββ items.py # Auction Listing Creation & Filtered Search Endpoints
β βββ payment.py # Stripe Onboarding, Checkout Links, Webhooks & Refunds
β βββ websockets.py # Real-Time WebSocket Rooms for Live Item Bidding
β
βββ services/ # Core Business Logic & Database Transaction Isolation
β βββ auth_services.py # Authentication Workflow & Token State Management Logic
β βββ auth_email_services.py # Brevo API Email Client for OTP Delivery
β βββ email_services.py # Transactional SMTP Notification Templates & Sending Logic
β βββ items_services.py # Item Creation, Queries & Seller Filters
β βββ payment_services.py # Stripe API Checkout & Webhook Processing
β βββ websockets_services.py # WebSocket Connection Manager & Broadcast Synchronization
β
βββ tests/ # Automated Test Suite (100% Statement Coverage)
βββ conftest.py # Fixtures & Isolated In-Memory SQLite Setup
βββ test_auth.py # Core Registration & Login Verification
βββ test_advanced_auth.py # Token Rotation, Multi-Device Logout & Brevo OTP Recovery Tests
βββ test_database.py # SQLModel Engine & Session Behavior
βββ test_email.py # SMTP & Mocked Brevo Email Verification
βββ test_items.py # Auction Listing Integrity & Query Filtering
βββ test_main.py # Lifespan Events & Exception Handler Verification
βββ test_payment.py # Stripe Webhook Crypto-Signature & Token Generation Tests
βββ test_scheduler.py # Background APScheduler Automated Closures & Pruning
βββ test_websockets.py # Live Bidding Broadcasts & Concurrency Checks
BidBazaar is orchestrated for enterprise Kubernetes environments, featuring a PostgreSQL StatefulSet, Horizontal Pod Autoscaling (HPA) for the FastAPI backend, and Ingress routing. To deploy the entire cluster architecture locally via Minikube or Docker Desktop:
kubectl apply -f kubernetes-bidbazaar.ymlThe fastest and most reliable way to run the platform locally without installing PostgreSQL directly on your host machine.
- Clone the Repository
git clone <your-repo-url>
cd BidBazaar- Configure Environment Variables Copy the example configuration file and input your credentials:
cp .env.example .env(Ensure STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET, SMTP_PASSWORD, and BREVO_API are filled in)
- Launch Container Suite
docker-compose up --buildDocker automatically provisions a dedicated PostgreSQL database (db), runs all Alembic migrations (alembic upgrade head), and starts the FastAPI server (api) at http://localhost:8000.
Prerequisites
- Python 3.10+
- PostgreSQL server installed and running locally
- Stripe CLI (for testing local payment webhooks)
1. Clone and Create Virtual Environment
git clone <your-repo-url>
cd BidBazaar
python -m venv venv
venv\Scripts\activate # On Windows
# source venv/bin/activate # On macOS / Linux
pip install -r requirements.txt2. Setup Database & Credentials
Create your .env file and configure your local PostgreSQL connection string:
DATABASE_URL=postgresql://postgres:password@localhost:5432/bidbazaar_dbRun database migrations to build all tables (users, refresh_tokens, otp_codes, items, bids):
alembic upgrade head3. Run the Development Server
uvicorn main:app --reload --host 0.0.0.0 --port 8000Interactive Swagger API documentation will be immediately accessible at http://localhost:8000/docs.
4. Stripe Webhook Forwarding (Local Testing) In a separate terminal, use the Stripe CLI to forward events directly to your local application:
stripe listen --forward-to localhost:8000/payment/webhook| Method | Endpoint | Description |
|---|---|---|
| POST | /auth/signup |
Register a new user account with strict password complexity enforcement |
| POST | /auth/login |
Authenticate with username/password to receive access and refresh tokens |
| POST | /auth/refresh |
Exchange a valid sliding-window refresh token for a new access token |
| POST | /auth/logout |
Revoke the provided refresh token (is_revoked = True) to end session |
| POST | /auth/logout-all |
Universal sign-out: revokes all active refresh tokens across all user devices |
| POST | /auth/forget-password |
Dispatch a time-sensitive 6-digit verification code to registered email via Brevo |
| POST | /auth/verify-password |
Verify the 6-digit code and obtain a short-lived password reset authorization token |
| POST | /auth/reset-password |
Finalize password change using the reset token and revoke all existing sessions |
| Method | Endpoint | Description |
|---|---|---|
| POST | /items/ |
Create a new auction item listing (requires valid JWT access token) |
| GET | /items/ |
Retrieve all active items (Supports ?search= and ?sort_by= query filters) |
| GET | /items/seller/{username} |
Retrieve public listings published by a specific seller |
| Method | Endpoint | Description |
|---|---|---|
| WS | /bids/{item_id}?token= |
Connect to the WebSocket room for a specific item to broadcast and receive live bids |
| Method | Endpoint | Description |
|---|---|---|
| POST | /payment/onboard |
Generate an automated Stripe Connect Express onboarding link for sellers |
| GET | /payment/checkout/{item_id}?token= |
Validate one-time cryptographic token and redirect winning bidder to Stripe Checkout |
| POST | /payment/webhook |
Asynchronous webhook ingest verifying Stripe crypto-signatures and settling item status |
| POST | /payment/refund/{item_id} |
Initiate an automated refund reversing Stripe payment intents and notifying buyers |
BidBazaar enforces uniform, standardized JSON error payloads ({"error": true, "message": "...", "path": "..."}) across all endpoints, ensuring seamless frontend integration without unhandled server stack traces:
400 Bad Request: Business logic violations, duplicate registrations, invalid OTP verification codes, or malformed Stripe signatures.401 Unauthorized: Expired/invalid JWTs, incorrect credentials, revoked refresh tokens, or expired password reset tokens.403 Forbidden: Unauthorized item modifications or expired one-time checkout links.404 Not Found: The requested auction item, user profile, or resource does not exist.422 Unprocessable Entity: Request validation failures (e.g., missing required fields, password format non-compliance, invalid types).500 Internal Server Error: Standardized fallback catching unexpected server exceptions securely without leaking internal architecture.
- Cloud-Native Kubernetes Orchestration: Architecting a production-ready Kubernetes cluster featuring PostgreSQL StatefulSets with persistent volume claims (PVCs), Horizontal Pod Autoscalers (HPA) for traffic-based scaling, and Ingress controllers for clean, prefix-based API routing.
- Enterprise Security Architecture: Designing zero-trust authentication workflows where stateless JWT access tokens are protected by stateful database-tracked refresh tokens (
jti), allowing instant session termination (/auth/logoutand/auth/logout-all) while maintaining high performance. - Transactional API Integration: Combining
httpxasynchronous REST calls with Brevo API to guarantee high-deliverability 6-digit OTP delivery for self-service account recovery. - Automated Memory & DB Hygiene: Using
APSchedulerbackground threads (clean_expired_auth_data) to prevent database bloat by continuously pruning expired OTP records and revoked tokens without impacting API request response times. - Strict Typing & Documentation: Enforcing comprehensive Google-style docstrings and precise Python type hints across 100% of routes, services, schemas, and models.
- Test-Driven Reliability: Building an exhaustive, deterministic suite of 82 automated tests (
100% total statement coverage) usingpytestandSQLModelin-memory SQLite dependency injection, guaranteeing confidence in production deployments.
MIT License - feel free to use and adapt this architecture for educational or commercial purposes.
Author: Riya Chaleria
LinkedIn: Riya Chaleria
Email: riyachaleria@gmail.com