Skip to Content
Getting StartedArchitecture Overview

Architecture Overview

BinoAuth is designed as a modern, scalable authentication platform with a microservices architecture that supports multi-tenancy and high availability.

System Architecture

High-Level Architecture

┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ Frontend Apps │ │ Admin Dashboard│ │ Documentation │ │ (React/Next) │ │ (Next.js) │ │ (Nextra) │ └─────────┬───────┘ └─────────┬───────┘ └─────────────────┘ │ │ └──────────────────────┼──────────────────────┐ │ │ ┌────────────▼────────────┐ │ │ API Gateway │ │ │ (Load Balancer) │ │ └────────────┬────────────┘ │ │ │ ┌────────────▼────────────┐ │ │ BinoAuth API │ │ │ (FastAPI Python) │ │ └────────────┬────────────┘ │ │ │ ┌────────────▼────────────┐ │ │ Database Layer │ │ │ PostgreSQL + Redis │ │ └─────────────────────────┘ │ ┌─────────────────────────────────────┘ ┌─────────────────────────────────────────────┐ │ SDK Ecosystem │ │ ┌──────────────┐ ┌──────────────┐ │ │ │ React SDK │ │ Next.js SDK │ │ │ └──────────────┘ └──────────────┘ │ │ ┌──────────────┐ ┌──────────────┐ │ │ │ Node.js SDK │ │ Core SDK │ │ │ └──────────────┘ └──────────────┘ │ └─────────────────────────────────────────────┘

Core Components

1. API Server (FastAPI)

The heart of BinoAuth, built with modern Python technologies:

Technology Stack:

  • FastAPI: Modern, fast web framework
  • SQLAlchemy 2.0: Async ORM for database operations
  • Alembic: Database migrations
  • Pydantic: Data validation and serialization
  • Uvicorn: ASGI server

Key Features:

  • Async/await: Non-blocking I/O for high performance
  • Type hints: Full type safety throughout
  • Auto-generated OpenAPI: Automatic API documentation
  • Request validation: Automatic request/response validation

Directory Structure:

api/ ├── src/ │ ├── api/ # API route handlers │ ├── models/ # SQLAlchemy models │ ├── schemas/ # Pydantic schemas │ ├── services/ # Business logic │ ├── core/ # Configuration, security │ └── middleware/ # Request/response middleware ├── migrations/ # Database migrations └── tests/ # Test suite

2. Database Layer

PostgreSQL with Redis for optimal performance:

PostgreSQL Schema Design

Public Schema (Shared Resources):

  • tenants - Tenant information
  • api_keys - API keys for programmatic access
  • admin_users - Admin dashboard users

Tenant Schemas (Isolated per Tenant):

  • users - End users
  • applications - OAuth clients
  • tokens - Access/refresh tokens
  • sessions - User sessions
  • external_accounts - Third-party integrations

Redis Usage

  • Session Storage: User sessions and temporary data
  • Rate Limiting: Request throttling counters
  • Caching: Frequently accessed data
  • Token Blacklisting: Revoked token tracking

3. Frontend Applications

Admin Dashboard (apps/admin/)

Management interface for tenants and applications:

Technology:

  • Next.js 15: React framework with App Router
  • React 19: Latest React with concurrent features
  • NextAuth.js: Authentication for admins
  • Tailwind CSS: Utility-first styling
  • TypeScript: Type safety

Features:

  • Tenant management
  • Application/client management
  • User management
  • API key management
  • Analytics and monitoring

Auth Frontend (apps/frontend/)

User-facing authentication flows:

Technology:

  • Next.js 15: Full-stack React framework
  • React 19: Modern React features
  • Tailwind CSS: Responsive design
  • TypeScript: Type safety

Features:

  • Login/signup forms
  • Email/phone verification
  • Magic link authentication
  • Device code flow
  • External provider integration

4. SDK Ecosystem

Comprehensive TypeScript SDKs for different integration scenarios:

Core SDK Architecture

