A high-performance, secure payment processing system built with FastAPI, implementing double-entry accounting, JWT authentication, and ACID-compliant financial operations.
This project represents a production-ready financial backend designed to handle sensitive payment operations securely. Unlike simple CRUD applications, this system implements core fintech principles such as Double-Entry Ledger Accounting, Idempotency, and Race Condition Handling.
π Enterprise-Grade Security
- JWT-based stateless authentication with refresh token rotation.
- Bcrypt password hashing & salt.
- Role-Based Access Control (RBAC) middleware.
π° Robust Financial Engine
- Double-Entry Ledger: Every transaction has a balanced debit and credit entry.
- Idempotency: Prevents duplicate processing of the same request.
- ACID Transactions: Guarantees data integrity using PostgreSQL transaction blocks.
- Money Holds: Pre-authorization logic (Escrow support).
π High Performance
- Async I/O with
asyncpgconnection pooling. - Optimized database indexing for financial queries.
- Pydantic v2 for lightning-fast data validation.
The system follows a layered architecture pattern ensuring separation of concerns.
graph TD
Client[Client Application] -->|HTTPS/JSON| API_GW[FastAPI Gateway]
subgraph "Backend Services"
API_GW --> Auth[Auth Service]
API_GW --> Payment[Payment Service]
API_GW --> Ledger[Ledger Service]
API_GW --> Account[Account Service]
end
subgraph "Data Persistence"
Payment -->|Write| DB[(PostgreSQL Primary)]
Ledger -->|Write| DB
Auth -->|Read/Write| DB
end
style API_GW fill:#009688,stroke:#333,stroke-width:2px,color:white
style DB fill:#336791,stroke:#333,stroke-width:2px,color:white
payment-backend/
βββ app/
β βββ api/ # Route handlers (v1)
β βββ core/ # Config, Security, Database setup
β βββ models/ # SQLAlchemy ORM models
β βββ schemas/ # Pydantic data schemas
β βββ services/ # Business logic (Payment, Auth, Ledger)
β βββ utils/ # Helper functions
βββ alembic/ # Database migrations
βββ tests/ # Pytest suites
βββ .env.example # Environment variables template
βββ main.py # Application entry point
βββ requirements.txt # DependenciesThe core of the system relies on the relationship between Transactions and Ledger Entries.
erDiagram
USERS ||--o{ ACCOUNTS : owns
ACCOUNTS ||--o{ LEDGER_ENTRIES : has
TRANSACTIONS ||--|{ LEDGER_ENTRIES : generates
PAYMENT_INTENTS ||--|| TRANSACTIONS : initiates
USERS {
uuid id PK
string email
string password_hash
}
ACCOUNTS {
string account_number PK
decimal balance
string currency
}
TRANSACTIONS {
uuid id PK
string status
timestamp created_at
}
LEDGER_ENTRIES {
uuid id PK
decimal amount
string entry_type "DEBIT/CREDIT"
}
- Python 3.9+
- PostgreSQL 14+
- Git
-
Clone the repository
git clone https://github.com/Ir-Rafi/Payment-Processing-Backend-Industry-Grade-.git cd Payment-Processing-Backend-Industry-Grade- -
Virtual Environment Setup
python -m venv venv # Windows venv\Scripts\activate # macOS/Linux source venv/bin/activate
-
Install Dependencies
pip install -r requirements.txt
-
Environment Configuration Create a
.envfile based on the example:cp .env.example .env
Update
DATABASE_URLandJWT_SECRET_KEYin the.envfile. -
Database Migration
# If using Alembic alembic upgrade head # Or using raw SQL psql -U postgres -d fincore_day1 -f schema/init.sql
-
Launch Server
uvicorn main:app --reload
Access the API at:
http://localhost:8000/docs
Detailed documentation is available via Swagger UI (/docs). Here are the primary endpoints:
| Module | Method | Endpoint | Description |
|---|---|---|---|
| Auth | POST |
/auth/register |
Register new user & create wallet |
| Auth | POST |
/auth/login |
Get Access & Refresh Tokens |
| Payment | POST |
/payments |
Initiate a payment (Idempotent) |
| Payment | POST |
/transfer |
P2P Fund Transfer |
| Refund | POST |
/refunds |
Process full/partial refunds |
| Account | GET |
/accounts/{id}/balance |
Get real-time balance |
| Account | GET |
/accounts/history |
Get transaction audit log |
Request:
POST /api/v1/payments
{
"idempotency_key": "unique-uuid-v4",
"from_account": "ACC_1001",
"to_account": "ACC_2002",
"amount": 50.00,
"currency": "USD",
"description": "Service payment"
}Response:
{
"status": "success",
"transaction_id": "tx_789xyz",
"new_balance": 950.00,
"timestamp": "2024-03-15T10:30:00Z"
}Instead of just updating a balance column (e.g., balance = balance - 50), this system creates immutable ledger entries for every transaction. This ensures that money is never created or destroyed, only moved.
| Account | Entry Type | Amount |
|---|---|---|
| Sender (Alice) | DEBIT | -$50.00 |
| Receiver (Bob) | CREDIT | +$50.00 |
| System Check | SUM | $0.00 |
Network failures can cause requests to be retried. We use an idempotency_key header/field. If the server receives a key it has already processed, it returns the stored result of the original operation without re-processing the payment.
Contributions are welcome!
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/NewFeature) - Commit your Changes (
git commit -m 'Add some NewFeature') - Push to the Branch (
git push origin feature/NewFeature) - Open a Pull Request
Ir-Rafi
Distributed under the MIT License. See LICENSE for more information.