A sophisticated and production-ready Multi-Level Marketing (MLM) microservice built using FastAPI, PostgreSQL, and Redis. It manages user network hierarchies, spillover logic, bonus calculations, rank evaluations, and reporting — designed to integrate into larger microservices architectures.
- Register users with
parent_id
- Forced matrix support via MAX_CHILDREN spillover logic
- Automatically assigns
level
in the network - Fetch user downlines
- Referral-based bonus distribution (direct & indirect)
- Configurable per-level bonus amounts
- Trigger-based logic (referral, purchase, etc.)
- Bonus status management (pending, paid)
- Bonus history for each user
- Dynamic rank assignment (e.g., Bronze, Silver, Gold)
- Based on downline size or custom rules
- Get last 7-day earnings for a user
- Used for payouts or user analytics
- Caches user data and downlines
- Speeds up network queries and reduces DB load
- Framework: FastAPI
- Database: PostgreSQL (SQLAlchemy + Alembic)
- Cache: Redis
- Containerization: Docker
- Testing: Manual seed script via
test_data.py
Set ENV VARS according to the .env.example
file given in the app/configs
directory.
python test_data.py
This will:
- Create a root MLM user
- Add multiple children
- Trigger referral bonuses
MAX_CHILDREN = 3
BONUS_MAP = {
1: 10.0, # Direct
2: 5.0,
3: 2.0,
4: 1.0
}
RANKS = [
("Bronze", 3),
("Silver", 10),
("Gold", 25),
("Diamond", 50)
]
Method | Route | Description |
---|---|---|
POST |
/user/register |
Add user to MLM tree |
GET |
/user/downline/{user_id} |
Get user’s direct downlines |
POST |
/bonus/bonus |
Trigger bonus distribution |
GET |
/bonus/bonus/user/{user_id} |
Get user bonus history |
GET |
/bonus/bonus?status=pending |
Admin: list bonuses |
PATCH |
/bonus/bonus/{id}/mark-paid |
Admin: mark bonus paid |
POST |
/ranks/evaluate/{user_id} |
Evaluate and assign rank |
GET |
/reports/weekly/{user_id} |
Weekly report of earnings |
Irfan Ahmad – Backend Engineer
📧 Contact | 🔗 GitHub
This microservice is designed to work with an external Authentication Service for user registration and login. The user_id
is assumed to be passed in from that service.
This microservice has also been integrated into an MLM Gateway along with the Authentication Service
A Rust implementation of the same MLM logic, built for ultra-performance using Actix, SeaORM, and Redis, also exists here