Skip to content

Architecture

This page describes how Kirak is structured internally. It is intended for contributors and developers who want to understand how the runtime works under the hood. If you are building an application, start with Getting Started.


Kirak is a model-driven runtime for FastAPI. At startup, it reads your model JSON definitions and uses them to drive every architectural decision:

  • Which database tables to create and migrate.
  • Which CRUD and GraphQL endpoints to mount.
  • Which roles are authorized for which operations.
  • Which fields are searchable, sortable, or hidden.

You declare your data structure and access policy in one place; Kirak executes the runtime, enforcement, and database orchestration.


Every incoming HTTP request traverses a standardized middleware chain and internal dispatch() pipeline:

flowchart TD
Req["Incoming HTTP Request"] --> Sec["SecurityHeadersMiddleware<br/>(X-Content-Type, X-Frame, X-XSS, Referrer)"]
Sec --> Origin["OriginValidationMiddleware<br/>(DNS Rebinding protection & CORS check)"]
Origin --> Ctx["RequestContextMiddleware<br/>(Injects UUID request_id & user_id into context)"]
Ctx --> Mon["MonitoringMiddleware<br/>(RED metrics: Timing, rates, error capture)"]
Mon --> Body["BodySizeLimitMiddleware<br/>(Enforces max_body_mb / HTTP 413 check)"]
Body --> Router["FastAPI Router<br/>(Matches model, operation, and path)"]
Router --> Dispatch["dispatch() Pipeline"]
subgraph Pipeline["Internal dispatch() Pipeline"]
D1["1. Resolve User Principal from JWT"] --> D2["2. Coerce Filter & Control Parameter Types"]
D2 --> D3["3. Validate Request Parameters against Spec"]
D3 --> D4["4. Execute before_* Hooks (Serial)"]
D4 --> D5["5. AccessPolicyEngine (RBAC + Row-Level Security)"]
D5 --> D6["6. Validate Fields & Construct Parameterized SQL"]
D6 --> D7["7. Execute DB Query & Serialize Output"]
D7 --> D8["8. Execute after_* Hooks (Serial)"]
end
Dispatch --> Pipeline
Pipeline --> Resp["JSONResponse (Uniform Response Envelope)"]

Security Separation: Hooks and access control checks run at distinct phases. The AccessPolicyEngine executes inside the operation after before_* hooks run. If access is denied, the request returns 403 PERMISSION_DENIED immediately and no SQL is ever executed.


A single Kirak facade coordinates the entire framework:

  • Loads and parses kirak.json and models/*.json.
  • Manages the async database connection pool (via asyncpg, asyncmy, or SQLite).
  • Mounts FastAPI routers and middleware.
  • Coordinates lazy-loaded modules.

Application code can access this instance via request.app.state.kirak or kirak = app.get_kirak().

Every model definition separates two concerns:

  • "schema": Data types, constraints, default values, and search indexing.
  • "access": Security policies, authorized roles, and row-level ownership rules.

Four fields are managed automatically by the runtime and must never be defined in schema:

  • id: Auto-increment integer or UUID primary key.
  • created_at: Set automatically on INSERT.
  • updated_at: Updated automatically on INSERT and every UPDATE.
  • deleted_at: Managed on soft-delete; cleared on restore.

Kirak auto-generates 11 operations per model:

Operation Method Path Description
fetch GET /{model}/fetch Paginated querying with filters and sorting
search GET /{model}/search Full-text search across searchable: true fields
count GET /{model}/count Count records matching filters
exists GET /{model}/exists Fast boolean existence check
create POST /{model}/create Insert single record (or bulk batch)
update PUT /{model}/update Update records matching filter
upsert PUT /{model}/upsert Insert or update on conflict
delete DELETE /{model}/delete Soft delete (sets deleted_at)
destroy DELETE /{model}/destroy Hard delete (permanent removal)
restore PATCH /{model}/restore Un-delete soft-deleted record
graphql POST /graphql Auto-generated GraphQL query interface

All Kirak capabilities—Auth, CRUD, Notifications, Payments, Storage, Scheduler, AI, Vector, and MCP—inherit from BaseModule.

flowchart TD
BaseModule["BaseModule (Core Foundation)<br/>- Hook Registry & dispatch() pipeline<br/>- Request-correlated logging<br/>- Data access facade & GraphQL"]
BaseModule --> CoreAuth["Core Auth<br/>(Always Loaded)"]
BaseModule --> CrudEngine["CRUD Engine<br/>(Always Loaded)"]
BaseModule --> OptModules["Optional Modules (Lazy-Loaded)<br/>Notifications, Payments, Storage, AI, Vector, Scheduler, Monitoring, MCP"]
  • Core Modules: Auth and CrudEngine are loaded unconditionally.
  • Optional Modules: Lazy-loaded upon first use using double-checked locking, keeping startup fast and memory footprint low when modules are not actively called.

When using create_kirak_app(), the runtime follows an orchestrated startup and shutdown lifecycle:

flowchart TD
subgraph Startup["Application Startup"]
S1["1. on_startup(app)<br/>(External services: Redis, etc.)"] --> S2["2. Kirak(app, models_path)<br/>(Load & validate kirak.json + models/*.json)"]
S2 --> S3["3. kirak.connect()<br/>(Open DB pool, init Auth & CrudEngine)"]
S3 --> S4["4. on_kirak_ready(kirak)<br/>(Register hooks & custom application logic)"]
S4 --> S5["5. kirak.mount_routers()<br/>(Mount all FastAPI routes & OpenAPI docs)"]
S5 --> S6["6. Start Background Workers<br/>(Account purge, scheduler queue, monitoring)"]
end
Startup --> Running["APPLICATION RUNNING (Serving Requests)"]
subgraph Shutdown["Application Shutdown"]
T1["7. Stop Workers<br/>(Drain scheduler queue, flush monitoring buffer)"] --> T2["8. Close Redis Connection"]
T2 --> T3["9. kirak.disconnect()<br/>(Close database pool cleanly)"]
T3 --> T4["10. on_shutdown(app)<br/>(Clean up external client connections)"]
end
Running --> Shutdown

Cloudflare Workers Notice: On Cloudflare Workers / Pyodide, steps 2, 4, and 5 run during import time before the database connects so they can be captured in the Worker’s deployment snapshot. on_kirak_ready must be a plain synchronous def that performs no I/O.


All framework exceptions inherit from KirakException and map to standard HTTP status codes:

classDiagram
class KirakException {
+int status_code = 500
+str message
}
class ValidationError {
+int status_code = 400
}
class AuthenticationError {
+int status_code = 401
}
class PermissionDenied {
+int status_code = 403
}
class NotFoundError {
+int status_code = 404
}
class DatabaseError {
+int status_code = 500
}
class ConfigurationError {
+int status_code = 500
}
KirakException <|-- ValidationError
KirakException <|-- AuthenticationError
KirakException <|-- PermissionDenied
KirakException <|-- NotFoundError
KirakException <|-- DatabaseError
KirakException <|-- ConfigurationError

All exceptions are importable from the top level:

from kirak import ValidationError, PermissionDenied, NotFoundError

Concern Component / Library
Web Runtime FastAPI, Starlette
Validation Pydantic v2, JSON Schema
PostgreSQL Driver asyncpg (Async binary protocol)
MySQL Driver asyncmy (Async binary protocol)
SQLite Driver Python built-in sqlite3 + aiosqlite
Authentication PyJWT, bcrypt, cryptography (Fernet)
Social OAuth social-auth-core
TOTP / MFA pyotp
GraphQL graphql-core v3
AI Integration pydantic-ai