┌─────────────────────────────────────────────────┐ │ Framework SDKs │ │ ┌──────────────┐ ┌──────────────┐ │ │ │ React SDK │ │ Next.js SDK │ │ │ └──────┬───────┘ └──────┬───────┘ │ │ │ │ │ │ └─────────┬───────┘ │ │ │ │ │ ┌────────────────▼────────────────┐ │ │ │ OAuth Core SDK │ │ │ │ (Generic OAuth 2.0 Client) │ │ │ └────────────────┬────────────────┘ │ │ │ │ │ ┌────────────────▼────────────────┐ │ │ │ Generated SDKs │ │ │ │ (Admin SDK + Tenant SDK) │ │ │ └─────────────────────────────────┘ │ └─────────────────────────────────────────────────┘

Multi-Tenant Architecture

Tenant Isolation Strategy

BinoAuth uses schema-based multi-tenancy for complete data isolation:

-- Public schema (shared) CREATE SCHEMA public; -- Tenant-specific schemas CREATE SCHEMA tenant_123; CREATE SCHEMA tenant_456;

Tenant Resolution

Tenants are resolved through multiple methods:

  1. Subdomain: tenant1.auth.example.com
  2. Domain: auth.tenant1.com
  3. Header: X-Tenant-ID: tenant-123
  4. Path: /tenant/tenant-123/auth

Database Connection Management

# Dynamic schema switching async def get_tenant_db(tenant_id: str): engine = create_async_engine( DATABASE_URL, connect_args={"options": f"-csearch_path=tenant_{tenant_id}"} ) return engine

Security Architecture

Token Security

JWT Token Structure:

{ "header": { "typ": "JWT", "alg": "HS256", "kid": "key-id" }, "payload": { "sub": "user-123", "iss": "https://auth.example.com", "aud": "client-456", "exp": 1234567890, "iat": 1234567890, "scope": "openid profile email" }, "signature": "..." }

Token Validation Flow:

1. Client sends token in Authorization header 2. API extracts and validates token signature 3. Check token expiration and claims 4. Verify audience and issuer 5. Extract user context for request

Rate Limiting Architecture

Redis-based Rate Limiting:

# Rate limit key structure key = f"rate_limit:{endpoint}:{client_ip}:{user_id}" # Sliding window algorithm current_count = await redis.incr(key) if current_count == 1: await redis.expire(key, window_seconds) if current_count > max_requests: raise RateLimitExceeded()

Security Layers

  1. Transport Security: HTTPS/TLS everywhere
  2. Authentication: OAuth 2.0 + OpenID Connect
  3. Authorization: Scope-based access control
  4. Rate Limiting: Per-endpoint, per-user limits
  5. CSRF Protection: State parameter validation
  6. Input Validation: Pydantic schema validation

Scalability Architecture

Horizontal Scaling

API Server Scaling:

  • Stateless Design: No server-side state storage
  • Load Balancing: Multiple API instances
  • Auto-scaling: Based on CPU/memory/requests

Database Scaling:

  • Read Replicas: Distribute read operations
  • Connection Pooling: Efficient connection management
  • Query Optimization: Indexed queries and caching

Caching Strategy

Multi-level Caching:

┌─────────────────┐ │ CDN Cache │ Static assets, public data └─────────┬───────┘ ┌─────────▼───────┐ │ Application │ In-memory caching │ Cache │ └─────────┬───────┘ ┌─────────▼───────┐ │ Redis Cache │ Session data, rate limits └─────────┬───────┘ ┌─────────▼───────┐ │ Database │ Persistent storage └─────────────────┘

Deployment Architecture

Container Architecture

Docker Images:

  • API Server: Python FastAPI application
  • Frontend Apps: Next.js applications
  • Database: PostgreSQL with initialization scripts
  • Cache: Redis with persistence

Docker Compose Stack:

services: api: build: ./api ports: ["8000:8000"] depends_on: [db, redis] admin: build: ./apps/admin ports: ["3000:3000"] depends_on: [api] frontend: build: ./apps/frontend ports: ["3100:3100"] depends_on: [api] db: image: postgres:15 volumes: [postgres_data:/var/lib/postgresql/data] redis: image: redis:7-alpine volumes: [redis_data:/data]

