# unkeyed/unkey architecture

> Architecture diagram of the GitHub repository unkeyed/unkey, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-04-05). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/unkeyed/unkey
- Repository: https://github.com/unkeyed/unkey

## Overview

##### Overall Architecture and Major Components
- Client/Frontend Layer – This includes the website, dashboards, documentation, and engineering portals. For example:
– apps/www: The public marketing website with components for landing pages, blogs, policies, and pricing.
– apps/dashboard: The web-based dashboard and admin interface where users manage keys, view analytics, configure settings, and monitor status.
– apps/docs: The documentation site with API references, guides, tutorials, and quickstart information.
– apps/engineering: An internal portal that provides in-depth architecture, design guidelines, internal documentation, and RFCs.
– apps/play: A playground or demo service used for experimenting with Unkey features.

- API and Core Services – These handle authentication, key management, rate limiting, and authorization:
– apps/api: The primary API service written mostly in TypeScript. It defines routes for creating, verifying, updating, and removing keys and handles API requests (including ratelimit and usage tracking).
– go/apps/api (and related directories in go/): The Golang implementation that provides many of the low‐level API endpoints, healthchecks, and OpenAPI documentation. It also integrates features like liveness checks, rate limiting endpoints, and service registration.
– apps/agent: A backend “agent” service written in Go and other languages that manages internal functions such as event routing, rate limiter replication, and connectivity (via protocols like gossip). It also holds business logic such as ratelimiting, encryption and key rotation.
– packages/ratelimit and packages/rbac: Shared libraries that encapsulate the business logic for managing rate limits and RBAC (roles and permissions) respectively. They are used across multiple services.

- Billing, Workflows and Data Services:
– apps/billing: Handles billing, subscription management, quota tracking and related data operations. It integrates with external payment processors and implements usage‐based billing.
– apps/workflows: Implements scheduled jobs and background maintenance tasks, such as refilling keys and invoicing. This service orchestrates tasks that are vital for data consistency and billing operations.
– apps/chproxy: Acts as a proxy for ClickHouse, which is the analytical database used for storing metrics, logs, and usage data.
– apps/logdrain: This service aggregates and drains logs from the system, helping in analytics and monitoring the key verification and API usage events.

- Internal and Shared Libraries:
– The “go” directory and its subdirectories (go/internal, go/pkg, etc.) contain multiple services and utilities handling lower-level tasks like caching, database interaction (SQL files in go/pkg/db), distributed membership (via “cluster” logic), and connection management.
– The “packages” directory (with subpackages such as api, cache, error, hono, nextjs, rbac) represents reusable modules that encapsulate core functionality. They are meant to be shared across services – for example, standardized error handling, caching, and tracing.
– The “internal” directory holds migration tools, billing migrators, authentication migrators, and wrappers for third-party services (like ClickHouse setup, AWS interactions, encryption utilities, etc.), ensuring smooth operations and system-wide consistency.
– The “tools” directory contains load testing (Artillery, k6), migration scripts, and local development utilities to simulate and manage the system.

##### Brief Service Descriptions (What Each Service Does)
- apps/agent: Operates as an internal agent managing event routing, ratelimiting, and key encryption duties. It uses protocols like gossip for state synchronization between nodes.
- apps/api: The main API gateway that processes incoming key-related actions (create, verify, update), handles authorization, rate limiting, and integrates with the agent for distributed operations.
- apps/billing: Manages subscription, quota, and billing-related calculations to ensure that usage is tracked and paid for accurately.
- apps/chproxy: Provides a proxy layer to the ClickHouse database making it easier to route analytical queries efficiently.
- apps/dashboard: Serves a web portal for users and administrators to manage API keys, view analytics, trace error logs, and configure system settings.
- apps/docs: Offers public-facing API documentation and developer guides outlining how to integrate and use Unkey’s authentication and authorization services.
- apps/logdrain: Consolidates logs from different parts of the system (API requests, agent events) to support monitoring, troubleshooting, and onward analytics.
- apps/play: A prototype or sandbox environment where developers can experiment with Unkey’s features without affecting production.
- apps/workflows: Schedules and orchestrates periodic background jobs related to maintenance tasks (for example, key refills, invoicing, and migrations).
- The “go” and “internal” directories: Implement many of the low-level services including API route handling, membership clustering, database interactions, and core business logic such as encryption, rate limiting, and logging.
- Packages (such as ratelimit, rbac, cache, error, hono) : Provide shared libraries and modules to standardize and centralize common functionality across the system.

