Instructions to use WalidAlHassan/ecommerce_backend with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use WalidAlHassan/ecommerce_backend with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="WalidAlHassan/ecommerce_backend")# Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("WalidAlHassan/ecommerce_backend", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use WalidAlHassan/ecommerce_backend with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "WalidAlHassan/ecommerce_backend" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "WalidAlHassan/ecommerce_backend", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/WalidAlHassan/ecommerce_backend
- SGLang
How to use WalidAlHassan/ecommerce_backend with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "WalidAlHassan/ecommerce_backend" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "WalidAlHassan/ecommerce_backend", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "WalidAlHassan/ecommerce_backend" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "WalidAlHassan/ecommerce_backend", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use WalidAlHassan/ecommerce_backend with Docker Model Runner:
docker model run hf.co/WalidAlHassan/ecommerce_backend
- E-commerce Ordering & Payment System
- Overview
- Architecture Overview
- Technology Stack
- Features
- Authentication
- Category Management
- Product Management
- Order Management
- Database Design
- Payment Architecture
- Stripe Integration
- bKash Integration
- Payment Reliability
- Redis Usage
- Design Patterns Used
- Project Structure
- Installation
- Environment Variables
- Database Setup
- Running Locally
- Docker Deployment
- Deployment Guide
- API Documentation
- API Summary
- Health Check
- Testing
- Security Features
- Production Considerations
- Future Improvements
- System Documentation
- Database ERD
- Payment Flow
- License
E-commerce Ordering & Payment System
A production-style Django REST Framework backend developed for a Backend Engineer assessment.
This project demonstrates backend engineering practices including:
- Clean architecture
- REST API design
- JWT authentication
- Database modeling
- Inventory management
- Order processing
- Payment gateway integration
- Design patterns
- Redis caching
- Automated testing
- API documentation
- Docker deployment
Overview
The system is an e-commerce backend where users can:
- Register and authenticate using JWT
- Browse categories and products
- Create orders
- Reserve inventory during checkout
- Make payments through Stripe or bKash
- Track order and payment status
The project is designed with scalability and maintainability in mind by separating responsibilities:
API Layer
|
Serializer Layer
|
Service Layer
|
Business Logic
|
Database / External Providers
Architecture Overview
Client
|
Django REST API
|
----------------------------
| |
Serializer Layer Service Layer
| |
-------- Business Logic ----
|
Database Layer
|
PostgreSQL + Redis
|
External Payment Providers
Stripe / bKash
Technology Stack
Backend
- Python 3.12+
- Django 6.x
- Django REST Framework
- PostgreSQL 16
- Redis 7
- SimpleJWT
- Stripe SDK
- bKash Tokenized Checkout API
- drf-spectacular
- Docker
- Gunicorn
Supported Development Environment
Tested on:
- Arch Linux
- Ubuntu Linux
Features
Authentication
Implemented:
- Custom User model
- JWT authentication
- Registration
- Login
- Token refresh
- Profile management
- Permission control
Endpoints:
POST /api/auth/register/
POST /api/auth/login/
POST /api/auth/token/refresh/
GET /api/auth/profile/
PATCH /api/auth/profile/
Category Management
The category system supports hierarchical product organization.
Example:
Electronics
βββ Laptop
β βββ Gaming Laptop
β βββ Business Laptop
βββ Mobile
Implemented:
- Self-referencing category model
- Parent-child relationships
- Recursive tree generation
- DFS traversal
- Redis caching
Endpoint:
GET /api/categories/tree/
Product Management
Implemented:
- Product CRUD
- Category relationship
- Filtering
- Search
- Pagination
- Ordering
- Permission-based access
Product model:
Product
id
category
name
sku
description
price
stock
status
created_at
updated_at
Database protections:
- Price validation
- Foreign key integrity
- Indexed lookup fields
Order Management
The order system handles:
- Order creation
- Order item creation
- Stock validation
- Inventory locking
- Transaction safety
- Order lifecycle management
Order statuses:
PENDING
PAID
PROCESSING
SHIPPED
COMPLETED
CANCELLED
Order processing flow:
Customer
|
Create Order
|
Validate Stock
|
Lock Inventory
(select_for_update)
|
Create Order Items
|
Calculate Total
|
Create Payment
|
Payment Confirmation
|
Order Status = PAID
Critical operations use:
transaction.atomic()
select_for_update()
to prevent inventory race conditions.
Database Design
The system uses PostgreSQL with relational database modeling.
Entity Relationship Overview
User
|
|
Order
|
|
OrderItem
|
|
Product
|
|
Category
Order
|
|
Payment
Category Model
Category
id
name
slug
parent_id
created_at
updated_at
Supports:
- Nested categories
- Recursive traversal
- Cached category trees
Product Model
Product
id
category_id
name
sku
price
stock
status
created_at
updated_at
Database protections:
- Non-negative price constraint
- Foreign key relationships
- Query optimization indexes
Order Model
Order
id
user_id
total_amount
status
created_at
updated_at
Payment Model
Payment
id
order_id
provider
status
amount
transaction_id
provider_payment_id
created_at
updated_at
Reliability features:
- Amount constraints
- Unique transaction identifiers
- Payment status protection
- Webhook tracking
Payment Architecture
The payment system uses:
- Strategy Pattern
- Factory Pattern
- Service Layer Pattern
Architecture:
PaymentService
|
PaymentStrategyFactory
|
----------------------------
| |
StripePaymentStrategy BkashPaymentStrategy
| |
Stripe SDK bKash Client
| |
Stripe API bKash API
The order system does not directly depend on payment providers.
Stripe Integration
Implemented:
- PaymentIntent creation
- Client secret generation
- Payment tracking
- Webhook verification
- Idempotent event processing
- Automatic order updates
Webhook endpoint:
POST /api/payments/webhooks/stripe/
Flow:
Customer
β
Create Payment
β
Stripe PaymentIntent
β
Stripe Webhook
β
Signature Verification
β
Webhook Processing
β
Payment Update
β
Order Status Update
bKash Integration
Implemented:
- Token generation
- Create checkout payment
- Execute payment
- Payment verification
- Callback handling
Callback:
POST /api/payments/bkash/callback/
Flow:
Customer
β
bKash Checkout
β
Callback API
β
PaymentService
β
BkashPaymentStrategy
β
Execute Payment
β
Payment SUCCESS
β
Order PAID
Payment Reliability
Payment processing handles asynchronous gateway communication.
Webhook Idempotency
Every webhook event is stored:
WebhookEvent
provider
event_id
event_type
processed
payload
Duplicate events are prevented using:
event_id UNIQUE constraint
This prevents:
- Duplicate payment updates
- Multiple order status transitions
- Repeated side effects
Payment State Protection
Invalid state transitions are prevented.
Example:
SUCCESS -> FAILED
is not allowed.
This protects against delayed or out-of-order webhook delivery.
Redis Usage
Redis is used for category tree caching.
Flow:
Request Category Tree
|
Check Redis Cache
|
Cache Exists?
/ \
Yes No
| |
Return Generate Tree
|
Save Cache
Design Patterns Used
Service Layer Pattern
Business logic is separated from views.
Example:
APIView
|
OrderService
|
Models
Used in:
- OrderService
- PaymentService
- CategoryService
Strategy Pattern
Payment providers implement a common interface:
PaymentStrategy
|
-----------------
| |
Stripe bKash
Adding a new payment provider does not require changing order logic.
Factory Pattern
Provider selection is handled by:
PaymentStrategyFactory
The application depends on abstractions instead of concrete payment implementations.
Project Structure
ecommerce_backend/
βββ accounts/
βββ categories/
βββ products/
βββ orders/
βββ payments/
β
β βββ strategies/
β βββ base.py
β βββ factory.py
β βββ stripe.py
β βββ bkash.py
β
βββ common/
β
βββ ecommerce_backend/
β βββ settings.py
β βββ urls.py
β βββ wsgi.py
β
βββ Dockerfile
βββ docker-compose.yml
βββ entrypoint.sh
βββ requirements.txt
βββ schema.yml
βββ manage.py
βββ README.md
Installation
Clone repository:
git clone <repository-url>
cd ecommerce_backend
Create environment:
python -m venv .venv
source .venv/bin/activate
Install dependencies:
pip install --upgrade pip
pip install -r requirements.txt
Environment Variables
Create:
cp .env.example .env
Example:
SECRET_KEY=your_secret_key
DEBUG=True
DB_NAME=ecommerce_backend
DB_USER=ecommerce_user
DB_PASSWORD=password
DB_HOST=localhost
DB_PORT=5432
REDIS_HOST=localhost
REDIS_PORT=6379
STRIPE_SECRET_KEY=
STRIPE_WEBHOOK_SECRET=
BKASH_BASE_URL=
BKASH_APP_KEY=
BKASH_APP_SECRET=
BKASH_USERNAME=
BKASH_PASSWORD=
BKASH_CALLBACK_URL=
Never commit .env.
Database Setup
Run migrations:
python manage.py migrate
Create admin user:
python manage.py createsuperuser
Running Locally
Start Redis:
redis-cli ping
Expected:
PONG
Run server:
python manage.py runserver
Docker Deployment
Build and run:
docker compose up -d --build
Services:
backend
postgres
redis
Architecture:
Nginx
|
Gunicorn
|
Django Application
/ \
PostgreSQL Redis
Deployment Guide
Environment Configuration
- Copy the example environment file:
cp .env.example .env
- Configure the required variables:
- Django
SECRET_KEY - PostgreSQL credentials
- Redis connection
- Stripe API keys
- bKash credentials
- Run database migrations:
python manage.py migrate
Frontend Deployment (Optional)
This project is a backend-focused assessment and does not include a frontend.
If a frontend is developed (e.g. React or Next.js), it can be deployed to Vercel and configured to consume this REST API.
Example architecture:
Vercel (Frontend)
β
βΌ
Django REST API
β
βββ PostgreSQL
βββ Redis
Backend Access via ngrok
For local testing or payment webhook integration, expose the local Django server using ngrok.
Start the development server:
python manage.py runserver
Expose it:
ngrok http 8000
Example public URL:
https://xxxxx.ngrok-free.app
This URL can be used for testing external integrations such as Stripe webhooks and bKash callbacks.
Docker Deployment
Build and start all services:
docker compose up --build
The Docker Compose setup starts:
- Django backend
- PostgreSQL database
- Redis cache
API Documentation
Generated using:
drf-spectacular
Swagger:
http://127.0.0.1:8000/api/docs/
Schema:
http://127.0.0.1:8000/api/schema/
Redoc:
http://127.0.0.1:8000/api/redoc/
API Summary
| Module | Endpoint |
|---|---|
| Authentication | /api/auth/ |
| Categories | /api/categories/ |
| Products | /api/products/ |
| Orders | /api/orders/ |
| Payments | /api/payments/ |
| Health | /api/health/ |
Health Check
Endpoint:
GET /api/health/
Checks:
- Django application
- PostgreSQL
- Redis
Response:
{
"status": "ok",
"database": "ok",
"redis": "ok"
}
Testing
Run:
python manage.py test
Current:
42 tests passing
Coverage:
Authentication:
- Registration
- Login
- JWT authentication
- Permissions
Products:
- CRUD
- Validation
- Filtering
Orders:
- Order creation
- Stock validation
- User isolation
Payments:
- Stripe webhook verification
- Payment processing
- bKash callback handling
Health:
- Database connectivity
- Redis connectivity
Security Features
Implemented:
- JWT authentication
- Password hashing
- Environment-based secrets
- Webhook signature verification
- Database transaction protection
- Permission-based APIs
- User data isolation
Production Considerations
Before deployment:
- Set
DEBUG=False - Configure HTTPS
- Configure CORS
- Use managed PostgreSQL
- Use managed Redis
- Configure logging
- Add monitoring
- Run migrations safely
Future Improvements
Possible extensions:
- Celery background jobs
- Email notifications
- Analytics dashboard
- Recommendation system
- Elasticsearch integration
- CI/CD pipeline
- Kubernetes deployment
System Documentation
System Architecture
The backend follows a layered architecture:
Database ERD
The database design includes:
- Users
- Categories
- Products
- Orders
- OrderItems
- Payments
- Webhook Events
Payment Flow
Stripe Payment Flow
bKash Payment Flow
License
MIT License
Developed as a Backend Engineer assessment project.