Production Deployment

Kubernetes Deployment:

apiVersion: apps/v1 kind: Deployment metadata: name: binoauth-api spec: replicas: 3 selector: matchLabels: app: binoauth-api template: metadata: labels: app: binoauth-api spec: containers: - name: api image: binoauth/api:latest ports: - containerPort: 8000 env: - name: DATABASE_URL valueFrom: secretKeyRef: name: binoauth-secrets key: database-url

Monitoring and Observability

Metrics Architecture

Application Metrics:

  • Request Metrics: Response times, error rates
  • Business Metrics: User registrations, logins
  • System Metrics: CPU, memory, database connections

Monitoring Stack:

┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ Prometheus │ │ Grafana │ │ AlertManager │ │ (Metrics) │ │ (Dashboards) │ │ (Alerts) │ └─────────────────┘ └─────────────────┘ └─────────────────┘

Logging Architecture

Structured Logging:

{ "timestamp": "2024-01-01T12:00:00Z", "level": "INFO", "message": "User authenticated successfully", "tenant_id": "tenant-123", "user_id": "user-456", "client_id": "client-789", "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0...", "request_id": "req-abc123" }

API Design Principles

RESTful Design

Resource-based URLs:

# Public API (Admin) GET /api/v1/tenants POST /api/v1/tenants GET /api/v1/tenants/{tenant_id} PUT /api/v1/tenants/{tenant_id} DELETE /api/v1/tenants/{tenant_id} # Tenant API (End-users) GET /api/v1/users/me POST /api/v1/auth/login POST /api/v1/oauth/token

Error Handling

Consistent Error Responses:

{ "error": { "code": "INVALID_CREDENTIALS", "message": "Invalid email or password", "details": { "field": "password", "reason": "Password does not match" }, "timestamp": "2024-01-01T12:00:00Z", "request_id": "req-abc123" } }

Performance Considerations

Database Optimization

Indexing Strategy:

-- User lookup optimization CREATE INDEX idx_users_email ON users(email); CREATE INDEX idx_users_phone ON users(phone); -- Token validation optimization CREATE INDEX idx_tokens_access_token ON tokens(access_token); CREATE INDEX idx_tokens_refresh_token ON tokens(refresh_token); -- Session management optimization CREATE INDEX idx_sessions_user_id ON sessions(user_id); CREATE INDEX idx_sessions_expires_at ON sessions(expires_at);

Connection Pooling

SQLAlchemy Configuration:

engine = create_async_engine( DATABASE_URL, pool_size=20, # Connection pool size max_overflow=30, # Additional connections pool_pre_ping=True, # Validate connections pool_recycle=3600, # Recycle connections hourly )

Development Architecture

Monorepo Structure

Workspace Organization:

binoauth/ ├── api/ # FastAPI backend ├── apps/ # Frontend applications │ ├── admin/ # Admin dashboard │ ├── frontend/ # Auth frontend │ └── docs/ # Documentation ├── packages/ # SDK packages │ ├── core/ # Core utilities │ ├── oauth-core/ # OAuth client │ ├── react/ # React integration │ └── nextjs/ # Next.js integration ├── examples/ # Example applications └── tools/ # Development tools

Build System

Bun Workspaces:

{ "workspaces": [ "apps/*", "packages/*", "examples/*" ], "scripts": { "build": "bun run build:packages && bun run build:apps", "dev": "bun run dev:api & bun run dev:apps", "test": "bun test" } }

What’s Next?

Understanding BinoAuth’s architecture helps you:

  1. Plan Your Deployment - Choose the right deployment strategy
  2. Integrate SDKs - Use the appropriate SDK for your needs
  3. Customize Configuration - Optimize for your use case
  4. Scale Your Implementation - Prepare for growth

The architecture is designed to be flexible, scalable, and maintainable while providing excellent developer experience and security.

Last updated on