net_backend
Rust crates · 0.2.0 · MIT OR Apache-2.0

Build your own game backend in Rust: server, protocol and client.

A family of Rust crates for game backends: a framework you build your own server with, the shared message types both sides speak, a small Rust client, and a generator that writes a server and a client project that run at once. The server speaks plain HTTP + WebSocket + JSON, so any client in any language can use it.

two commands · PowerShell, cmd, bash, zsh
cargo install net_backend
net-backend new mygame

0.2.0MIT OR Apache-2.0Rust 1.95+

01 Start in one line

Two commands. A running game backend.

net-backend new asks a few questions and writes a project that runs at once: the server with the modules you pick, a client for your kind of game, a demo app with buttons, and Docker files for your database. Try the answers below: the command and the preview follow.

bash
$ cargo install net_backend
  Installing net_backend v0.2.0
     …
   Installed package `net_backend v0.2.0` (executable `net-backend`)
$ net-backend new mygame



  Build your own game backend in Rust  v0.2.0

  ◆ Client  ──────────────────────────────────────────────────
  ↑↓ move · type to filter · enter confirm
✓ How will your game talk to the server? Rust client (server + protocol + net_backend_client)

  ◆ Database  ────────────────────────────────────────────────
  ↑↓ move · type to filter · enter confirm
✓ Database? SQLite (a file, nothing to install)

  ◆ Modules  ─────────────────────────────────────────────────
  ↑↓ move · space toggle · → all · ← none · enter confirm
✓ Server modules? accounts, saves, chat, leaderboards, notifications, friends, groups, lobbies, matchmaking, files (10)

  ◆ Demo  ────────────────────────────────────────────────────
  y / n · enter takes the default
✓ Add a demo app to try it (a small window with buttons and a log)? Yes

  ◆ Start  ───────────────────────────────────────────────────
  y / n · enter takes the default
   INFO  The first build of the demo takes about 1 to 2 minutes.
✓ Start the server (and the demo) when done? No

  ✓ Cargo.toml                               the workspace
  ✓ server/                                  the game server: SQLite, 10 modules
  ✓ client/                                  a client on net_backend_client
  ✓ demo/                                    the egui demo app
  ✓ config.toml, config.docker.toml          the server's settings
  ✓ Dockerfile, compose.yaml, .dockerignore  Docker deploy (SQLite)
  ✓ README.md, .gitignore                    how to run and deploy it

   DONE  Created mygame · net_backend 0.2.0
  Project   /home/you/mygame
  Client    Rust client
  Database  SQLite
  Modules   auth, storage, chat, leaderboards, notifications, friends, groups, lobbies, matchmaking, files
  Demo      egui window (demo/)

  The same setup without questions
  $ net-backend new mygame --client rust --db sqlite --modules auth,storage,chat,leaderboards,notifications,friends,groups,lobbies,matchmaking,files --demo

  Next steps
  › cd mygame
  › cargo run          # the server on http://127.0.0.1:8080
  › cargo run -p demo  # the demo, in a second terminal
    (the demo with Steam: cargo run -p demo --features steam; see README.md)

  README.md in the project describes the rest.

Click an underlined answer to change it.

net-backend new mygame --client rust --db sqlite --modules auth,storage,chat,leaderboards,notifications,friends,groups,lobbies,matchmaking,files --demo
mygame/
├── Cargo.toml                 # the workspace; `cargo run` = the server
├── README.md                  # how to run, deploy and extend it, and the one-line command
├── config.toml                # the server's development configuration
├── config.docker.toml         # the configuration inside the Docker image
├── Dockerfile                 # the server in a small non-root Linux image
├── compose.yaml               # the image on 127.0.0.1:8080
├── .gitignore, .dockerignore  # .gitignore also lists /files
├── server/
│   ├── Cargo.toml             # net_backend_server with the database's and the modules' features, tokio
│   └── src/main.rs            # 10 modules registered
├── client/
│   ├── Cargo.toml             # net_backend_client
│   └── src/main.rs
└── demo/
    ├── Cargo.toml             # egui
    └── src/main.rs, src/steam.rs, src/invite.rs

Every question is also a flag, and -y takes every default. Want to wire it yourself? Pick one of the four ways below.

02 What is your client?

One server. Four ways to talk to it.

The expert route: pick the crates yourself. Every path uses the same server, and the server does not care which client connects: the JSON on the wire is the contract.

Server + protocol + net_backend_client

for Rust apps, tools, bots and other engines

HTTP, WebSocket (feature ws), SSH / SFTP (ssh, sftp); async and blocking; the session handled (refresh before expiry, one 401 retry); a token file; files with progress; OpenID Connect sign-in; proxies; your own certificates or the system's store; HTTP/2.

