Skip to content

JohnPei1/GatekeeperAPI

Repository files navigation

🚦 Gatekeeper API

Python FastAPI License

A fair, highly scalable virtual queueing system with built-in IP-based rate limiting that protects backends during high-traffic events. Instead of overwhelming your servers, Gatekeeper places users in a cryptographically secure queue and controls access to your protected resources.


🏗️ Architecture

┌─────────────────────────────────────────────────────────────┐
│                     GATEKEEPER API                          │
│  (FastAPI + Redis + PostgreSQL + Background Workers)       │
│                                                             │
│  Endpoints: /queue/enqueue, /queue/status,                 │
│             /queue/verify, /queue/finish, /config          │
└─────────────────────────────────────────────────────────────┘
                    ▲                           ▲
                    │                           │
        ┌───────────┘                           └───────────┐
        │                                                   │
        │ Frontend Calls                     Backend Calls  │
        │ /enqueue, /status                  /verify, /finish
        │                                                   │
┌───────┴────────┐                                  ┌───────┴────────┐
│   Browser      │                                  │    Business    │
│                │                                  │    Backend     │
│ client_side.js │  1. enqueue(userId)              │                │
│ (Frontend)     │  2. waitUntilReady()             │ server_side.py │
│                │  3. Redirect to /checkout?jwt=.. │ (Backend)      │
│                │     ────────────────────────────>│                │
└────────────────┘                                  │ 4. verify(jwt) │
                                                    │ 5. Process     │
                                                    │ 6. finish(jwt) │
                                                    └────────────────┘

🚀 Quick Start

Prerequisites

  • Docker & Docker Compose
  • Python 3.11+ (for local development)

1. Clone & Configure

git clone https://github.com/yourusername/GatekeeperAPI.git
cd GatekeeperAPI

# Create environment file
cp .env.example .env

Edit .env and set:

JWT_SECRET=your_super_secret_random_string_here
BUSINESS_IDS=your_api_key_1:your_api_key_2
DATABASE_URL=postgresql+asyncpg://user:password@db:5432/gatekeeperdb
REDIS_URL=redis://redis:6379

🛠️ Production Setup

1. Start with Docker Compose

docker-compose up -d

This starts:

  • API Server on http://localhost:8000
  • Background Workers for queue processing
  • PostgreSQL database
  • Redis cache

2. Verify Health

curl http://localhost:8000/health
# Expected: {"status": "healthy"}

3. Configure Your Business

curl -X POST http://localhost:8000/config \
  -H "business_id: your_api_key_1" \
  -H "Content-Type: application/json" \
  -d '{
    "admission_limit": 10,
    "admission_frequency": 5,
    "jwt_expiry_seconds": 120,
    "ready_ttl_seconds": 300,
    "ip_enqueue_limit": 100,
    "ip_enqueue_limit_interval": 60,
    "ip_status_polling_limit": 60,
    "ip_status_polling_limit_interval": 60
  }'

Configuration Explained:

  • admission_limit: 10 → Allow 10 users per interval
  • admission_frequency: 5 → Process queue every 5 seconds
  • jwt_expiry_seconds: 120 → Tokens expire after 2 minutes (min: 60, max: 600)
  • ready_ttl_seconds: 300 → Ready state lasts 5 minutes (min: 60, max: 3600)
  • ip_enqueue_limit: 100 → Max 100 enqueue requests per window (rate limit per IP)
  • ip_enqueue_limit_interval: 60 → Enqueue rate limit window in seconds
  • ip_status_polling_limit: 60 → Max 60 status polls per window (rate limit per IP)
  • ip_status_polling_limit_interval: 60 → Status polling rate limit window in seconds

🛠️ Development Setup

For local development with api server hot-reload, real time code sync into the container (volume mount) and debugging:

1. Use Development Docker Compose

# Start development environment
docker-compose -f docker-compose.dev.yml up -d

# Stop development environment
docker-compose -f docker-compose.dev.yml down

2. Local Development (Without Docker)

# Create virtual environment
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt
pip install -r dev_requirements.txt

# Set up local environment
cp .env.example .env
# Edit .env with local settings (Redis/PostgreSQL running locally)

# Run API with hot-reload
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

# In another terminal, run workers
python -m app.worker.run_workers

# Run tests
pytest app/tests/ -v

Development Features:

  • 🔄 Hot-reload on code changes
  • 🐛 Debug mode enabled
  • 📊 Detailed error traces
  • 🧪 Access to test suite

📚 API Documentation

Authentication

All endpoints (except /health, /docs) require:

  • business_id header: Your API key

Token-based endpoints also require:

  • jwt header: User's queue token

Endpoints

1. Enqueue User

Add a user to the waiting queue.

POST /queue/enqueue
Headers:
  business_id: your_api_key
  user_id: user123

Response:
{
  "jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",  // Empty string if already queued/ready
  "position": 42,
  "message": "User enqueued successfully."
}

Note: If user is already in queue or ready state, JWT will be an empty string.

2. Check Queue Status

Poll queue position and ready state. Auto-refreshes JWT if expired.

GET /queue/status
Headers:
  business_id: your_api_key
  jwt: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Response:
{
  "warning_msg": null,  // Warning if user not found
  "jwt_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",  // Regenerated if expired
  "position": 35,  // null if ready or not found
  "ready": false
}

Note: Always use the returned jwt_token for subsequent requests.

3. Verify Ready State

Simple boolean check for backend validation.

GET /queue/verify
Headers:
  business_id: your_api_key
  jwt: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Response:
{
  "message": "User is ready",
  "ready": true
}

4. Finish & Clear

Remove user from ready state after serving.

DELETE /queue/finish
Headers:
  business_id: your_api_key
  jwt: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Response:
{
  "status": "ready_cleared",  // or "not_ready"
  "message": "User removed from ready state"
}

5. Get Configuration

Retrieve current business configuration.

GET /config
Headers:
  business_id: your_api_key

Response:
{
  "message": "Configuration retrieved successfully",
  "updated_config": {
    "ip_enqueue_limit": 1,
    "ip_enqueue_limit_interval": 1,
    "ip_status_polling_limit": 1,
    "ip_status_polling_limit_interval": 1,
    "admission_limit": 1000,
    "admission_frequency": 5,
    "jwt_expiry_seconds": 300,
    "ready_ttl_seconds": 600
  }
}

6. Update Configuration

Update business-specific settings.

POST /config
Headers:
  business_id: your_api_key
  Content-Type: application/json

Body:
{
  "admission_limit": 20,
  "admission_frequency": 10
}

Response:
{
  "message": "Configuration updated successfully",
  "updated_config": { ... }
}

7. Health Check

No authentication required.

GET /health

Response:
{
  "status": "healthy"
}

8. API Documentation

Interactive API documentation (Swagger UI). No authentication required.

GET /docs

Browser: Opens interactive API documentation with "Try it out" functionality

Alternative: Visit /redoc for ReDoc-style documentation.

About

A fair, highly scalable and cryptographically secured virtual queueing system with built-in IP-based rate limiting that protects backends during high-traffic events. Built with FastAPI, Redis, and PostgreSQL.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors