A custom rate limiter and API credit system similar to what you see in Gemini/OpenAI/Claude APIs. This was intended as a learning project trying to push the edges of CAP theorem and latency. Completely serverless architecture written for cloudflare workers along with a serverless redis for fun. Below is AI slop for more info :)
A production-ready serverless API management platform built with Cloudflare Workers and Upstash Redis. This platform provides a comprehensive solution for API key management, rate limiting, credit tracking, and multi-tenant plan management.
- API Key Management: Generate, validate, and revoke API keys with crypto-safe security
- Role-Based Access Control (RBAC): Control access with different permission levels (Admin, Developer, Reader)
- Subscription Plans: Four service tiers (Free, Standard, Pro, Test) with customizable limits
- Real-time Rate Limiting: Apply rate limits based on the user's plan with sliding window algorithm
- Credit System: Track and limit API usage with a precise credit-based system
- Multi-tenancy: Support for multiple tenants with completely isolated resources
- Performance Optimized: Ultra-fast response times with intelligent caching and smart cache management
- Comprehensive Testing: 100% coverage with automated E2E test suite including detailed latency tracking
- Production Ready: Deployed globally with monitoring and analytics
- Cloudflare Workers: Serverless compute platform with global edge deployment
- Upstash Redis: Serverless Redis database with sub-10ms latency
- Hono: Ultra-lightweight framework optimized for Cloudflare Workers
- TypeScript: For complete type safety and developer experience
- Zod: Runtime schema validation for bulletproof request handling
| Plan | Rate Limit | Credits | Access |
|---|---|---|---|
| FREE | 50/hour | 1,000 | Public APIs, Basic TODOs |
| STANDARD | 500/hour | 10,000 | All v1 APIs, TODOs, Posts |
| PRO | 5,000/hour | 100,000 | All endpoints (*) |
| TEST | 3/5sec | 9 | All endpoints (for testing) |
- Node.js (16+)
- Upstash Redis account
- Cloudflare account
-
Clone the repository:
git clone https://github.com/yourusername/api-management-platform.git cd api-management-platform -
Install dependencies:
npm install
-
Create
.dev.varsfile with your Upstash Redis credentials:UPSTASH_REDIS_REST_URL=your-upstash-redis-url UPSTASH_REDIS_REST_TOKEN=your-upstash-redis-token
-
Start development server:
npm run dev
-
Deploy to production:
npm run deploy
POST /tenant- Create a new tenantGET /tenant/:tenantId- Get tenant informationGET /tenant- List all tenants (admin only)PATCH /tenant/:tenantId/plan- Update tenant's planPOST /tenant/:tenantId/credits- Add credits to a tenant
POST /keys/create- Generate a new API keyPOST /keys/verify- Validate an API keyGET /keys/:keyId- Get API key detailsGET /keys/tenant/:tenantId- List all keys for a tenantDELETE /keys/:keyId- Revoke an API keyPATCH /keys/:keyId- Update API key details
GET /proxy/todos/:id- Access JSONPlaceholder todos APIGET /proxy/posts/:id- Access JSONPlaceholder posts APIPOST /proxy/custom- Proxy custom API requests
GET /health- System health check and bootstrapGET /cache-stats- Real-time cache performance metrics
All API responses include comprehensive headers for monitoring:
X-Credits-Used: 1
X-Credits-Remaining: 999
X-Credits-Cost: 1
X-Credits-Pre-Call: 0
X-RateLimit-Limit: 50
X-RateLimit-Remaining: 49
X-Cache-Hit: validation-cache,always-fresh
X-Lookup-Time: 45npm test
# OR
npm run test:comprehensiveThe comprehensive test validates with detailed latency metrics:
- β API Key Validation (valid/invalid/empty/missing keys) - Tracks latency per validation type
- β Credit Logic (accurate tracking and deduction) - Measures credit update performance
- β Rate Limiting (proper 429 responses when limits exceeded) - Times rate limit enforcement
- β Credit Exhaustion (proper 402 responses when credits depleted) - Tracks exhaustion detection speed
Sample Test Output:
β
PASS Key Validation: 4/4 | Latency (ms): avg 245, min 156, max 334
β
PASS Credit Logic: 3/3 | Latency (ms): avg 289, min 267, max 312
β
PASS Rate Limiting: 1/1 | Latency (ms): avg 198, min 167, max 245
β
PASS Credit Exhaustion: 1/1 | Latency (ms): avg 234, min 189, max 298
Test typically completes in ~6-8 seconds with 100% pass rate and detailed performance insights.
npm run dev # Start development server
npm test # Run comprehensive E2E tests with latency tracking
npm run deploy # Deploy to Cloudflare Workers
npm run format # Format code with Prettier-
Configure API mapping in
src/config/api-mappings.ts:"weather/forecast": { internalPath: "weather/forecast", targetUrl: "https://api.weather.com/v1/forecast", description: "Weather forecast API", creditCost: 5 }
-
Update plan access in
src/config/plans.ts:[PlanType.STANDARD]: { endpoints: [ "weather/*", // Allow weather APIs // ... other endpoints ], }
-
Add authentication in proxy route if needed
- Credit Sync Middleware: Optimized validation caching with always-fresh credit data
- Smart Cache Management: Threshold-based cleanup (no arbitrary timers)
- Rate Limiting: Sliding window with Upstash Redis
- Permission Checking: Role-based access control
- Analytics: Minimal overhead tracking for monitoring
Cache Layers:
βββ Validation Cache (5min TTL) β API key metadata
βββ Always Fresh Credits β Real-time credit tracking
βββ Smart Cleanup β Threshold-based cache management
βββ Memory Monitoring β ~15MB cache limit with 90% efficiency
Redis Keys:
βββ apikey:{keyId} β Full API key data
βββ lookup:{key} β keyId mapping
βββ tenant:{tenantId} β Tenant information
βββ credits:{tenantId} β Real-time credit tracking
βββ ratelimit:{keyId} β Rate limiting counters
Live API: https://api.groundng.site
The platform is deployed and running with:
- β‘ Ultra-fast response times with optimized middleware
- π§ Smart cache management - threshold-based cleanup
- π Secure API key management with crypto-safe generation
- π Real-time credit and rate limit tracking with synchronous updates
- π Global edge deployment via Cloudflare Workers
- πΎ Serverless Redis with Upstash for sub-10ms operations
- π Performance monitoring with built-in cache statistics
- Cryptographically secure API key generation
- Rate limiting with sliding window algorithm
- Credit exhaustion protection (402 Payment Required)
- Multi-tenant isolation with complete data segregation
- Input validation with Zod schemas
- Comprehensive error handling with detailed logging
- Secure Redis operations with atomic transactions
- Credit Validation: Cached for 5 minutes, always-fresh credit data
- Cache Efficiency: 90%+ hit rates with smart cleanup algorithms
- Memory Management: ~15MB cache limit with threshold-based cleanup
- Redis Operations: Batched operations and connection reuse
- Rate Limiting: Sub-10ms enforcement with sliding windows
- Global Deployment: Edge computing via Cloudflare Workers
- Threshold-Based Cleanup: No arbitrary timers, cleanup triggered by actual usage
- Memory Efficiency: Conservative 15MB limit for 128MB worker environment
- Smart Expiration: Expired entries cleaned first, oldest valid entries removed as needed
- Performance Monitoring: Real-time cache statistics at
/cache-stats
/health- System health and version information/cache-stats- Real-time cache performance metrics- Response headers include detailed performance data
{
"total": 1234,
"valid": 1100,
"expired": 134,
"expiredRatio": 11,
"memoryEstimateMB": "3.7MB",
"utilizationPercent": "25%",
"nextCleanup": {
"sizeTriggered": "43766 entries away",
"expiredTriggered": "20% expired threshold"
}
}ISC License
- Upstash - Serverless Redis infrastructure with global replication
- Cloudflare Workers - Global serverless platform with edge computing
- Hono - High-performance web framework optimized for edge environments