##### Next Steps
- Frontend applications (apps/www, apps/dashboard, apps/docs) send requests to the API services (apps/api and the equivalent Go services).
- The API service communicates with the agent (apps/agent) to enforce rate limits and verifies keys.
- Both API and agent services interact with the ClickHouse proxy (apps/chproxy) for analytics and with shared libraries to ensure consistency in key validation and error handling.
- Billing and workflows services exchange data with the API layer to manage billing and task scheduling.

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% Client/Frontend Layer
    subgraph "Client/Frontend Layer"
        WWW["Website (apps/www): Public landing pages, blogs, policies, pricing."]:::frontend
        DASH["Dashboard (apps/dashboard): Admin interface for managing keys, analytics, and settings."]:::frontend
        DOCS["Documentation (apps/docs): API references, guides, and tutorials for developers."]:::frontend
        ENG["Engineering Portal (apps/engineering): Internal documentation, architectural designs, and RFCs."]:::frontend
        PLAY["Playground (apps/play): Demo environment for experimenting with Unkey features."]:::frontend
    end

    %% API and Core Services Layer
    subgraph "API and Core Services"
        API["Main API Service (apps/api): Processes API requests, key actions, and rate limiting (TypeScript)."]:::core
        GOAPI["Go API Endpoints (go/apps/api): Provides low‐level API endpoints, healthchecks, and OpenAPI documentation."]:::core
        AGENT["Agent Service (apps/agent): Manages event routing, key encryption, rate limiter replication, and state synchronization."]:::core
    end

    %% Support Services Layer
    subgraph "Support Services"
        BILLING["Billing Service (apps/billing): Handles subscriptions, quota tracking, and usage‐based billing."]:::support
        WORKFLOWS["Workflows Service (apps/workflows): Orchestrates scheduled jobs and background tasks such as key refills and invoicing."]:::support
        CHPROXY["ClickHouse Proxy (apps/chproxy): Acts as a proxy for analytical queries to the ClickHouse database."]:::support
        LOGDRAIN["LogDrain Service (apps/logdrain): Aggregates logs for monitoring API usage and key verification events."]:::support
    end

    %% Shared Libraries & Internal Utilities Layer
    subgraph "Shared Libraries & Internal Utilities"
        RTLIB["Rate Limiting Library (packages/ratelimit): Encapsulates rate limiting logic used by various services."]:::library
        RBACLIB["RBAC Library (packages/rbac): Implements roles, permissions, and access control logic."]:::library
        OTHERLIB["Other Shared Libraries (packages/*): Provides caching, error handling, and additional utilities."]:::library
        GO_INTERNAL["Go Internal Services (go internal/pkg): Handles low‐level tasks such as clustering, database interactions, and encryption."]:::library
        INTERNAL["Internal Services (internal/*): Contains migration tools, third‐party wrappers, and AWS/database setup utilities."]:::library
    end

    %% Development & Testing Tools Layer
    subgraph "Development & Testing Tools"
        TOOLS["Development Tools (tools): Includes load testing scripts, migration tools, and local development utilities."]:::tool
    end

    %% Data flows and interactions
    WWW -->|"REST/APICalls"| API
    DOCS -->|"Access & Integration"| API
    DASH -->|"AdminOperations"| API
    ENG -->|"InternalAccess"| API
    PLAY -->|"DemoRequests"| API

    API -->|"DelegatesRequests"| GOAPI
    API -->|"EnforcesSecurity"| AGENT

    API -->|"SendsAnalytics"| CHPROXY
    AGENT -->|"UpdatesState"| CHPROXY

    BILLING -->|"BillingInfo"| API
    WORKFLOWS -->|"TriggersJobs"| API

    API -->|"UtilizesLibs"| RTLIB
    API -->|"UtilizesLibs"| RBACLIB
    AGENT -->|"UtilizesLibs"| RTLIB
    AGENT -->|"UtilizesLibs"| RBACLIB

    API -->|"DatabaseInteraction"| GO_INTERNAL
    AGENT -->|"DatabaseInteraction"| GO_INTERNAL
    BILLING -->|"UsesMigrators"| INTERNAL

    API -->|"StreamsLogs"| LOGDRAIN
    AGENT -->|"StreamsLogs"| LOGDRAIN

    TOOLS -->|"SimulatesEnvironment"| API

    %% Click Events for Component Mapping
    click WWW "https://github.com/unkeyed/unkey/tree/main/apps/www"
    click DASH "https://github.com/unkeyed/unkey/tree/main/apps/dashboard"
    click DOCS "https://github.com/unkeyed/unkey/tree/main/apps/docs"
    click ENG "https://github.com/unkeyed/unkey/tree/main/apps/engineering"
    click PLAY "https://github.com/unkeyed/unkey/tree/main/apps/play"
    click API "https://github.com/unkeyed/unkey/tree/main/apps/api"
    click GOAPI "https://github.com/unkeyed/unkey/tree/main/go/apps/api"
    click AGENT "https://github.com/unkeyed/unkey/tree/main/apps/agent"
    click BILLING "https://github.com/unkeyed/unkey/tree/main/apps/billing"
    click WORKFLOWS "https://github.com/unkeyed/unkey/tree/main/apps/workflows"
    click CHPROXY "https://github.com/unkeyed/unkey/tree/main/apps/chproxy"
    click LOGDRAIN "https://github.com/unkeyed/unkey/tree/main/apps/logdrain"
    click RTLIB "https://github.com/unkeyed/unkey/tree/main/packages/ratelimit"
    click RBACLIB "https://github.com/unkeyed/unkey/tree/main/packages/rbac"
    click OTHERLIB "https://github.com/unkeyed/unkey/tree/main/packages"
    click GO_INTERNAL "https://github.com/unkeyed/unkey/tree/main/go"
    click INTERNAL "https://github.com/unkeyed/unkey/tree/main/internal"
    click TOOLS "https://github.com/unkeyed/unkey/tree/main/tools"

    %% Styles
    classDef frontend fill:#AED6F1,stroke:#1F618D,stroke-width:2px;
    classDef core fill:#FAD7A0,stroke:#D68910,stroke-width:2px;
    classDef support fill:#A9DFBF,stroke:#239B56,stroke-width:2px;
    classDef library fill:#F5B7B1,stroke:#C0392B,stroke-width:2px;
    classDef tool fill:#E8DAEF,stroke:#8E44AD,stroke-width:2px;
```