the installer
net-backend new mygame --client rust
or add the crates yourself
cargo add net_backend_client --features ws
cargo add tokio --features rt-multi-thread,macros
cargo add serde_json
net_backend_client
use net_backend_client::protocol::auth::{GetAccount, LoginRequest};
use net_backend_client::protocol::storage::{GetObject, PutObject, WriteObject};
use net_backend_client::{Client, Error};

let client = Client::new("https://api.example.com")?;
client.login(LoginRequest::new("player@example.com", "a long password")).await?;

let me = client.call(&GetAccount::new()).await?;
client.call(&WriteObject::new("saves", "slot-1", PutObject::new(serde_json::json!({"level": 3})))).await?;
let save = client.call(&GetObject::new("saves", "slot-1")).await?;
println!("{:?} is on level {}", me.display_name, save.value["level"]);

every path → the same net_backend_server

The server side, for every path

cargo add
cargo add net_backend_server                                                  # PostgreSQL (the default)
cargo add net_backend_server --no-default-features --features sqlite          # or SQLite (MySQL / MariaDB: --features mysql)
cargo add net_backend_server --no-default-features --features sqlite,storage,chat   # or SQLite with storage + chat
cargo add tokio --features rt-multi-thread,macros
cargo add serde --features derive                                             # for your own request types
Installer--db sqlite (the default)
Server featurecargo add net_backend_server --no-default-features --features sqlite,storage,chat
In Cargo.tomlnet_backend_server = { version = "0.2.0", default-features = false, features = ["sqlite", "storage", "chat"] }
config.tomlurl = "sqlite:game.db"
Productionthe project's compose.yaml (one container on 127.0.0.1:8080), or systemd with --db sqlite behind Caddy

Choose PostgreSQL when the server and the database should run on different machines, when you run more than one server process, or when every committed write must survive a power loss.

Module features are added to the list the same way: storage, chat, leaderboards, notifications, friends, groups, oauth, lobbies, matchmaking, files; plus steam for Steam login and smtp for real mail.

03 How it fits together

Your rules on top. A shared protocol underneath.

net_backend_server is a library you build your own server binary with. The protocol crate holds the message types both sides speak; clients in other languages send the same JSON.

net_backend architecture Your client (Rust with net_backend_client, Bevy with bevy_net_backend, or any HTTP or WebSocket library) talks HTTP and WebSocket to your server built on net_backend_server: a core with auth, sessions, the WebSocket hub and permissions, and the modules storage, chat, leaderboards, notifications, friends, groups, oauth, lobbies, matchmaking and files, on SQLite, PostgreSQL or MySQL / MariaDB. Both sides share net_backend_protocol. your client your game / app / tool · Rust: net_backend_client · Bevy: bevy_net_backend · Other: any HTTP / WS library HTTP + WebSocket client your server (Rust binary) your rules / hooks / logic net_backend_server core: auth, sessions, WS hub, permissions modules: storage, chat, leaderboards, notifications, friends, groups, oauth, lobbies, matchmaking, files SQLite · PostgreSQL · MySQL / MariaDB HTTP / WS JSON answers + pushes net_backend_protocol shared message types · plain Rust + serde · no networking, no async runtime, no engine
Not Rust? Use the HTTP / WebSocket API directly: the API reference → Browser games on another domain work too, once the server lists their origin in cors.allowed_origins.

04 In the box

Eleven modules. Pick what your game needs.

Every module is a cargo feature, off by default, on MySQL, PostgreSQL and SQLite. Modules work together when both run: chat gives groups and lobbies a room each; notifications carry friend requests, group and room invitations; friends make friends-only lobbies, files and storage objects possible.

auth

Accounts

Email + password and Steam logins, tokens that refresh themselves, email verification, password reset, roles, an audit log.

/v1/auth/register, /login, /steam, /refresh, /logout; /v1/account; /v1/admin/…

more

argon2id passwords; opaque access tokens and rotating refresh tokens stored as hashes; sessions and revocation (open WebSockets close at once); bans; rate limits and a failed-login lockout; mail by log or SMTP; roles and /v1/admin routes; every admin action in the audit log.

storage

Storage

Saves as JSON objects with versions and conditional writes — and share an object with everyone or your friends.

/v1/storage/{collection}/{key}, /_batch/get, /_batch/put; /v1/users/{user}/storage/…

chat

Chat

Chat that feels like a chat app — edits, read receipts, typing, and rooms your players run.

chat.join, chat.send, chat.history, chat.edit, chat.mark_read, chat.unread, chat.set_typing; pushes chat.message, chat.edited, chat.read, chat.typing, chat.room; /v1/chat/rooms, /v1/chat/dm

more

