Networking Internals
This page is about how multiplayer works inside the engine: the transport, the handshake, replication, RPC routing and the server process. To use multiplayer in a game, read Multiplayer first; it covers the components and the script API from the game's side.
"Networking" names two unrelated things in this workspace, and the crate names do not make that obvious:
| Crate | What it is |
|---|---|
crates/api/renzora_network_api | The multiplayer contract: components, the replication registry, RPCs, session queries. renzora::network to a plugin or script |
crates/renzora_network | The multiplayer runtime: UDP transport, server, client, replication |
crates/renzora_network_editor | The Network panels and inspector entries (Editor scope) |
crates/api/renzora_net_api | The HTTP contract: request vocabulary and the Backend trait |
crates/renzora_net | The HTTP front end: blocking facade and the per-frame pump |
crates/renzora_http | An HTTP backend over ureq (Editor scope) |
The first three are multiplayer and are the bulk of this page. The last three are covered under HTTP at the end.
Layout
renzora_network is a Runtime-scope plugin and an optional engine feature: the networking feature of renzora_runtime pulls it in, and a lean export of a project that never uses multiplayer strips it (the networking capability; see Export System).
| Module | Job |
|---|---|
transport | Datagrams, handshake, reliability, fragmentation. Sans-IO except udp.rs |
protocol | The game messages carried over the transport |
server | Accept players, route RPCs, replicate (NetworkServerPlugin) |
client | Connect, mirror the server's world, report the player's own avatar |
interpolation | Smooth remote motion on a shared server clock |
spawner | One avatar per player, and prefab instancing |
reflect_io | Components to bytes and back by type path |
script_extension | Network verbs declared for language backends |
Everything but the type registrations is native only. A browser cannot open a UDP socket, so on wasm NetworkPlugin registers the types and stops, and every renzora::network call behaves as it does offline.
The contract is deliberately free of the runtime. A game, a plugin or a Rust script talks to resources defined in renzora_network_api (NetOutbox, NetworkStatus, ReplicationRegistry) and to the scripting inboxes in renzora_scripting_api; the runtime drains and fills them. That is why a single-player export can drop the runtime without the game's code failing to compile, and why a Rust script, which cannot reach App, can still replicate a component and send an RPC through &mut World.
Transport
A from-scratch reliability layer over UDP, in transport/. It is written sans-IO: ServerEndpoint and ClientEndpoint take datagrams in through receive and hand datagrams out through take_outgoing, and never touch a socket. udp.rs is the only file that does, moving bytes between a non-blocking UdpSocket and the endpoints. Keeping I/O out is what lets the tests run a session through a simulated network that loses, duplicates and reorders packets.
Packets
Every datagram is MAGIC (RZN followed by the wire version byte, currently 2) and then one bincode-encoded Packet:
| Packet | Sent by | Meaning |
|---|---|---|
ConnectRequest { protocol, nonce } | Client | Let me in. Repeated until answered |
Challenge { nonce, token } | Server | Prove you receive at the address you claim |
ChallengeResponse { nonce, token } | Client | The echo |
Accepted { client_id, tick_rate } | Server | You are in |
Denied { reason } | Server | ServerFull or ProtocolMismatch |
Payload { seq, ack, ack_bits, messages } | Either | Messages plus acknowledgements |
Disconnect | Either | Goodbye. Sent several times, since nothing acknowledges it |
A datagram without the magic is dropped before any decoding, and decoding is bounded so a forged length prefix cannot make the receiver allocate without limit. Bumping the version byte makes old and new builds ignore each other instead of misreading each other.
| Constant | Value | Why |
|---|---|---|
MAX_PACKET_BYTES | 1200 | Below every real path MTU, so the network itself never fragments a datagram |
FRAGMENT_BYTES | 1000 | Largest piece of a split reliable message |
MAX_UNRELIABLE_BYTES | 1100 | Unreliable messages are never split: losing any piece would lose all of it |
Handshake
The challenge step exists so a server keeps no state for a client until the client has proved it receives at its source address. The token is a keyed hash of the address and the nonce, with a secret the server picks at startup; the server can recheck it from the response alone. Without that step anyone could fill every slot by sending requests with forged source addresses.
The protocol value is server::protocol_id: a hash of the project's name and the wire magic. A client of a different game, or of an incompatible build of this one, is turned away at the handshake with ProtocolMismatch rather than misreading the stream.
On acceptance the server assigns a random 64-bit client id (at least 2, unique in the session). Ids are unpredictable to a stranger but not cryptographic, and there is no encryption: everything on the wire is readable.
| Timer | Value |
|---|---|
| Handshake retry | 200 ms |
| Connect timeout | 10 s, ending with "no answer from the server" |
| Peer timeout | 8 s of silence |
Reliability
connection.rs implements both channels over one peer:
- Every
Payloadcarries a 16-bit sequence number and acknowledges the last 33 packets received (ackplus a 32-bit field). Acks ride on traffic that is going out anyway, so a lost ack is repaired by the next packet. - A reliable message is included again on a timer until a packet that carried it is acknowledged. The timer is 1.5 times the measured round trip, with a 50 ms floor so a LAN does not resend every frame. The receiver buffers out-of-order arrivals and releases them strictly in id order, so reliable messages arrive exactly once, in send order.
- A reliable message larger than
FRAGMENT_BYTESis split, each piece flaggedmoreexcept the last, and reassembled before delivery. This is what lets a late joiner receive the whole world as a stream of spawns. - At most 4096 reliable ids may be in flight past the oldest unacknowledged one, which keeps the 16-bit id comparison unambiguous.
- One flush builds at most 48 packets, so a large burst spreads over several frames instead of overflowing the socket buffer.
- With nothing to send, a keepalive goes out every 100 ms, so a quiet but healthy link never times out.
- A packet not acknowledged within one second counts as lost, which is the packet-loss figure the status reports.
On Windows, an ICMP "port unreachable" from an earlier send surfaces as ConnectionReset on the next receive. It says a peer went away, not that the socket broke, so the reader keeps going.
Protocol
Inside a payload, protocol::NetMessage is the game's vocabulary:
| Message | Direction | Channel |
|---|---|---|
Roster { players } | Server to client | Reliable |
Spawn(SpawnData) | Server to client | Reliable |
Despawn { net_id } | Server to client | Reliable |
Update { net_id, changed, removed } | Server to client | Reliable |
Snapshot { time, transforms } | Server to client | Unreliable |
Owned { time, transforms } | Client to server | Unreliable |
Rpc { from, target, name, args } | Either | As the sender chose |
Everything that must arrive and arrive in order (spawns, despawns, component changes, the roster, RPCs by default) is reliable. Transforms are unreliable: they are sent again a moment later anyway, so a lost one is replaced rather than resent.
Components travel as (type_path, json_bytes). JSON because Bevy's reflection deserializer needs a self-describing format for maps and enums, and because a component that fails to decode should fail with a readable error. Transforms change every tick, so they get the compact WireTransform instead: translation always, rotation and scale only when the entity's NetworkTransform syncs them. A snapshot holds at most 18 transforms, to stay under the unreliable size limit.
RPC arguments are a JSON object. JSON cannot tell an integer from a float, so a whole number decodes as an integer and anything else as a float, and RpcArgs reads either as either. A three-number array is a Vec3.
Server
NetworkServerPlugin is added beside NetworkPlugin only for --server and --host. Its startup system binds UDP on 0.0.0.0:<port>, inserts the NetServer resource, and sets NetworkStatus to DedicatedServer or Host. A port that cannot be bound is logged and written to NetworkStatus::last_error; the process keeps running without a server.
The frame is bracketed by two exclusive systems:
server_receive(PreUpdate) drains the socket, turns connects and disconnects into roster changes and player events, and handles messages. It runs first so scripts see this frame's RPCs and joins.server_send(PostUpdate) sends the outbox's RPCs, replicates when a send tick is due, flushes the endpoint and fillsNetworkStatus. It runs last so what scripts did this frame goes out this frame.
Snapshots go out at the project's tick rate, capped at 30 per second (MAX_SEND_RATE): above that bandwidth grows and smoothness does not, because interpolation already hides the gaps. A long frame restarts the schedule instead of bursting to catch up.
Replication, per send tick
- Every
Networkedentity is visited. One not seen before gets aNetworkId(unless it already has one) and aSpawnto every client. - For one seen before, each component in the
ReplicationRegistryis serialized and compared with what was last sent. Changes and removals go out as oneUpdate. - A recorded entity that is gone, or no longer
Networked, goes out as aDespawn. - Transforms go into snapshots: those that moved more than a small threshold (so physics noise at rest does not stream a still object forever), plus every one at least once a second, which repairs a lost final update.
- A client that joined since the last tick then gets the roster and the whole world as spawns. It is sent after the diff, so what it receives is current, and it is left out of that tick's broadcast.
Diffing serialized bytes means a game needs no change tracking of its own: any registered, reflected component on a Networked entity replicates when its value changes.
Owner-moved entities
An entity whose NetworkTransform::authority is Owner and whose NetworkOwner is a client is moved by that client. The client reports it in Owned messages; the server accepts a report only for an entity that client owns and is allowed to move, and ignores the rest. The server relays the owner's own report to everyone else rather than its interpolated copy (relaying that would add the interpolation delay twice), and leaves the entity out of the owner's own snapshots: an echo arriving 50 ms late would drag the avatar backwards.
RPC routing
The server stamps from with the connection's id, whatever the message claims, so one player cannot speak as another. Then by target:
| Target | Delivered to |
|---|---|
Server | The server's own scripts |
All | The server's scripts and every client |
Others | Every client but the sender, and the server's scripts unless the server sent it |
Peer(id) | That client, or the server's scripts if id is the server's own peer id |
Delivery to the local process is a push onto ScriptRpcInbox, which the scripting system turns into the Rpc hook. With no session at all, rpc::route_offline delivers Server and All RPCs locally with from: 0, so a game written for multiplayer still works alone.
A client leaving despawns every entity it owned.
Listen server
With --host the process is a client and a server at once. The host's own player is not a connection: it has the fixed peer id HOST_PEER_ID (1), anything addressed to it is delivered in-process, and it is listed first in the roster. A dedicated server is SERVER_PEER_ID (0) and has no player.
Client
connect (from renzora::network::connect or --connect) resolves the address, preferring IPv4: a server bound to 0.0.0.0 does not answer on ::1, which localhost resolves to first on Windows. An empty address or port 0 falls back to the project's [network] values.
client_receive and client_send mirror the server's pair. Notable behaviour:
- Adopting scene entities. Client and server load the same scene, so a
Networkedobject placed in the editor exists on both. ASpawncarries the entity'sSceneEntityId, and the client adopts its own copy instead of spawning a second. A spawn can arrive before the client's scene finishes loading, so an unmatched one waits up to 5 seconds for its entity before spawning fresh. - Disconnect cleanup. Entities the network spawned are marked
NetSpawnedand despawned when the session ends; adopted scene entities are released (theirNetworkIdremoved) and stay as they were. - RPCs wait while connecting and go once the handshake completes.
- Owned transforms are reported at up to 30 Hz, only when they moved or once a second.
- Retry. A
--connectlaunch retries a server that does not answer for up to 60 seconds. Play starts the server and its clients at the same moment, and a cold server can take longer to open its port than one handshake waits.
On AppExit both sides send Disconnect, so the other end sees it at once instead of after the 8-second timeout.
Interpolation and the shared clock
Every remote entity keeps a short history (one second) of (server time, transform) samples in NetInterpolation, and apply_interpolation draws it at a point INTERPOLATION_DELAY (100 ms) in the past, between the two samples either side. The delay is what a lost packet hides behind.
All times are server time. NetClock on a client starts from the first snapshot's stamp plus half the round trip, advances with the local frame time, and is nudged 5% toward each new stamp so drift and changing latency are absorbed gradually; a gap of more than 250 ms snaps instead. A client stamps its own Owned reports with the same clock, so both directions share one timeline. apply_interpolation only writes a transform that changed, so change detection downstream (and the replication diff on a host) stays meaningful.
A client's own owner-moved avatar has no NetInterpolation; the client moves it directly.
Avatars
When a player joins, the server queues them in PendingAvatars. Once the scene's NetworkPlayerSpawner exists (a player can join before the server's scene has loaded), it spawns the spawner's prefab for each, owned by that player and marked NetworkPlayer. Avatars are spread around the spawner by the golden angle, so any number of players are evenly apart with no table of slots. instance_prefabs turns a NetworkPrefab into a scene instance on every peer, from each peer's own copy of the project, so a prefab's looks never cross the wire.
Replicating your own components
A component replicates when it is all three of:
- Registered in the
ReplicationRegistry, by type path. - Reflected with
#[reflect(Component)]and registered with the type registry on every peer. - On a
Networkedentity.
use bevy::prelude::*;
use renzora::network::AppReplicateExt;
#[derive(Component, Reflect, Default)]
#[reflect(Component, Default)]
struct Health(f32);
fn build(app: &mut App) {
app.register_type::<Health>().replicate::<Health>();
}
The registry is keyed by type path rather than Rust type for two reasons: a Rust script cannot reach App but can reach the resource (world.resource_mut::<ReplicationRegistry>().register::<Health>()), and the type path is the identity on the wire anyway. The defaults are Name, NetworkOwner, NetworkPlayer, NetworkPrefab and NetworkTransform: without them a client would receive a bare position with nothing to draw at it.
A path that is not registered for reflection on a peer is skipped with one warning, not treated as a reason to stop replicating everything else.
Server mode and configuration
The binary decides its role from flags in src/main.rs:
| Flag | Role |
|---|---|
--server | Headless dedicated server: no window or GPU, driven by a fixed-rate runner at the tick rate, with a console for its log |
--host | Listen server: a normal windowed game that also accepts players |
--connect [address[:port]] | Join a server at startup. Bare --connect uses the project's [network] address |
renzora_runtime::server::config_from_args builds the server's NetworkConfig before the App exists (the headless runner needs the tick rate). Each value comes from a flag, else from the project's [network] section, else from the default:
| Setting | Flag | Default |
|---|---|---|
server_addr | --addr, --address | 127.0.0.1 |
port | --port | 7636 |
tick_rate | --tick-rate | 64 |
max_clients | --max-clients | 32 |
transport | none | udp |
The project is read from the same places the game reads it: the archive (the --rpak server.rpak an exported server's launcher passes, or the one embedded in the binary), then --project, then ./project.toml. A packed server has no project.toml on disk, so this order is what makes it honour its own configuration.
transport parses webtransport and websocket as well, but only UDP is implemented: the server and client always open a UDP socket.
If the build has no networking (a lean export that stripped it), config_from_args returns None and --server or --host logs a warning and starts an ordinary client instead of silently ignoring the flag.
The project's [network] section also holds play_mode (single, host or server) and play_clients, read by the editor's Play button. host starts the game with --host; server starts a headless --server first and the game with --connect; each extra client is another process with --connect 127.0.0.1:<port>. Play always uses the loopback address, since server_addr is where a shipped game finds its server, not where a test session runs.
Status
NetworkStatus is the one place to read the session's state, filled by the runtime every frame:
| Field | Meaning |
|---|---|
role | Offline, Client, DedicatedServer or Host |
state | The connection state |
is_server, client_id | This process's side and peer id |
rtt_ms, jitter_ms, packet_loss | Link quality (client) |
bytes_in_per_sec, bytes_out_per_sec | Traffic, summed over clients on a server |
tick | Send ticks since the server started |
connected_clients | Per client: id, round trip, packet loss (server) |
players | The roster |
replicated_entities | How many entities are replicated |
last_error | Why the last session ended, unless it was by choice |
The renzora::network session functions (role, is_server, is_client, is_connected, local_peer_id, players, owner_of, net_id_of, entity_by_net_id, is_mine, has_authority, connect, disconnect, spawn_prefab) are thin readers over this and the components. spawn_prefab on a client does nothing and returns None: only the server creates replicated entities, and a client asks it to with an RPC.
Editor
renzora_network_editor registers three panels (network_monitor, network_entities, network_settings) and inspector entries for Networked, NetworkTransform, NetworkOwner and NetworkPlayerSpawner. The monitor and entities panels read NetworkStatus and the Networked entities; the settings panel shows the project's [network] configuration.
Testing
crates/renzora_network/tests/session.rs runs a whole session over real UDP on localhost: a server App and client Apps in one process with the real plugins, stepped frame by frame. It proves what the transport's unit tests cannot, that the server's replication, the client's adoption and the routing agree end to end.
cargo test --profile dist -p renzora_network
Bind the server to port 0 in a test (NetworkConfig { port: 0, .. }) and read the chosen port from NetServer::local_addr, so parallel tests never collide.
HTTP
HTTP is a separate system with a separate shape: the engine describes requests and something else performs them.
renzora_net_apidefines the request vocabulary and theBackendtrait (name,init,start,poll,cancel,shutdown). A backend registers withApp::add_net_backend.startmust not block: it is called from the frame, so it spawns the transfer and returns, andpollhands back whatever finished.renzora_net(NetPlugin) is the front end.Request::get(url).send()blocks the calling thread while a per-frame pump hands the request to the backend and routes the answer back. Never call it from a system: the pump needs the frame to progress, so it would wait on itself (it gives up withError::NoPumpafter two seconds rather than hanging). Call it from a thread of your own.renzora_http(RenzoraHttpPlugin) is the backend overureqand rustls. It is Editor scope: the editor's marketplace, update check, template and source downloads all need it, but a shipped game does not get it, which keeps the TLS stack (about twenty crates) out of games that never make a request. It is absent on wasm, whereureqdoes not compile.
Keeping the client behind a trait is what lets a platform supply its own (a browser's fetch, a console's certified library). See Network Backends for writing one.