Rate Limiting for Banking Transactions
1. Approaches to Implementing Rate Limiting
Rate limiting ensures that a user does not exceed a fixed number of requests per second. Two
common approaches for implementing rate limiting are:
Approach 1: Token Bucket Algorithm
📌 Concept:
● The Token Bucket algorithm allows requests to be processed at a steady rate,
ensuring that bursts of requests are handled without rejecting legitimate traffic.
● A bucket is filled with tokens at a fixed rate (e.g., 5 tokens per second).
● Each request consumes one token; if no tokens are available, the request is denied or
delayed until more tokens are added.
📌 Steps:
1. A bucket with a capacity (C) holds tokens (e.g., C = 5 for 5 requests per second).
2. Tokens are added at a fixed rate (1 per 200ms to maintain 5 per second).
3. If a request arrives when the bucket has tokens, a token is consumed, and the
request is processed.
4. If the bucket is empty, the request is rejected or queued until tokens are refilled.
📌 Pros & Cons:
✅ Allows bursts of requests while maintaining an average rate.
✅ More flexible for banking transactions where occasional high loads are expected.
❌ Requires precise token refill logic and synchronization in distributed systems.
Approach 2: Sliding Window Counter
📌 Concept:
● Maintains a moving window of time (e.g., 1 second) and tracks request counts within
that window.
● If requests exceed the limit (e.g., 5 per second), new requests are rejected.
● Instead of resetting at fixed intervals, it smoothly adjusts based on request
timestamps.
📌 Steps:
1. Each request is timestamped and stored in a queue/hashmap.
2. Expired timestamps (older than 1 second) are removed.
3. If the number of timestamps in the last second is ≤ 5, the request is allowed.
4. Otherwise, the request is rejected.
📌 Pros & Cons:
✅ More accurate control over request rate.
✅ Works well in real-time banking transactions to prevent fraud.
❌ Memory overhead due to storing request timestamps.
❌ Less burst-friendly compared to the token bucket.
Trade-offs Between Approaches
Feature Token Bucket Sliding Window Counter
Handles bursts ✅ Yes ❌ No
Memory Usage ✅ Low ❌ High
Fairness ❌ Less accurate ✅ Strict enforcement
Complexity ❌ More complex ✅ Simpler
Best for High-load banking Fraud prevention
Conclusion
● Sliding Window Counter is chosen as it strictly enforces 5 transactions per second,
making it ideal for fraud prevention in banking transactions at Zeta.
● The Token Bucket approach could be explored for more flexibility if occasional burst
handling is needed.
Scalable Banking API - Transaction
Processing & Consistency
1. API Design & Requirements
The API has three endpoints:
✅ GET /balance/{account_id} – Retrieves the balance of a specific account.
✅ POST /credit – Adds money to an account.
✅ POST /debit – Deducts money while ensuring sufficient funds.
Key Features Implemented:
🔹 Atomicity: Transactions use locks to prevent partial updates.
🔹 Concurrency Handling: Thread locks (Lock()) prevent race conditions.
🔹 Failure Safety: If a transaction fails, no partial changes occur.
🔹 Clear Error Handling: Returns specific HTTP error codes for failures.
2. Database Schema
For a real-world scenario, we'd use a relational database like PostgreSQL:
sql
CopyEdit
CREATE TABLE accounts (
account_id VARCHAR PRIMARY KEY,
balance DECIMAL NOT NULL CHECK (balance >= 0)
);
CREATE TABLE transactions (
id SERIAL PRIMARY KEY,
account_id VARCHAR REFERENCES accounts(account_id),
amount DECIMAL NOT NULL,
transaction_type VARCHAR CHECK (transaction_type IN ('debit',
'credit')),
created_at TIMESTAMP DEFAULT NOW()
);
This ensures data integrity, foreign key relationships, and balance constraints.
3. Ensuring Consistency in Case of Failures
✅ Database Transactions (ACID Compliance):
● In a real system, BEGIN TRANSACTION, COMMIT, ROLLBACK in
PostgreSQL/MySQL ensures atomicity.
● If a debit fails, ROLLBACK prevents partial withdrawals.
✅ Write-Ahead Logging (WAL):
● Ensures crash recovery by recording transactions before applying them.
✅ Redis for Optimistic Locking:
● We can use Redis-based locks to handle concurrency for high-scale transactions.
4. Performance Optimizations
🚀 Indexing: Adding indexes on account_id in the transactions table speeds up queries.
🚀 Caching with Redis: Store frequently accessed balances to reduce DB reads.
🚀 Asynchronous Processing: Use Kafka or RabbitMQ for event-driven updates (e.g., sending
SMS alerts).
Full-Stack Al-Powered Customer Portal
(Building a No-Code-First MVP)
1. MVP Design
(a) Frontend Interface (No-Code Approach)
Since this is a self-service portal, a simple web-based dashboard will do:
● Tools: GlideApps (no-code), Thunkable (mobile app), or React (if coded).
● Features:
○ Login Page – Customers authenticate using their ID.
○ Dashboard –
✅ View account balance.
✅ Apply for a loan (form-based input).
✅ Check dispute history.
○ Loan Eligibility Page –
✅ AI-generated loan eligibility score & recommendation.
(b) Backend Logic
The backend will handle:
✅ Fetching account balance from a database (simulated for now).
✅ Processing loan applications with AI-based scoring.
✅ Retrieving dispute history for a customer.
The loan eligibility logic considers:
● Income
● Credit Score
● Existing Loans
● Debt-to-Income Ratio
(c) AI Logic for Loan Eligibility
A simple rule-based AI system assigns a score:
● Credit Score > 750 & Low Debt → Highly Eligible
● Credit Score 600-750 & Medium Debt → Moderate Eligibility
● Credit Score < 600 or High Debt → Not Eligible
2. API Implementation (FastAPI)
Let's create an API that:
✅ Accepts customer details for loan eligibility.
✅ Returns a loan score and recommendation.
I'll implement this in FastAPI:
Loan Eligibility Api
3. Approach Explanation
(a) Building the MVP in 24 Hours with AI-Assisted Tools
If I had to build this fast, I’d use:
● GlideApps/Thunkable: To build a no-code web/mobile frontend.
● Zapier/n8n: For automating API calls (e.g., fetch balance, check loan status).
● Google Sheets/Airtable: For storing user data without setting up a full DB.
● OpenAI GPT API: To refine loan recommendations with AI.
(b) Using a Low-Code Platform
● Retool: Pre-built UI for customer dashboard & loan processing.
● Power Automate: Automate dispute status updates.
● Bubble.io: Drag-and-drop full-stack web app with backend workflows.
Rapidly Automating a Banking Process
(Workflow & API Integration)
1. Workflow Design
Step 1: Collecting Dispute Data
● A customer submits a dispute form (via a web app or chatbot).
● Required fields: customer_id, transaction_id, dispute_reason,
dispute_description.
Step 2: AI-Based Classification
● A simple rule-based AI system classifies disputes into categories:
○ Fraudulent Transaction
○ Duplicate Charge
○ Unauthorized Access
○ Service Not Provided
Step 3: Assigning Priority Levels
● The system prioritizes disputes based on:
○ Customer history (VIP vs. regular).
○ Transaction amount (higher amounts = higher priority).
○ Past fraud activity (e.g., if the customer has disputed many transactions
before).
Step 4: Routing the Dispute
● High-risk disputes → Fraud Investigation Team
● Medium-risk disputes → General Support Team
● Low-risk disputes → Automated Resolution (e.g., issuing a refund)
Step 5: Notifying the Support Team
● The system sends an automated Slack/Email notification to the assigned team.
● The AI suggests possible resolutions (e.g., refund, account freeze, manual
review).
2. API Implementation (FastAPI)
This API will:
✅ Accept dispute details via a POST request.
✅ Classify the dispute based on predefined AI rules.
✅ Assign priority levels.
✅ Return the recommended action.
Let's implement it:
Python FastAPI Code for Dispute Management
I'll create a clean API implementation in FastAPI with basic AI rules.
Dispute Management Api
3. Approach Explanation
(a) Using AI-Assisted & Low-Code Tools
If I had to implement this with minimal custom code:
● Zapier or n8n: Automate dispute classification and routing.
● Chatbot (Rasa/Chatbot.com): Accept disputes via a conversational interface.
● Airtable/Google Sheets API: Store dispute records for tracking.
● OpenAI GPT API: Improve dispute classification with a trained AI model.
(b) Future AI Improvements
● Machine Learning Model: Train a model on historical disputes to improve
classification.
● NLP-based Sentiment Analysis: Detect urgency from user descriptions.
● Self-learning AI: Adapt priority levels based on resolution success.