Public, group and DM rooms; history pages; presence; moderation hooks and deletion; edits for 15 minutes (moderators: any message); "seen" in DMs, groups and player rooms; typing indicators, quiet in rooms with more than 50 players online; players create public or private rooms, name moderators, invite, kick.

leaderboards

Leaderboards

Best, latest or summed scores; all-time, daily or weekly boards; your rank and the ranks around you.

/v1/leaderboards, /{board}, /{board}/scores, /{board}/me, /{board}/around

more

Boards in config.toml (or code); score mode best / latest / sum; higher or lower is better (race times); all-time, daily or weekly (00:00 UTC, weeks on Monday); finished periods stay readable for 8 periods; unique ranks (ties: who got there first); a server hook checks, changes or refuses every score; a board can take scores from the server's own code only.

notifications

Notifications

Stored per player, pushed live, read / unread, kept for as long as you set.

notify.new (push), notify.list, notify.count, notify.mark, notify.delete; /v1/notifications

more

Only the server creates them (from a route, a hook or a module); 200 per player, kept 30 days (both settings); the same calls over HTTP and the WebSocket.

friends

Friends

Add by name or friend code, block, see who is online — and find which of your Steam friends already play.

/v1/friends, /requests, /blocks, /code, /presence, /steam, /settings; push friends.presence

more

Add by account id, display name or an 8-character friend code (any case, with or without a dash); accept, decline, cancel, remove, block; online = an open WebSocket or a heartbeat; requests and acceptances are notifications; limits 200 friends, 50 open requests, 500 blocks (settings).

groups

Groups

Guilds and clans with roles, invitations and their own chat room.

/v1/groups, /{group}/invites, /{group}/members, /{group}/transfer

more

Owner / admin / member; open or invite-only; invitations as notifications; a name search; a chat room per group with the chat module; limits 100 members, 10 groups per player (settings).

oauth

Sign in with Google

Sign in with Google — or any OpenID Connect provider; linked to your accounts.

POST /v1/auth/oauth/{provider}; DELETE /v1/account/identities/{provider}

more

The game sends the provider's ID token; the server checks the signature (RS256 / ES256 against the provider's published keys), issuer, audience, expiry and nonce, and each sign-in counts once; Google is a ready preset; the first login creates the account; a logged-in player links a provider (never merging two accounts) and unlinks it.

lobbies

Lobbies

Join codes, ready flags, metadata search; the server coordinates, your game connects.

/v1/lobbies, /search, /join (by code), /{lobby}/ready, /{lobby}/host; pushes lobby.member, lobby.changed

more

Public, private or friends-only; join by id or by the 8-character join code (any case, with or without a dash; also a number, for platforms that pass a number); ready flags; the host changes metadata, size, visibility and state (open / in game / closed), kicks, hands over, makes a new code; a search by metadata; a chat room per lobby; a player whose connection drops leaves after 30 s (setting).

matchmaking

Matchmaking

Queues with your own rules; the server tells the players when they matched.

/v1/matchmaking/queues, /ticket; pushes match.found, match.expired

more

Queues from the configuration; one ticket per player with attributes (a rating, a region); every second the server matches by the game's own rules (a hook; first come, first matched by default); tickets run out after their timeout; tickets live in the server's memory.

files

Files

Screenshots, replays, levels: upload, share with friends or everyone, download.

POST /v1/files, /v1/files/{file}/content, /v1/files/usage

more

Multipart uploads streamed (never held in memory) with a content type, a SHA-256 and metadata; private, public, friends, or shared with chosen players; 16 MiB per file, 100 files, 256 MiB per player (settings); slow connections are fine (an upload fails only when no data arrives for 30 s, or after an hour); the bytes in a folder on the server (Docker: a data volume) or in a store the game provides.

core

Permissions

Fine-grained rights on top of roles, set in one config table.

[permissions]; RequirePermission<P>; chat.moderate, lobbies.manage

05 Your server

A library, not a finished application.

Your game adds its own routes (plain axum handlers or typed HttpCall routes), hooks (before: pass on, change or reject; in_tx: inside a module's transaction; after), WebSocket handlers by kind, its own modules (routes + migrations + hooks), commands and permissions. Every binary gets the same command line:

serve (or no command)run the server until SIGTERM / Ctrl-C
migrate, migrate statusapply / list migrations
migrations publish <module>copy a module's SQL into the app, which then owns it
config check [--connect]validate the configuration (and try the database)
openapi export, asyncapi exportwrite the API documents
healthcheckexit 0 when the running server's /readyz answers 200
user:create, user:role, user:ban, user:unban, sessions:revokeaccounts from the command line

The server README · docs.rs

src/main.rs
use net_backend_server::axum::{routing::post, Json};
use net_backend_server::{ApiJson, AppError, Config, NetBackendServer};
use serde::Deserialize;

#[derive(Deserialize)]
struct Craft {
    item: String,
}

async fn craft(ApiJson(body): ApiJson<Craft>) -> Result<Json<String>, AppError> {
    if body.item.is_empty() {
        return Err(AppError::bad_request("item is empty"));
    }
    Ok(Json(format!("crafted {}", body.item)))
}

#[tokio::main]
async fn main() -> Result<(), net_backend_server::Error> {
    let config = Config::load()?;                    // NBS_CONFIG / config.toml + NBS__* variables
    NetBackendServer::new(config)
        .route("/v1/game/craft", post(craft))      // plain axum handlers
        .run()                                     // the command line; `serve` by default
        .await
}

06 Self-hosted

Your machine. Your data.

Try the server with one Docker command, run it in production with three, or install it as a systemd service. No Rust needed for Docker.

Docker · PowerShell, cmd, bash, zsh
docker run --rm -p 127.0.0.1:8080:8080 ghcr.io/warmar94/net_backend_server:0.2

Then http://127.0.0.1:8080/v1/info in a browser, or curl http://127.0.0.1:8080/v1/info (curl.exe in Windows PowerShell), answers:

/v1/info
{"protocol":1,"min_protocol":1,"modules":["auth","chat","files","friends","groups","leaderboards","lobbies","matchmaking","notifications","oauth","storage"]}

The image is the reference server for linux/amd64 and linux/arm64 with a configuration built in: SQLite in /data, migrations applied on start, accounts, storage, chat with a world room, a highscore leaderboard, notifications, friends, groups, the OpenID Connect module (no provider configured), lobbies, matchmaking with a duel queue, players' files in /data/files.

The trial is plain HTTP with open registration, for your own computer: the port is published on 127.0.0.1 only. A server for players uses the production Compose file (HTTPS through Caddy).

Measured on a small VPS

10 000authenticated WebSockets over HTTPS through Caddy: all connected, none closed during the hold; server ~15 KiB per socket
600 000of 600 000 chat deliveries over HTTPS: 200 members, 50 senders at 1 message/s, every message stored
~4 500/sHTTP requests on /v1/info through Caddy, 64 connections
5000of 5000 sockets reconnected after a redeploy closed them with 1001

Measured on a 2 vCPU / 7.8 GiB virtual machine (Ubuntu 24.04, MySQL 8 or PostgreSQL 16 on the same machine, Caddy in front). The HTTPS rows ran load_test on that same machine, so it shared the 2 vCPU with the server, Caddy and the database. Every number, SQLite against PostgreSQL, and the setup →

07 Steam

Steam login, friends who play, invites.

A Steam crate for Bevy, the Steam side of the server, and demos that show it end to end.

bevy_steam_kit 0.2.0

Steam for Bevy

One plugin with the one Steam callback pump of the process, and opt-in features: lobby (lobbies, rich presence so friends see "Join Game", invites), stats, leaderboards, auth (Web API tickets for a game server), friends, overlay, and steam, the real backend. An in-memory fake Steam for tests.

cargo add
cargo add bevy_steam_kit --features lobby,friends,auth,overlay,steam
net_backend_server

The server's Steam side

  • Steam login and linking: the game posts a Steam Web API ticket to POST /v1/auth/steam; the server asks Steam and links the account to the SteamID64. Needs the server's feature steam with steam_app_id, steam_identity and a publisher Web API key (steam_web_api_key_file).
  • Friends who play here: a Steam-linked player sends its Steam friends' IDs (POST /v1/friends/steam) and gets back the ones with an account on the server; findable by default, a per-player setting turns it off.
  • Invites with join codes: a lobby's join code also exists as a number, so it travels through Steam: +nb_lobby 590122524587 = join code K7M2-Q9XD. Join codes, invites and "Join Game" need no Steam login on the server.
the demos

The demos with Steam

in a generated project
cargo run -p demo --features steam

A Steam panel with Steam login and linking, the Steam friends who have an account on the server (with a friend request to each), the "findable through Steam" setting, "Join Game" and Steam invites for the current lobby, and joining a lobby from Steam. The Bevy demo uses bevy_steam_kit; the egui demo uses steamworks directly. Steam must be running and logged in; the app id is STEAM_APP_ID (480, Valve's test app "Spacewar", when not set).

08 Free and open source

MIT OR Apache-2.0. Build on it.

Every crate, in three repositories: net_backend (protocol, server, client, the installer, the deploy files, API.md), bevy_net_backend and bevy_steam_kit. Issues and pull requests are welcome. Self-hosted: your server, your database, your players' data.