A sophisticated rate limiting system for AI chatbots that controls usage costs by limiting requests based on user types. Built with Express.js and integrated with Vercel AI SDK using Groq's powerful LLaMA models.
- Beautiful Web Interface: Interactive dashboard for testing and monitoring
- Fixed Window Rate Limiting: 1-hour windows for different user types
- Multi-tier Rate Limits:
- π Guest users: 3 requests/hour (tracked by IP)
- π€ Free users: 10 requests/hour (tracked by user ID)
- β Premium users: 50 requests/hour (tracked by user ID)
- Cost-Effective: Rate limits are checked BEFORE calling AI APIs
- Groq AI Integration: Real AI responses via Groq's LLaMA models
- JWT Authentication: Secure user authentication system
- Comprehensive Testing: Full test suite with Jest
- Clean API: RESTful endpoints with clear error messages
- Mobile Responsive: Works perfectly on all devices
GET /- Interactive web dashboard with authentication and chat
POST /api/chat- Send message to AI (rate limited)POST /api/auth/login- Authenticate and get JWT tokenGET /api/status- Check remaining requests for current user
POST /api/auth/register- Register new user (demo)GET /api/auth/users- Get demo users infoGET /api/limits- Get rate limits configurationGET /api/health- Health check with system infoGET /api/chat/models- Available Groq AI models
- Clone and setup:
cd "/home/saiful/Desktop/poridhi/Exam/Rate Limiter"
npm install- Environment Setup:
cp .env.example .env
# Edit .env file with your GROQ_API_KEY from https://console.groq.com/keys- Start the server:
npm start
# Open http://localhost:3000 in your browser- Use the Web Interface:
- Click on demo users to quickly login
- Or login as guest for IP-based rate limiting
- Chat with AI and see rate limits in real-time
- Monitor your usage with live status updates
NODE_ENV=development
PORT=3000
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
GROQ_API_KEY=your-groq-api-key-here
# Rate Limiting Configuration
GUEST_LIMIT=3
FREE_LIMIT=10
PREMIUM_LIMIT=50
WINDOW_SIZE_HOURS=1The system includes demo users for testing:
| Username | Password | Type | Limit |
|---|---|---|---|
freeuser |
password123 |
free | 10 req/hour |
premiumuser |
password123 |
premium | 50 req/hour |
curl -X POST http://localhost:3000/api/chat \
-H "Content-Type: application/json" \
-d '{"message": "Hello AI!"}'# Login first
TOKEN=$(curl -s -X POST http://localhost:3000/api/auth/login \
-H "Content-Type: application/json" \
-d '{"username": "freeuser", "password": "password123"}' \
| jq -r '.token')
# Make AI request
curl -X POST http://localhost:3000/api/chat \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
-d '{"message": "Hello AI!"}'curl -H "Authorization: Bearer $TOKEN" \
http://localhost:3000/api/statusnpm test./examples/test-rate-limiter.shnpm test -- --coverage{
"success": true,
"message": "AI response here...",
"remaining_requests": 7,
"user_type": "free",
"model_used": "llama-3.1-8b-instant"
}{
"success": false,
"error": "Too many requests. Free users can make 10 requests per hour.",
"remaining_requests": 0,
"reset_time": "2024-01-15T15:00:00.000Z",
"user_type": "free"
}{
"success": true,
"remaining_requests": 8,
"total_requests": 10,
"user_type": "free",
"reset_time": "2024-01-15T15:00:00.000Z",
"window_info": {
"size": "1 hour",
"reset_in_ms": 3425000
}
}- Fixed Window: Resets every hour at fixed intervals
- In-Memory Storage: Fast lookups with automatic cleanup
- User Tracking: By user ID for authenticated, by IP for guests
- Cost Protection: Limits checked before AI API calls
- JWT-based authentication
- Password hashing with bcrypt
- Input validation and sanitization
- Error handling with appropriate HTTP status codes
- In-memory storage (suitable for single instance)
- For production: Consider Redis for distributed rate limiting
- Automatic cleanup of expired entries
- Configurable limits via environment variables
- Set
NODE_ENV=production - Use a strong
JWT_SECRET - Configure real
GROQ_API_KEY - Set appropriate rate limits
- Use HTTPS in production
- Replace in-memory storage with Redis
- Add request logging and monitoring
- Implement user management database
- Add rate limiting by endpoint
- Set up proper error tracking
-
"Invalid or expired token"
- Check JWT token format and expiry
- Verify JWT_SECRET matches
-
Rate limits not working
- Check system time synchronization
- Verify environment variables
-
AI responses not working
- Ensure GROQ_API_KEY is set correctly
- Check Groq API quota and billing
- Verify API key from https://console.groq.com/keys
# Get current rate limit data (development only)
curl http://localhost:3000/api/debug/rate-limits
# Health check
curl http://localhost:3000/api/healthMIT License - see LICENSE file for details.
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
Built with β€οΈ using Express.js, Vercel AI SDK, and JWT Authentication