Hazel

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:

CrateWhat it is
crates/api/renzora_network_apiThe multiplayer contract: components, the replication registry, RPCs, session queries. renzora::network to a plugin or script
crates/renzora_networkThe multiplayer runtime: UDP transport, server, client, replication
crates/renzora_network_editorThe Network panels and inspector entries (Editor scope)
crates/api/renzora_net_apiThe HTTP contract: request vocabulary and the Backend trait
crates/renzora_netThe HTTP front end: blocking facade and the per-frame pump
crates/renzora_httpAn 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).

ModuleJob
transportDatagrams, handshake, reliability, fragmentation. Sans-IO except udp.rs
protocolThe game messages carried over the transport
serverAccept players, route RPCs, replicate (NetworkServerPlugin)
clientConnect, mirror the server's world, report the player's own avatar
interpolationSmooth remote motion on a shared server clock
spawnerOne avatar per player, and prefab instancing
reflect_ioComponents to bytes and back by type path
script_extensionNetwork 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:

PacketSent byMeaning
ConnectRequest { protocol, nonce }ClientLet me in. Repeated until answered
Challenge { nonce, token }ServerProve you receive at the address you claim
ChallengeResponse { nonce, token }ClientThe echo
Accepted { client_id, tick_rate }ServerYou are in
Denied { reason }ServerServerFull or ProtocolMismatch
Payload { seq, ack, ack_bits, messages }EitherMessages plus acknowledgements
DisconnectEitherGoodbye. 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.

ConstantValueWhy
MAX_PACKET_BYTES1200Below every real path MTU, so the network itself never fragments a datagram
FRAGMENT_BYTES1000Largest piece of a split reliable message
MAX_UNRELIABLE_BYTES1100Unreliable 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.

TimerValue
Handshake retry200 ms
Connect timeout10 s, ending with "no answer from the server"
Peer timeout8 s of silence

Reliability

connection.rs implements both channels over one peer:

  • Every Payload carries a 16-bit sequence number and acknowledges the last 33 packets received (ack plus 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_BYTES is split, each piece flagged more except 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:

MessageDirectionChannel
Roster { players }Server to clientReliable
Spawn(SpawnData)Server to clientReliable
Despawn { net_id }Server to clientReliable
Update { net_id, changed, removed }Server to clientReliable
Snapshot { time, transforms }Server to clientUnreliable
Owned { time, transforms }Client to serverUnreliable
Rpc { from, target, name, args }EitherAs 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 fills NetworkStatus. 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

  1. Every Networked entity is visited. One not seen before gets a NetworkId (unless it already has one) and a Spawn to every client.
  2. For one seen before, each component in the ReplicationRegistry is serialized and compared with what was last sent. Changes and removals go out as one Update.
  3. A recorded entity that is gone, or no longer Networked, goes out as a Despawn.
  4. 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.
  5. 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:

TargetDelivered to
ServerThe server's own scripts
AllThe server's scripts and every client
OthersEvery 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 Networked object placed in the editor exists on both. A Spawn carries the entity's SceneEntityId, 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 NetSpawned and despawned when the session ends; adopted scene entities are released (their NetworkId removed) 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 --connect launch 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:

  1. Registered in the ReplicationRegistry, by type path.
  2. Reflected with #[reflect(Component)] and registered with the type registry on every peer.
  3. On a Networked entity.
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:

FlagRole
--serverHeadless dedicated server: no window or GPU, driven by a fixed-rate runner at the tick rate, with a console for its log
--hostListen 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:

SettingFlagDefault
server_addr--addr, --address127.0.0.1
port--port7636
tick_rate--tick-rate64
max_clients--max-clients32
transportnoneudp

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:

FieldMeaning
roleOffline, Client, DedicatedServer or Host
stateThe connection state
is_server, client_idThis process's side and peer id
rtt_ms, jitter_ms, packet_lossLink quality (client)
bytes_in_per_sec, bytes_out_per_secTraffic, summed over clients on a server
tickSend ticks since the server started
connected_clientsPer client: id, round trip, packet loss (server)
playersThe roster
replicated_entitiesHow many entities are replicated
last_errorWhy 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_api defines the request vocabulary and the Backend trait (name, init, start, poll, cancel, shutdown). A backend registers with App::add_net_backend. start must not block: it is called from the frame, so it spawns the transfer and returns, and poll hands 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 with Error::NoPump after two seconds rather than hanging). Call it from a thread of your own.
  • renzora_http (RenzoraHttpPlugin) is the backend over ureq and 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, where ureq does 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.