Swarog is an open, self-hostable backend platform written in Rust — the same category of system as Firebase or Supabase: accounts and sessions, configuration, an admin portal, audit, scheduling, API keys, notifications, email, social features, and player cloud saves (JSON documents), behind one public front door. A game backend is the first module set built on it: characters, inventory, matches, rating, leaderboards, and parties are modules compiled in alongside the platform ones.
It is built as a modular monolith with a proven split: the whole backend runs
as a single cmd/server process, and every domain module also compiles and boots
as its own cmd/<name>-svc process. Both topologies run the same domain code and
are exercised end to end by a live integration suite on every verification run.
The architecture applies the Open/Closed principle at the level of the system: the backend grows by addition — new modules, new contract traits, new event subscriptions — and no module imports another's implementation. Because every module already boots as a separate process, any module can run as its own process without a rewrite.
Firebase and Supabase are generic hosted services into which you deploy data
models, access rules, and functions, and clients call the APIs they expose
(Supabase generates its data API from the database schema). Swarog is composed at
compile time from Rust modules that own their database schemas and typed
operations, and each module runs either inside the shared process or as its
own. It is not a drop-in replacement for either. Its vocabulary also shows its
origin in games — identities resolve to a player_id, and the front door
includes a player QUIC plane.
It runs as native processes on one machine with one PostgreSQL database; no container orchestrator or cloud-provider service is required. The monolith also ships a Docker Compose setup. No capacity or cost figures have been measured yet.
- 18 domain modules plus a gateway — 12 general-purpose platform modules and 6 game modules — each a "fortress" that never imports another module's implementation and boots as its own service.
- Three extensibility seams: a module registry, a synchronous capability registry that swaps local implementations for QUIC-backed remote clients, and a durable event bus over Postgres.
- Durable cross-module events: at-least-once delivery with a stable event id; effects are exactly-once for handlers that write their effect through the delivery transaction, which also commits the subscription checkpoint.
- A single public front door (HTTP, a WebSocket push hub, and a QUIC player plane), with an internal mTLS QUIC edge between services.
- Architecture rules enforced by tooling where they can be checked: dependency checks, per-process boot checks, wire-contract snapshots, and a split-versus-monolith parity proof, with advisory public-API snapshots.
- Self-hosted on native processes. Development, verification, and supervision tooling run on Linux, macOS, and Windows without containers; Docker Compose is an additional way to run the monolith. The code is licensed under the EUPL-1.2.
Module registry (core/lifecycle). Every feature is a lifecycle::Module
registered in a cmd/* composition root. Dependencies are declared as a manifest
(requires()) rather than sorted topologically: a two-phase build runs every
provider's register before any module's init, so initialisation order does not
matter. A process whose module set lacks a required capability fails at startup.
Lifecycle phases are register → init → migrate → start → stop; register
and init perform no I/O, and stop runs in reverse registration order.
Service registry (registry::provide / require). Synchronous calls go
through capability traits. A consumer depends on the provider's contract crate,
never its implementation, and resolves dyn Trait under a registry key. In a
split deployment a remote::Stub provides a QUIC-backed client under the same
key; for synchronous calls, that registry swap is the only difference between
the two topologies.
Generated RPC operations are not retried unless the contract marks a method
#[retry_safe].
Event bus (ctx.bus()). Every cross-module event is durable. A producer
appends to a shared, XID-ordered Postgres log inside its own database transaction,
without knowing its consumers. Each consumer owns a versioned pull subscription
with an explicit start position. Ordering is per subscription; a failing event
backs off and pauses its one subscription and is never skipped automatically
(operators inspect and resume it with eventctl). The bus is fire-and-forget:
request/response goes through the service registry, and state projected from
events is eventually consistent. The durable plane is owned by the application
runtime (core/asyncevents), not by any module. Replica-local caches are
refreshed by a separate LISTEN/NOTIFY invalidation plane (core/invalidation).
Two minor seams complete the picture: contribution slots
(ctx.contribute / ctx.contributions), a multi-value registry for cross-cutting
collections such as admin pages, HTTP operations, and readiness checks; and
edge::EDGE_SLOT, where a module unconditionally contributes its internal-edge
handlers and the runtime applies them only when the process serves an internal
edge.
Every directory under modules/ is a fortress: it never imports another module's
implementation crate, and it compiles and boots as its own cmd/<name>-svc. The
only dependencies between fortresses are the contract crates under api/<name>/:
| Crate | Contents | May be imported by |
|---|---|---|
<name>api |
capability traits and operation metadata, transport-free | any module |
<name>events |
event payloads and bus::define descriptors |
any module |
<name>rpc |
generated transport glue | its own module, cmd/* roots, other api/*/rpc crates |
Foundations in core/ never depend on a module or a contract crate.
Modules are topology-blind. Domain code contains no optional transports, no
"if split" branches, and no topology environment switches. The cmd/* roots are
the only topology-aware code and differ only in their module list and in which
QUIC planes they serve.
All modules share one PostgreSQL database with full logical isolation: one schema per module and no cross-module foreign keys. A reference to another module's data is a plain id column, resolved through a capability call or kept in sync through durable events.
The 18 domain modules form two sets: 12 general-purpose platform modules and 6
game modules. Dependencies point one way. Several game modules use platform
contracts (accounts, config, scheduler, admin); no platform module depends on a
game module's crates in its production build, though some name game concepts as
data — for example, audit records the game events in its ledger, the
development API-key seed lists game operations, and the admin portal template
carries GameOps branding and game-specific icons and navigation. No build without
the game modules is defined or tested today.
- accounts — player identity: one player id, many provider identities; opaque
sessions with short-lived access tokens and rotating refresh-token families;
federated login (Epic, Google, guest), account linking, and self-service account
deletion. Deletion emits durable
player.deleted; seven modules purge the player's data on a five-minute sweep,partyremoves the player directly, andauditrecords it.leaderboard,rating,match, andmailcannot purge yet; the open gaps are in docs/todo/account-deletion.md. - config — database-backed settings with a monotonic revision, live reload
through the invalidation plane, and a durable
config.changedevent. - admin — the GameOps portal at
/admin: session authentication with CSRF protection and login lockout, rendering admin pages contributed by other modules, including remote pages fetched over QUIC. - audit — an append-only ledger fed by independent raw durable subscriptions, with scheduled retention.
- scheduler — data-driven interval schedules; a due schedule fires once across replicas under a per-schedule advisory lock, and missed intervals coalesce into a single fire.
- apikeys — per-key API access policy; the gateway requires an API key on every operation and enforces its role's policy.
- wallet — virtual currency: an operator-owned catalog, per-player balances, and an append-only ledger; credits and debits are internal-only and idempotent.
- notifications — a per-player inbox built from other modules' durable events, with operator messages and scheduled pruning.
- mail — outbound email through a durable outbox and a retrying worker, with a development log sink and an SMTP provider.
- friends — the social graph: friend requests by player handle, with symmetry and pair uniqueness enforced by the database schema.
- groups — social groups with roles and invitation/request membership states.
- storage — player cloud saves with owner-only writes, public or private reads, and compare-and-swap versioning.
- characters / inventory — the reference pair for new modules: plain-id relations, synchronous ownership checks over the wire, and starter grants and wipes driven by durable character events.
- match / rating / leaderboard — idempotent match reports, a persistent MMR
projection, and a persistent leaderboard, connected by the durable
match.finishedevent. - party — short-lived player parties with lease-based membership and real-time state pushed to members.
- gateway — the single public front door: HTTP operation routing (local or remote, decided by slot presence), a WebSocket push hub, the player QUIC plane, HTTP passthroughs, rate limiting, and native TLS termination. Domain services never host it; they serve operations only over the internal mTLS edge.
demos/webui is a development demo SPA for the accounts flow. It is not shipped
and is registered only in the monolith.
Feature-level status and planned work are tracked in docs/roadmap/feature-tracker.md; item-level gaps per topic are in docs/todo/.
- Extend by addition. New capability arrives as new code: a new module, new contract traits, new subscriptions in the consuming modules. No module imports another module's implementation.
- Every module is extractable. Any domain module runs as its own process today. A feature that works in only one topology is treated as a defect.
- One shared Postgres. A single database server with schema-per-module isolation is a deliberate operational choice, not an interim step towards database-per-service.
- Durable, transactional events. Delivery is at-least-once. Effects are exactly-once for handlers that write their effect through the delivery transaction, which also commits the checkpoint; there is no inbox table. Effects outside the database, such as an SMTP send, are at-least-once.
- Additive contract evolution. A published event payload is never changed in place. A breaking change is a new contract version with new subscription ids.
- Fail closed. Development conveniences (dev authentication, seeded API keys, seeded currencies, simulated purchases) are off unless explicitly enabled, and a process missing a required capability refuses to start.
- Mechanical enforcement over convention. Dependency direction, the fortress
rule, per-process boot, capability requirements, and durable-topic consistency
are checked by blocking
verifyctlstages; public-API snapshots are advisory. The standalonetopiccheckstage is advisory but currently adds no check beyond the durability-strict topic run inside the blockingfortressstage. Extend-by-addition and the shared-Postgres model are conventions, not gates. See docs/reference/architecture-enforcement.md.
Prerequisites:
- The Rust toolchain pinned in
rust-toolchain.toml(stable, installed byrustupon first use). - A local PostgreSQL reachable at
DATABASE_URL, defaulting topostgres://gamebackend:gamebackend@localhost:5432/gamebackend?sslmode=disable.scripts/db-provision.sh(orscripts/db-provision.ps1) creates the role and database. Module schemas are created by the services at boot. Integration tests use this database directly; Docker is not a test dependency.
Run either topology under the development supervisor:
cargo run -p devctl -- up monolith
cargo run -p devctl -- up split
cargo run -p devctl -- status
cargo run -p devctl -- downdevctl up builds the selected topology, mints the development edge CA, seeds the
development admin account (admin / admin), enables the development
conveniences, starts each process with a typed environment, health-checks it, and
keeps ownership in the foreground until shutdown. While it runs, inspect or stop
the fleet with the already-built target/debug/devctl binary instead of starting
another Cargo command.
Smoke test against the monolith:
curl -X POST localhost:8080/match/report -H "X-Api-Key: dev-key-server" \
-d '{"ReportId":"demo-1","Winner":"alice","Loser":"bob"}'
curl localhost:8080/leaderboard -H "X-Api-Key: dev-key-client"compose.yaml runs the monolith and its PostgreSQL in containers (a distroless
image built from the Dockerfile). The split topology is not in compose yet.
Secure default: copy .env.example to .env, set SWAROG_DB_PASSWORD to a
password of URL-safe characters (it is embedded in DATABASE_URL), then:
docker compose upDo not write a KEY= line with an empty value in .env: the mail settings fail
startup when set but empty, and other keys read blank as unset. Nothing is seeded in this variant: no dev keys, no admin login,
and /readyz stays red until MAIL_PROVIDER and MAIL_FROM are configured (by
design). Create an admin login without echoing the password or putting it in argv:
read -rs ADMINCTL_PASSWORD; export ADMINCTL_PASSWORD
docker compose run --rm -T -e ADMINCTL_PASSWORD \
--entrypoint /usr/local/bin/adminctl server create-user <name>Git Bash on Windows (MSYS) rewrites POSIX-looking arguments, so that command
fails with exec: "C:/Program": stat C:/Program: no such file or directory.
Prefix it with MSYS_NO_PATHCONV=1. In PowerShell:
$user = Read-Host -Prompt "Admin username"
$secure = Read-Host -AsSecureString -Prompt "Admin password"
$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
try { $env:ADMINCTL_PASSWORD = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr) }
finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr) }
docker compose run --rm -T -e ADMINCTL_PASSWORD `
--entrypoint /usr/local/bin/adminctl server create-user $user
Remove-Item Env:ADMINCTL_PASSWORDSet SWAROG_DB_PASSWORD by editing .env: a SWAROG_DB_PASSWORD exported in
your shell ($env:SWAROG_DB_PASSWORD in PowerShell) overrides the .env value.
The HTTP port is published on 127.0.0.1:8080 only; change it with SWAROG_BIND
and SWAROG_HTTP_PORT. For TLS, either:
TLS_MODE=fileswithTLS_CERT_PATH=/tls/cert.pemandTLS_KEY_PATH=/tls/key.pem, the files placed in./tls(mounted read-only at/tls). On a Linux host the key must be readable by uid 65532 (for examplechown 65532or mode 644). Put theTLS_*values in.env(compose reads it itself) rather than exporting them in Git Bash, which would rewrite/tls/...into a Windows path.TLS_MODE=acmewithACME_DOMAINS, which needsSWAROG_BIND=0.0.0.0,SWAROG_HTTP_PORT=443and public DNS.- Or terminate TLS in a reverse proxy and set
TRUSTED_PROXY_CIDRSto its address range. The proxy does not carry QUIC: setPLAYER_TLS_CERT_PATHandPLAYER_TLS_KEY_PATH(both or neither; PEM files under/tls) to give the player port its own certificate.
The player QUIC port 9100/udp is published too. It presents the certificate of
the TLS front: the TLS_CERT_PATH pair under TLS_MODE=files, or the same ACME
certificate as HTTPS under TLS_MODE=acme (ACME_DOMAINS must include the host
players dial). PLAYER_TLS_CERT_PATH and PLAYER_TLS_KEY_PATH, when set, win
over both. With TLS_MODE=off and no PLAYER_TLS_* it serves a development
certificate and logs a warning; only clients that trust the dev CA accept it.
Development variant: the overlay seeds the admin / admin login, enables the
development conveniences and dev API keys, and sends mail to the log.
docker compose -f compose.yaml -f compose.dev.yaml upIt runs as the separate project swarog-dev with its own containers and data, so
it never shares a database with the secure variant. The smoke test above works
against it.
Per-platform details (Linux, macOS, Windows) are in docs/reference/platform-notes.md.
cargo run -p verifyctl -- --fast
cargo run -p verifyctl -- --all
cargo run -p verifyctl -- --all --strict
cargo run -p verifyctl -- --slowverifyctl runs a manifest of stages, prints a PASS/FAIL/SKIP table, and exits
non-zero on any applicable blocking failure.
- Blocking (
--fast, the default): build, clippy with warnings denied, tests, dependency audit,fortress,routecheck,codegen-freshness,contract-golden,conformance, control-plane manifest checks (admincheck),docs-current,supported-targets, threewelescontract and boot stages, andsplit-proof. - Advisory (
--all; blocking with--strict): public-API snapshots, fuzzing, the external C# client, and event-topic checks (topiccheck). - Slow (
--slow): everything above plus mutation testing.
An audit installation, invocation, or network failure is a FAIL, not a green
SKIP. A stage is skipped only for an explicit --no-install with a missing tool or
a declared platform non-applicability.
split-proof is the central promise of the repository. It boots every domain
service and the gateway as separate processes, drives real traffic through the
gateway (registration and login, authorisation negatives, cross-process event
flows, live config reload, scheduler exactly-once, API-key policy, the social and
storage modules, parties over the push socket, account-deletion purge) and
asserts database state directly. It then boots the monolith on the same player
front for parity checks and proves its graceful shutdown.
All rollout-bearing tools (devctl, verifyctl, weles) share one lease at
run/rollout.lock, so only one fleet or verification run can use the shared
Postgres at a time.
weles— a standalone supervisor for native processes with per-service restart-on-crash and capped backoff. It never builds; it runs binaries staged withweles deployagainst a strictfleet.toml. See weles/README.md and docs/reference/weles-design.md.eventctl(cargo run -p eventctl) — operator CLI for durable subscriptions: list, lag, retry, pause, resume, skip, and retire. See docs/reference/event-plane-ops.md.adminctl(cargo run -p adminctl) — creates admin portal users or resets their passwords, reading the password from stdin, never from argv; wrapped byinstall.sh/install.ps1.
cmd/ composition roots, the only topology-aware code
server/ monolith (all modules in one process)
gateway-svc/ public front door (remote stubs only, no database)
<name>-svc/ one process per domain module
core/ foundations; never import modules or api/ crates
api/<name>/ contract crates per domain (api / events / rpc)
modules/ domain module implementations (the fortresses)
demos/ development demo SPA (monolith only)
weles/ standalone process supervisor
tools/ devctl, verifyctl, processctl, splitproof, architecture checkers,
code generators, operator CLIs, test support
clients/ external C# client (generated bindings)
docs/ reference documentation, plans, reviews, roadmap
experiments/ archived earlier implementations (Go, JVM), reference only
The project began as a Go modular monolith, was explored on the JVM, and was
ported to Rust in July 2026. The earlier implementations remain under
experiments/ as reference and are not developed further.
Swarog is developed by one human maintainer directing AI coding agents. Most of the code, tests, and documentation are written by agents running in Claude Code. The maintainer owns the architecture, approves plans, and decides what lands. AI is used only to build the project: the backend itself contains no language-model integration and makes no calls to AI services at runtime.
The agents follow written instructions kept in the repository: CLAUDE.md and AGENTS.md, with shared rules in .agents/shared/. Work proceeds in a fixed sequence:
- Plan. Non-trivial changes start as a dated plan in
docs/plans/, written from research into the existing code and reviewed by an independent agent. The plan is an ordered list of steps, each tagged with the model that will execute it. - Implement. Each step is dispatched to a specialised agent defined in
.claude/agents/:
core-implementerfor correctness-critical and cross-seam work,mockup-implementerfor admin UI built against design mockups, and lower-cost models for mechanical changes. - Test. The implementer writes the tests with the code, required to exercise
the branch that was previously wrong, on the topology at risk; verify gates
and splitproof assertions are a separate step for
test-author. - Review. An adversarial review of each code change by
core-reviewer, in a separate context, that attacks the diff by failure class.proof-auditoris added when the change touches a verification gate. - Document.
docs-writercorrects prose against the landed code, deleting claims the code does not support.
The failure classes agents are reviewed against are recorded in
docs/reference/core-failure-taxonomy.md,
derived from the fix commits of the project's own remediation history. Agent
working memory is mirrored into memory/ so it is versioned with the code.
The central design decision is that agents are not trusted to follow the
architecture; where a rule can be checked, the verification run checks it.
Dependency direction, the fortress rule, per-process boot, wire contracts,
documentation references, and split-versus-monolith parity fail the blocking
--fast run; public API surface changes are reported by the advisory stage and
fail only under --strict. An agent's mistake in those areas surfaces as a failed
gate rather than depending on a reviewer to notice it.
Swarog is pre-production and has no deployed users. Consequences of that phase:
- There is no hosted CI and no push hook. By convention,
cargo run -p verifyctl -- --fastis run locally before every push. - Schema and event-contract breaks are handled by dropping the affected schemas and booting fresh. There is no data-migration machinery; development data comes from seed scripts.
- The external C# client stage cannot run on macOS, and fuzzing cannot run on
Windows; both are declared platform exceptions in
verifyctl.
Copyright © Łukasz Baran.
Licensed under the European Union Public Licence v. 1.2 (EUPL-1.2). See LICENSE.