Start typing to search packages!
volt
By @fadeluc-123
Roblox
Mirrored from WallyVolt
Networking for Roblox games: one file describes every message, and a tool turns it into typed Luau modules.
Contents
- What Volt is
- Why use it
- Install
- Your first schema
- Compile
- Use it in your scripts
- Types
- Choosing how a message travels
- Sending less
- Safety defaults
- More tools
- Colors in VS Code
- Options
- Troubleshooting
- Versions
- Working on Volt
- License
What Volt is
Volt is a networking library for Roblox. You describe every message your game sends between the server and its players in one text file, called a schema, and a command-line tool called volt turns that file into Luau modules. Your scripts call those modules instead of creating and firing RemoteEvents.
Why use it
Your game sends less data. Volt writes each message into a buffer, which is a block of raw bytes, instead of sending Luau tables. A number from 0 to 255 takes one byte, and eight true or false values share one byte. The reliable messages fired during one frame go out together, in one remote call per player.
The code Volt writes reads and writes each value at a fixed place in the buffer, so turning a message into bytes and back takes little work.
The server checks every value. Before your code sees a message from a player, Volt checks each value against the type the schema gives it: its range, its length, its class. A message that fails is dropped and reported. Every message from a player also has a rate limit, so one player cannot flood the server.
Every message is listed in one place. The schema names each message, who sends it and what it carries, so all of your game's network traffic can be read in one file. The generated modules are fully typed, so your editor knows the type of every argument.
Install
Volt has two parts. The first is volt, a compiler: a program that reads one kind of file and writes code from it. It runs on your computer while you work. The second is the runtime, a small Luau package that runs inside your game and does the sending and receiving. Rokit installs the compiler and Wally installs the runtime.
These steps assume your game is a Rojo project that already uses Rokit, which installs command-line tools, and Wally, which installs Luau packages.
-
Install the compiler. In your game's folder, run:
rokit add fadeluc-123/voltThis pins
voltin yourrokit.toml, so everyone who works on the game gets the same version. -
Add the runtime to your
wally.toml, under[dependencies]. Wally 0.3.2 has noaddcommand, so you type the line yourself:[dependencies] Volt = "fadeluc-123/volt@0.1.0"Then install it:
wally installKeep the name on the left as
Volt, with a capital V. Wally names the entry inPackages/after it, Roblox instance names are case sensitive, and every generated module requiresReplicatedStorage.Packages.Voltunless told otherwise, so a lowercase name fails at the firstrequire. A different name works only if every schema sets a matchingoption runtime, and that only helps your game's own schemas. A package built on Volt that runs its own scope was compiled withReplicatedStorage.Packages.Voltwritten into it, so a game that uses any such package installs Volt asVolt.If your game uses a package that was compiled with
option yield = promise, also install evaera's Promise library asPromise:Promise = "evaera/promise@4.0.0"That puts it at
ReplicatedStorage.Packages.Promise, the path the package's client module requires. The package's own copy of Promise sits insidePackages/_Index, which that path never reaches. -
Map Wally's
Packagesfolder toReplicatedStorage.Packagesin your Rojo project file. The examples in this README also putsrc/SharedatReplicatedStorage.Shared, the server scripts inServerScriptServiceand the client scripts inStarterPlayerScripts. Adefault.project.jsonthat does all of that:{ "name": "MyGame", "tree": { "$className": "DataModel", "ReplicatedStorage": { "Packages": { "$path": "Packages" }, "Shared": { "$path": "src/Shared" } }, "ServerScriptService": { "Server": { "$path": "src/Server" } }, "StarterPlayer": { "StarterPlayerScripts": { "Client": { "$path": "src/Client" } } } } } -
Give the type checker Volt's types. Each time you install packages, run all three commands, in this order:
wally install rojo sourcemap default.project.json --output sourcemap.json wally-package-types --sourcemap sourcemap.json Packages/For each package, Wally writes a small file in
Packages/that points at the package's real code, and those files leave the package's types out. The generated modules use Volt's types, such asVolt.Runtime, so in a game that uses--!strictthe type checker reportsUnknown type 'Volt.Runtime'and dozens of errors after it until this step runs. The second command writes a map of your project tosourcemap.json. The third uses that map to rewrite the small files with the types included. If you do not havewally-package-typesyet, add it withrokit add JohnnyMorganz/wally-package-types.The type checker here is luau-lsp, which also runs inside VS Code as the Luau Language Server extension. It has two checkers, the old one it runs by default and the new one, called
LuauSolverV2, and the generated modules check clean under both. To use the new one in VS Code, put these lines in your game's.vscode/settings.json:{ "luau-lsp.fflags.enableNewSolver": true, "luau-lsp.fflags.enableByDefault": true, "luau-lsp.fflags.sync": false }Each line sets Luau flags, the switches that turn Luau's newer features on or off.
enableNewSolverturns the new checker on.enableByDefaultturns on every flag that is simply on or off, asluau-lsp analyzedoes on the command line.sync: falsestops the extension from copying the flags Roblox has set today, so a change Roblox makes to them never reaches your editor unannounced. On the command line, pass--flag:LuauSolverV2=truetoluau-lsp analyze, which otherwise runs the old checker.
Your first schema
A schema is a text file whose name ends in .volt. It lists your messages and says where volt writes the modules. Save this as Game.volt in the root folder of your game's project:
-- Every message this game sends between the server and its players
option clientOutput = "src/Shared/Network/Client.luau"
option serverOutput = "src/Shared/Network/Server.luau"
option typesOutput = "src/Shared/Network/Types.luau"
-- A player sends the server a small number
event Ping {
from: Client,
type: Reliable,
call: SingleAsync,
data: u8,
}
-- The server sends a small number back
event Pong {
from: Server,
type: Reliable,
call: SingleAsync,
data: u8,
}
-- A player asks the server a question and waits for the answer
function Echo {
data: string(0..32),
return: string(0..32),
}
Here is what each line does.
- A line that starts with
--is a comment. Volt ignores it. option clientOutput = "..."is wherevoltwrites the module your LocalScripts use. The path is relative to the folder that holdsGame.volt.option serverOutput = "..."is where it writes the module your server Scripts use.option typesOutput = "..."is where it writes a module of types for code that both sides share. It is optional; leave the line out if you do not need it.event Ping {starts an event namedPing. An event is a one-way message: one side fires it, the other side listens, and nothing comes back.from: Clientsays who fires it:Clientfor a player's LocalScripts,Serverfor the server, orBoth.type: Reliablemeans the message always arrives, exactly once, in the order it was fired. AnUnreliablemessage can be lost. Choosing how a message travels says when to use each.call: SingleAsyncsays how the listening side runs its listener.Singleallows one listener, andAsyncruns each message on its own thread, so the listener may wait. The same section explains the other modes.data: u8is what the message carries: one whole number from 0 to 255.u8is short for "unsigned 8-bit", a number that is never negative and fits in one byte. Types lists every type.}ends the event. Each key inside it ends with a comma.event Pong { ... }is the same shape withfrom: Server, so the server fires it and the players listen.function Echo {starts a function. A function is a question with an answer: a player calls it, the server runs a handler, and the handler's return value goes back to that player. A function goes from a client to the server unless it says otherwise; When the server asks a player shows one that goes the other way.data: string(0..32)is what the player sends: a string from 0 to 32 bytes long.return: string(0..32)is what the server answers with.
The schema leaves two options at their defaults. option runtime is where the modules find the Volt runtime, and it defaults to ReplicatedStorage.Packages.Volt, where Wally put it. option scope names the folder Volt makes for this schema's remotes, and it defaults to the schema's file name, so this schema's remotes live in ReplicatedStorage.Volt.Game. Two schemas with different names never see each other's messages.
data can also be a list of named values, called a parameter pack. With data: (x: f32, y: f32) the sender calls fire(x, y) and the listener receives x and y as two arguments.
Compile
volt does not create folders, so make the output folder once (in PowerShell, leave out -p):
mkdir -p src/Shared/Network
Then run the compiler on the schema:
volt Game.volt
It prints one line:
Game.volt: ok, schema hash 0x894D330D
The schema hash is a fingerprint of the schema. Any change to a message or an option changes it, so yours will differ once your schema does.
These files now exist:
| File | Required by |
|---|---|
src/Shared/Network/Client.luau | your LocalScripts |
src/Shared/Network/Server.luau | your server Scripts |
src/Shared/Network/Types.luau | shared code that wants the types; written only when typesOutput is set |
the path inspectorOutput gives, such as src/Shared/Network/Inspector.luau | PacketProfiler, which shows what each packet holds; written only when inspectorOutput is set, which Game.volt does not do (The packet inspector) |
Each one starts with a comment saying it was generated. Never edit them. Change the schema and run volt again instead.
A schema too large for one client module and one server module also writes shard files beside them, such as ServerShard1.luau; A schema too big for one module explains them.
Run volt again after every change to the schema. The client module and the server module must come from the same schema, or the server kicks every player (see Safety defaults).
When the schema has a mistake, volt prints each one with its line, its column and a code, writes nothing and exits with code 1:
Game.volt:5:2: error V2003: unknown key "form" in event Ping; keys are from, type, call, data, queue, rate, timeout, channel
5 | form: Client,
| ^^^^
Game.volt:4:7: error V2004: missing key "from" in event Ping
4 | event Ping {
| ^^^^
The command takes four flags:
usage: volt <schema.volt | folder> [<file.volt> ...] [--check | --watch] [--ast] [--quiet]
--checkwrites nothing. It compiles the schema and compares each file it would write with the one already on disk, line endings aside: the client and server modules, the types module, every shard and the packet inspector.--watchkeeps running and compiles the schema again each time you save it (Compiling on every save).--astalso prints the schema in its full form, with every default filled in.--quietleaves out theokline.
--check and --watch cannot be used together. Given both, volt prints the usage line above and exits with code 2. It does the same when it is given no schema, a folder with no .volt file directly inside it, or a further argument that is not an existing .volt file. A schema file that does not exist is named, and the command exits with code 1:
volt: Game.volt is missing
Use --check in continuous integration (CI), the checks that run on every push, to prove the committed modules match the schema:
volt Game.volt --check
When they match, it prints the usual ok line and exits with code 0. When they do not, it names each file and exits with code 1:
Game.volt: src/Shared/Network/Client.luau is out of date
Game.volt: src/Shared/Network/Server.luau is out of date
A file that should exist and does not, such as a shard nobody committed or an inspector the schema has just asked for, is reported as missing:
Game.volt: src/Shared/Network/ServerShard2.luau is missing
A shard file the schema no longer writes is reported as no longer generated (A schema too big for one module):
Game.volt: src/Shared/Network/ServerShard3.luau is no longer generated
Each module's first comment names the Volt version that wrote it, so after you upgrade volt every module reads as out of date until you compile again.
A schema in several files
A large game can split its schema across a folder. volt compiles every .volt file directly inside the folder, and none in its subfolders, as one schema. This example has one mode, Arena, that reuses a file the main game keeps elsewhere:
Arena/
Network/ the generated modules go here
Schemas/
Arena.volt the options
Round.volt
Types.volt
Game/
Schemas/
Combat.volt
Types.volt
One file in the folder sets the options. Here it is Arena/Schemas/Arena.volt, which may also hold declarations:
option clientOutput = "../Network/Client.luau"
option serverOutput = "../Network/Server.luau"
option typesOutput = "../Network/Types.luau"
namespace Arena {
event Ready {
from: Client, type: Reliable, call: SingleSync,
}
}
The other files hold only declarations. Arena/Schemas/Round.volt uses a type that Arena/Schemas/Types.volt declares:
namespace Round {
event Start {
from: Server, type: Reliable, call: SingleAsync,
data: (score: Score),
}
}
type Score = u16(0..1000)
Create Arena/Network once, then compile the folder by naming it:
volt Arena/Schemas
The output paths are relative to the options file's folder, and the scope is the options file's name, Arena. To reuse a file kept in another folder, name it after the folder. Every path on the command line is relative to the folder you run the command in:
volt Arena/Schemas Game/Schemas/Combat.volt
A reused file compiles only when every name it uses is declared somewhere in the schema. This is how a mode builds on a base layer of shared types. Game/Schemas/Combat.volt uses Hit:
namespace Combat {
event Strike {
from: Client, type: Reliable, call: SingleSync,
data: Hit,
}
}
and the game declares Hit in Game/Schemas/Types.volt:
struct Hit { target: u16, amount: u16(1..999) }
So the command above fails, because nothing in the schema declares Hit:
Game/Schemas/Combat.volt:4:9: error V3001: unknown type "Hit"
4 | data: Hit,
| ^^^
There are two fixes. The mode's own Arena/Schemas/Types.volt can declare Hit, or you can pass the game's Types.volt as one more file:
volt Arena/Schemas Game/Schemas/Types.volt Game/Schemas/Combat.volt
Arena/Schemas/Arena.volt: ok, schema hash 0x41DAE044
Do one or the other. A name declared in both is an error:
Game/Schemas/Types.volt:1:8: error V3002: "Hit" is declared twice
1 | struct Hit { target: u16, amount: u16(1..999) }
| ^^^
There is no import. The files are read in a fixed order, the options file first, then the folder's other files by name, then the extra files in the order given, so every machine gets the same result. An option in any file but the options file is an error.
Compiling on every save
--watch compiles the schema, then keeps running and compiles it again each time it changes, so the modules follow your edits with no second command:
volt Game.volt --watch
It prints the usual line for the first compile, and again for each compile after it. Change Pong's data from u8 to u16 and save, and a second line follows:
Game.volt: ok, schema hash 0x894D330D
Game.volt: ok, schema hash 0xD2A7CAA1
- It reads the schema files' modification times every quarter of a second. Once it sees a change, it waits until the files read the same at two checks in a row, then compiles. The modules are written a quarter to half a second after your last save, and a save that writes several files compiles once.
- It watches what the command reads: the one file, or every
.voltfile directly inside the folder, plus any further files you name. A.voltfile added to the folder or removed from it counts as a change. It never watches the modules it writes, so writing them starts no compile. - A schema with a mistake prints its errors, as in Compile, and writes nothing. The watch goes on, and the next save that fixes the mistake writes the modules.
- A schema file that goes missing is reported as
volt: Game.volt is missing, and a watched folder left with no.voltfile asvolt: Arena/Schemas holds no schema file. Either way the watch waits for the next change. Any other error, such as an output folder that does not exist, printsvolt: internal error:followed by the error and a stack trace, and the watch goes on. - Each compile is the command run again with the same flags, so
--quietleaves out theoklines and--astprints the full form every time. - It never ends on its own: it runs until its process is stopped.
A schema too big for one module
Luau compiles a module only if its top level declares at most 200 local variables at once. A generated module declares one for each writer, reader and helper it keeps, so a schema with a few hundred messages could pass that limit, and Roblox could not load the module. Volt keeps each generated file under it by splitting such a module into shards: an entry module, written where clientOutput or serverOutput says, and shard files beside it, each holding the writers and readers of some of the messages.
A side is split into shards when either is true:
- Its one module would declare more than 150 locals at its top level. That is Luau's 200, less the margin Luau's documentation asks code near a limit to keep.
- The schema sets
option shardSize = N, and the side has more than N entries. An entry is one event, one function or one exported type.
Volt fills the shards in the order the schema declares its entries. It starts the next shard when the current one already holds shardSize entries, or when the next entry would take it past 150 locals. The client module and the server module decide on their own, so one side can be split while the other is one file. A side that meets neither condition is one module, the same file it would be without shardSize. The types module and the packet inspector are never split.
To see it, add option shardSize = 2 below the options of the schema from Your first schema, which has three entries, and compile again:
volt Game.volt
Game.volt: ok, schema hash 0x894D330D
The hash is the same as without the option. These files now exist:
| File | What it holds | Required by |
|---|---|---|
src/Shared/Network/Client.luau | the client's entry module | your LocalScripts |
src/Shared/Network/ClientShard1.luau | Ping and Pong, for the client | Client.luau |
src/Shared/Network/ClientShard2.luau | Echo, for the client | Client.luau |
src/Shared/Network/Server.luau | the server's entry module | your server Scripts |
src/Shared/Network/ServerShard1.luau | Ping and Pong, for the server | Server.luau |
src/Shared/Network/ServerShard2.luau | Echo, for the server | Server.luau |
src/Shared/Network/Types.luau | the types, never split | shared code that wants the types |
A shard takes its entry's file name with Shard and a number added before .luau, counting from 1, and sits in the entry's folder. The entry requires each shard by that name, as require("./ServerShard1"), so keep the shards beside it. Rojo syncs each one as a ModuleScript, so with the project file from Install they sit beside Client and Server in ReplicatedStorage.Shared.Network.
Your scripts do not change. They require the entry and never a shard, and the entry returns the same Network table a one-file module returns: the same messages and namespaces, the same events, functions and exports, hooks, rate, flush, onFailure and stats, and on the server the same player callbacks and budget, every table frozen. Requiring the server module still never waits, and firing a message costs what it costs in one file, since each message's writer sits in the shard that holds the message.
shardSize changes nothing that is sent, so the schema hash and --ast leave it out. A client and a server compiled with different shardSize values, or with one side split and the other not, still connect.
When a schema shrinks, or loses its shardSize, volt deletes the shard files it no longer writes, so none is left behind. Remove option shardSize = 2 from Game.volt and compile again, and only Client.luau, Server.luau and Types.luau remain. If you commit the generated modules, commit those deletions with them. --check catches a shard that should have been deleted. Run before that compile, it reports:
Game.volt: src/Shared/Network/Client.luau is out of date
Game.volt: src/Shared/Network/Server.luau is out of date
Game.volt: src/Shared/Network/ClientShard1.luau is no longer generated
Game.volt: src/Shared/Network/ServerShard1.luau is no longer generated
It names the first leftover shard of each side and exits with code 1. A shard that should exist and does not is reported as missing, like any module.
Volt never splits one entry: a message's writer, its reader and the helpers they use always share a shard. When one entry alone needs more than 150 locals, the compiler refuses the schema with V4003, reported at that entry. An event Big whose struct has 150 fields, each of its own exported type, gives Big needs 154 module-level locals on the server, more than one generated file holds (150). Give such a message fewer distinct named types, or split it into several messages.
The entry module declares a local for each shard, so it can require only so many. A shardSize so small that a side needs more shards than that is V4003 too, reported at the top of the options file: the server module needs 150 shards, more than its entry can require (146). Raise shardSize, or leave it out so that Volt splits only where it must.
Use it in your scripts
Every script requires its own side's module and names it Network. This server Script is src/Server/Main.server.luau:
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Network = require(ReplicatedStorage.Shared.Network.Server)
-- Runs every time a player fires Ping
Network.Ping.on(function(player, value)
print(`{player.Name} sent Ping {value}`)
-- Answer the player who sent it
Network.Pong.fire(player, value + 1)
-- Tell every player in the server
Network.Pong.fireAll(value)
end)
-- Runs every time a player invokes Echo; what it returns goes back to that player
Network.Echo.on(function(player, word)
return string.upper(word)
end)
This LocalScript is src/Client/Main.client.luau:
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Network = require(ReplicatedStorage.Shared.Network.Client)
-- Runs every time the server fires Pong at this player
local disconnect = Network.Pong.on(function(value)
print(`Pong {value}`)
end)
-- Send Ping to the server
Network.Ping.fire(7)
-- Ask Echo a question and wait for the answer
local ok, answer = Network.Echo.invoke("hello")
if ok then
print(`Echo answered {answer}`)
else
warn(`Echo failed: {answer}`)
end
-- Stop listening to Pong
disconnect()
With one player named Alice, the server prints:
Alice sent Ping 7
and the client prints:
Pong 8
Pong 7
Echo answered HELLO
The client hears both Pongs before the Echo answer because the server fired them first. Reliable messages from one side arrive in the order they were fired, and a function's answer travels in that same line.
On the server:
Network.Ping.on(listener)connects a listener to an event the clients fire. The listener receives the player, then the data.onreturns a function that disconnects the listener.Network.Pong.fire(player, value)sends to one player. It reaches a player who has just joined even when your ownPlayers.PlayerAddedlistener runs before Volt has set that player up, since the fire sets them up.Network.Pong.fireAll(value)sends to every player Volt has set up, so one fired from your ownPlayerAddedlistener can miss the player who just joined. Usefirefor that player.Network.Pong.fireList({ alice, bob }, value)sends to the players in a list,Network.Pong.fireSet({ [alice] = true }, value)to the players in a set, andNetwork.Pong.fireExcept(alice, value)to everyone but one player.Network.Echo.on(handler)connects the one handler a function has. Its return values are the answer. It runs on its own thread, so it may wait, for example on a DataStore, and the server never times it out.
On the client:
Network.Ping.fire(value)sends to the server.Network.Pong.on(listener)connects a listener to an event the server fires. The listener receives the data. It also returns a function that disconnects it.Network.Echo.invoke(...)sends the question and waits. It returnstrueand the answer, orfalseand the reason it failed.
A call fails with one of these reasons:
timeout: no answer came within the function's timeout, 10 seconds by default.no handler: the server has not connected a handler to the function.rate limited: the player called the function more often than its rate allows.too many calls: 65,535 calls to this function are already waiting.edit mode: the game is not running, for example when the module is required from the command bar or a UI story tool.dropped: the call did not fit in what the client may send at once (8,192 bytes by default, seemaxPacketin Options), so Volt dropped it before it left and reported anoutgoingfailure. The call fails at once, without waiting.- Any other reason is the first line of the handler's error, without the script's position: a handler that runs
error("no echo today")gives the reasonno echo today.
A value the schema does not allow raises an error where you fire it. Network.Ping.fire(300) raises Ping: expected u8, since 300 does not fit in a u8, and nothing is sent.
Volt does not send a message the moment you fire it. It collects what you fire and sends it on RunService.Heartbeat, which runs once every frame. The server sends once per frame, so a message it fires arrives about one frame later.
A player's client sends at most 60 times a second, whatever its frame rate. At 60 frames a second or slower, it still sends on every frame. At 240 frames a second it sends on only some frames, so a player who fires every frame sends 60 packets a second, the same as a player at 60 frames a second. A packet is one remote call carrying a batch of messages. This keeps each player under the server's limit of 240 packets a second (maxPacketsPerSecond in Options).
Three options change when that send happens:
option flush = 2makes the server send every second Heartbeat, and a client at most 30 times a second, so more messages share each send.option manualReplication = truestops sending on Heartbeat, and your code sends withNetwork.flush().option flushBytes = 4096also sends at the next Heartbeat once the bytes waiting for one target, one player on the server or the server on a client, have reached 4,096. A frame that piles up bytes goes out without waiting for theflush-th frame, and a quiet one keeps its batch. It still sends undermanualReplication, so setting it there means a send can happen without aNetwork.flush(). Reliable and unreliable bytes count together, on every channel, and bytes held for a player whose handshake has not arrived do not count. That Heartbeat sends everything waiting, as any send does. The compiler warns when every frame sends already, as with the defaultflush = 1and nomanualReplication, since the option would change nothing.
A message that arrives before any listener is connected waits in a queue, up to 64 messages per event. The first listener you connect receives them in the order they arrived.
An event with Single in its call allows one listener at a time. Disconnect the first before you connect another.
Requiring a module outside a running game does no harm. fire and on work but nothing is sent, invoke fails with edit mode, and no remotes are created. Requiring the server module never waits. The client module waits until the server has created the remotes.
Reading messages when you choose
With call: Polling, an event has no listener. Its messages wait in a queue until your code reads them with iter. Add this event to Game.volt and run volt Game.volt again:
-- A player votes for a map; the server reads the votes when it is ready
event Vote {
from: Client,
type: Reliable,
call: Polling,
data: u8,
}
On the server, read the votes once a frame:
local RunService = game:GetService("RunService")
-- Once a frame, read every vote that arrived since the last frame
RunService.Heartbeat:Connect(function()
for _, player, map in Network.Vote.iter() do
print(`{player.Name} voted for map {map}`)
end
end)
On the client, fire it like any event:
-- Vote for map 2
Network.Vote.fire(2)
The server prints Alice voted for map 2. Each step of the loop gives a running count, the player and the data, and removes that message from the queue. On the client the loop gives the count and the data, with no player. The queue holds 64 messages by default, and when it is full the oldest is dropped.
When the server asks a player
A function can also go the other way. The server asks one player a question, and that player's client answers it. Add from: Server to the function. Add this to Game.volt and run volt Game.volt again:
-- The server asks a player to accept a trade, and waits up to 15 seconds
function ConfirmTrade {
from: Server,
timeout: 15,
data: (offer: string(1..64)),
return: boolean,
}
Now the client answers. In the LocalScript, connect the handler right after you require the module:
-- Runs every time the server asks; what it returns goes back to the server
Network.ConfirmTrade.on(function(offer)
print(`The server offers {offer}`)
return true
end)
print(`Answering trades: {Network.ConfirmTrade.connected()}`)
The server asks. This server Script asks each player once their client has connected:
Network.onHandshake(function(player)
local ok, accepted = Network.ConfirmTrade.invoke(player, "3 wood for 1 stone")
if ok then
print(`{player.Name} answered {accepted}`)
else
warn(`ConfirmTrade failed: {accepted}`)
end
end)
With one player named Alice, the client prints:
Answering trades: true
The server offers 3 wood for 1 stone
and the server prints:
Alice answered true
On the server:
Network.ConfirmTrade.invoke(player, ...)sends the question to that one player and waits. The player comes first, then the data. It returnstrueand the answer, orfalseand the reason it failed. Withyield = promiseit returns a Promise instead. Passingnilas the player raises an error, as a fire atnildoes.- The server module has no
onfor this function, because the server never answers it.
On the client:
Network.ConfirmTrade.on(handler)connects the one handler. It receives the data with no player in front, since the question always comes from the server. Its return values are the answer. It runs on its own thread, so it may wait, for example for the player to press a button, and the client never times it out. The function'stimeoutstill ends the call on the server.Network.ConfirmTrade.connected()returnstruewhile a handler is connected. It returnsfalsebeforeonand after you call the functiononreturned. A framework can check it at startup, so a question the server may ask never goes unanswered.- The client module has no
invokefor this function, because the client never asks it.
If no handler is connected when the question arrives, the client answers at once and invoke returns false and no handler. The question can only arrive after the client's handshake, which goes out in the first frame after the client requires the module. So a client that connects its handlers right after the require, without waiting, never answers no handler.
When the client's handler raises an error, the client reports a handler failure with no player, whose detail starts with the function's name, as in ConfirmTrade: .... The server's invoke gets the first line of the error as its reason, the same as for a call from a client.
A call from the server fails for the same reasons as a call from a client, with these differences:
departed: the player left before the answer came back, had already left, or failed the handshake. A call to a player who leaves ends at once, not at its timeout.too many calls: 256 calls to this function are already waiting for that one player. Calls to other players still go out.dropped: the call did not fit in what the server may send that player at once (maxOutgoing), so Volt dropped it and reported anoutgoingfailure naming the player.rate limitednever happens, because the client limits nothing.ratemeans nothing on afrom: Serverfunction: the compiler warns if you set it, andNetwork.rateon the server raises an error for its name.
A call to a player whose client has not connected yet waits with the other reliable messages for that player, and goes out right after the handshake. Its timeout counts from the invoke, so ask a new player from onHandshake, as above, rather than from onJoin.
Types
Every value in data and return has a type. The type decides which values are allowed and how many bytes they take.
A range in parentheses narrows a type. Both ends are included: u8(0..8) allows 0 through 8. (10..) and (..10) leave one end open. For a string, a buffer or an array, the range is the length, and one number means an exact length.
| Type | What it holds | Bytes | Example |
|---|---|---|---|
u8, u16, u24, u32, u48, u64 | Whole numbers from 0 up. u8 holds up to 255, u16 up to 65,535, u32 up to 4,294,967,295. u64 stops at 2^53, the largest whole number a Luau number holds exactly. | 1, 2, 3, 4, 6, 8 | u8(0..8) |
i8, i16, i24, i32, i48, i64 | Whole numbers that can be negative. i8 holds -128 to 127. | 1, 2, 3, 4, 6, 8 | i16(-100..100) |
f16, f32, f64 | Numbers with decimals. f16 is the least precise and f64 is a full Luau number. NaN is never allowed. | 2, 4, 8 | f32(0..1) |
q8(min..max), q16(min..max) | A decimal between min and max, rounded to one of 256 or 65,536 evenly spaced steps. The range is required. | 1, 2 | q16(-3.2..3.2) |
boolean | true or false. | 1 bit; eight share a byte | boolean |
string | A string, measured in bytes. | the bytes, plus 1 or 2 for the length | string(0..64), string(8) |
string.utf8 | Text that must be valid UTF-8. The range still counts bytes, not characters, so string.utf8(1..4) holds "日" (3 bytes) but not "日本" (6). The receiver refuses invalid text on every read. | the bytes, plus 1 or 2 for the length | string.utf8(1..4096) |
buffer | A Luau buffer. | the bytes, plus 1 or 2 for the length | buffer(0..1024) |
unknown | Any Luau value. It travels beside the buffer and Volt never checks it. | 1 bit | unknown |
"melee", 2, true | Exactly that one value, called a literal type. The receiver already knows it, so nothing is sent; the sender refuses any other value while writeValidation is on, as it is by default. | none | struct { kind: "melee", damage: u16 } |
Vector3, Vector3<T> | A Vector3, each part sent as T, which is f32 unless you give one. | 12 by default | Vector3<q16(-1024..1024)> (6 bytes) |
Vector2, Vector2<T> | A Vector2. | 8 by default | Vector2<i16> |
CFrame, CFrame<P, R> | A CFrame: the position as three P, the rotation as three R, both f32 by default. | 24 by default | CFrame<f32, q16(-3.2..3.2)> |
AlignedCFrame, AlignedCFrame<P> | A CFrame turned to one of the 24 rotations that line up with the axes, plus a position. | 13 by default | AlignedCFrame |
QuaternionCFrame, QuaternionCFrame<P> | A CFrame with any rotation packed into 4 bytes, which comes back within about 0.28 degrees of the one sent, plus the position as three P. A CFrame with no real rotation, such as one holding NaN, is refused where you fire it, even with writeValidation off. | 16 by default | QuaternionCFrame<q16(-512..512)> (10 bytes) |
UDim2, UDim2<S, O> | A UDim2: each scale sent as S and each offset as O, both f32 unless you give them. | 16 by default | UDim2<q16(0..1), i16> (8 bytes) |
NumberRange, NumberRange<T> | A NumberRange, its Min and Max each sent as T. The receiver refuses one whose Min is above its Max. | 8 by default | NumberRange<u8(0..100)> (2 bytes) |
Rect, Rect<T> | A Rect, its four numbers each sent as T. | 16 by default | Rect<q16(0..1)> (8 bytes) |
Ray, Ray<O, D> | A Ray: the origin as three O and the direction, at whatever length it has, as three D. | 24 by default | Ray<i16(-2048..2048), q16(-512..512)> (12 bytes) |
Region3, Region3<T> | A Region3, sent as its two corners, each as three T, and rebuilt with Region3.new. It comes back with the position and size it had, and never rotated. | 24 by default | Region3<i16(-4096..4096)> (12 bytes) |
Color3 | A color, 0 to 255 per channel. | 3 | Color3 |
BrickColor | A BrickColor. | 2 | BrickColor |
DateTime, DateTimeMillis | A DateTime, to the second or to the millisecond. | 8 | DateTimeMillis |
Instance, Instance(Class) | An instance the receiver can see, of the class if you name one. | none; it travels beside the buffer | Instance(BasePart) |
StreamedInstance(Class) | An instance the receiver may not have streamed in yet. It arrives as nil when it has not. | none; it travels beside the buffer | StreamedInstance(Model) |
AwaitedInstance, AwaitedInstance(Class) | An instance the server names that a player may not have streamed in yet. The player's client holds the message until the instance arrives, so the listener always gets it. See Waiting for an instance. | 4 | AwaitedInstance(Model) |
Enum.Material and every other Enum. name | An item of that one Roblox enum. | 2 | Enum.KeyCode |
EnumItem | An item of any Roblox enum. The enum's name travels with it. | 4 or more | EnumItem |
A string, buffer or array with a range stores its length in the smallest number that holds the range, and one with an exact length stores none. With no range, the length takes 2 bytes and the most allowed is 65,535.
A range on a type argument bounds every number that argument carries, so Region3<i16(-4096..4096)> refuses a region with a corner more than 4,096 studs from the origin along any axis. A Rect or a Region3 whose numbers are a float with an open end, such as the default f32, also refuses an infinite number, since two infinite corners give it a size of NaN: the sender refuses it as expected Rect or expected Region3, and the receiver as out of range. A Region3 infinite in both directions along one axis already has a NaN center in Roblox, so the sender refuses it as expected f32 instead, naming that corner's number, such as Min.X.
Types can be combined:
| Form | What it holds | Example |
|---|---|---|
T? | A T, or nil. Costs 1 bit. | u8? |
T[], T[min..max], T[n] | An array of T. T[n] is exactly n long. | u8[0..16] |
{ [K]: V }, { [K]: V }(min..max) | A table from keys to values. A key can be any type in the first table except unknown, or a plain enum. | { [u8]: boolean }(0..64) |
set<T>, set<T>(min..max) | A table { [T]: true }. | set<u8>(0..64) |
struct { a: T, b: U } | A table with these fields. | struct { name: string(1..16), level: u8 } |
enum { A, B } | One of the strings "A" and "B". | enum { Red, Blue } |
enum "tag" { A { ... }, B { ... } } | A table whose tag field names the variant, plus that variant's fields, such as { kind = "Sword", damage = 10 }. | enum "kind" { Sword { damage: u8 }, Bow { range: u16 } } |
A | B | A value of either type. | u8 | string(0..16) |
struct { ..Name, c: T } | A struct with Name's fields copied in (Sharing fields between structs). | struct { ..Stack, slot: u8 } |
| a name | A named type, declared below. | Stack |
| a name with arguments | A generic type with its parameters filled in (Generic types). | Pair<u8, u8> |
An array of booleans is packed into bits: boolean[8] takes one byte. A map or a set refuses a duplicate key.
Volt picks a member of A | B by the value's Luau type, so the members must be told apart that way. Two number types, two strings, two buffers, two tables (structs, arrays, maps, sets and tagged enums all count) or two instances cannot share a union, and the compiler says so. To choose between two structs, use a tagged enum. nil is never a member; use ? instead. A literal counts as its Luau type, so u8 | "none" works, while "on" | "off" is two strings and is written enum { on, off } instead.
Give a type a name to use it in several places:
type Reference = string(1..64)
struct Stack { item: string(1..32), quantity: u16(1..999) }
enum Team { Red, Blue }
export struct Save { version: u16, stacks: Stack[0..256] }
type, struct and enum declare a name the whole schema can use. A named type also becomes a Luau type in the generated modules. export in front adds a write and a read for that type to the module (see More tools).
@private in front of a type, struct or enum keeps its Luau type to the generated modules: they still use it in their own signatures, but your scripts cannot name it. It changes nothing that is sent. An exported type cannot be private, since its write and read are for your scripts.
@private type Line = string.utf8(0..16384)
A namespace groups messages and types:
namespace Combat {
event Hit {
from: Client,
type: Reliable,
call: SingleSync,
data: (target: u16, damage: u8),
}
}
The event is then Network.Combat.Hit, and the client fires it with Network.Combat.Hit.fire(12, 30). Outside the namespace a name inside it is written Combat.Name. A name declared at the top of the file can be used inside every namespace. A type and a message cannot share a name.
Some names belong to the module itself, so no message or type at the top of the schema can take them: budget, events, exports, flush, functions, hooks, isBot, onFailure, onHandshake, onJoin, onLeave, rate, serverTime, stats, traffic, version and Volt. With option casing set to pascal or snake, they are spelled that way instead, such as Stats or on_failure. The compiler refuses one with V4001, as in "stats" is a member of the generated API and cannot be a top-level name; inside a namespace they are free. A named type also cannot take the name of a type the modules use, such as Player, Vector3 or ServerEvent, which is V4002.
Sharing fields between structs
..Name in a struct stands for the fields of the struct Name, in the order Name declares them, at the place you write it. This is called a spread. Add this to Game.volt:
-- The fields every character has
struct Base { id: u16, name: string(0..16) }
-- Base's two fields, then one of its own
struct Unit { ..Base, team: u8 }
-- A spread also works in a tagged enum's variant
enum Hit "kind" { Melee { ..Base, damage: u16 }, Miss }
event UnitSpawned {
from: Server,
type: Reliable,
call: SingleAsync,
data: Unit,
}
On the server:
Network.UnitSpawned.fireAll({ id = 7, name = "Scout", team = 1 })
On the client:
Network.UnitSpawned.on(function(unit)
print(`{unit.name} joined team {unit.team}`)
end)
Each client prints Scout joined team 1.
Unitabove is the struct{ id: u16, name: string(0..16), team: u8 }in every way: the same bytes, the same checks, the same Luau type and the same schema hash. A spread costs nothing on the wire.- A spread copies fields, so
UnitandBasestay separate types. ChangingBasechanges every struct that spreads it. - The name after
..must be a struct declaration, writtenstruct Name { ... }ortype Name = struct { ... }. It can sit in a namespace, as in..Combat.Stats, and a generic one takes its arguments, as in..Pair<u8, u8>(Generic types).
A field name that comes twice once the spreads are copied in is V3020, because a spread never overrides a field. Rename one of the two, or take it out of the struct that writes it:
Game.volt:5:23: error V3020: field "id" comes twice in Unit, from ..Base and as written
5 | struct Unit { ..Base, id: u8 }
| ^^^^^^
V3019 means the name cannot be spread. It reads a spread takes a struct, and "Id" is a primitive for a name that is no struct, a type parameter among them, so spread a struct declaration instead. It reads "A1" spreads itself through "B1" when a spread leads back to its own struct, so take one of the spreads out of the loop.
A parameter pack cannot hold a spread: data: (..Base, team: u8) is V2001, a parameter pack cannot spread a struct. Write out the values in the pack, or make data a struct that spreads Base.
Generic types
A type, struct or enum can take type parameters in angle brackets after its name. Each use of it fills them in, so one declaration serves many types. Add this to Game.volt:
-- A and B are filled in wherever Pair is used
struct Pair<A, B> { first: A, second: B }
-- A type or an enum takes parameters the same way
type Maybe<T> = T?
event Moved {
from: Client,
type: Reliable,
call: SingleSync,
data: (path: Pair<u8, u8>[0..32], target: Maybe<Pair<u8, u8>>),
}
On the client:
Network.Moved.fire({ { first = 1, second = 2 }, { first = 3, second = 4 } }, nil)
On the server:
Network.Moved.on(function(player, path, target)
print(`{player.Name} moved through {#path} points`)
end)
With one player named Alice, the server prints Alice moved through 2 points.
- Every use passes one argument per parameter, and an argument can be any type:
Pair<u8, u8>,Pair<Stack, string(0..8)>,Maybe<Pair<u8, u8>>. - The compiler makes each different set of arguments a named type of its own, so
Pair<u8, u8>costs exactly what a namedstruct { first: u8, second: u8 }would, on the wire and at run time. Using it twice shares one writer and one reader. A generic that nothing uses generates nothing. - The generated modules write it as one Luau type,
export type Pair<A, B> = { first: A, second: B }, and annotatePair<u8, u8>asPair<number, number>.@privateworks on a generic as on any named type.
A generic cannot be exported. export gives a type a write and a read (Exported serializers), which need one encoding, and a generic has a different encoding for each set of arguments. So the compiler refuses it with V2013:
Game.volt:4:19: error V2013: an exported type cannot take type parameters; export an instantiation, as export type Scores = Pair<u16, u16>
4 | export struct Pair<A, B> { first: A, second: B }
| ^
Do what the message says: keep the generic as it is, and export a name for the one set of arguments you want to save or send. An instantiation is the generic with its arguments filled in. Add this to Game.volt:
export type Scores = Pair<u16, u16>
Then, on either side:
local packet, side = Network.Scores.write({ first = 10, second = 20 })
local scores = Network.Scores.read(packet, side)
print(scores.first, scores.second)
This prints 10 20, and packet is a 4-byte buffer.
The other errors you can meet:
V3007: the wrong number of arguments, as in"Pair" takes 2 type arguments, got 1, or arguments on a type that takes none, as in"Plain" takes no type arguments, got 1. Pass one argument per parameter, and none to a type with no parameters.V2002: a parameter named twice, as instruct Pair<A, A>. Give each its own name.V4002: a parameter with the same name as a named type of the schema, as in"Stack" is the label of a named type of the schema and cannot name a type parameter, or as a type every generated module uses. Rename the parameter.V3021: a generic that contains itself with other arguments, asstruct List<T> { value: T, next: List<T[]>? }does. It would need a new type at every level, so a generic may contain itself only with its own parameters, as innext: List<T>?.V2001onevent Moved<T>: an event, a function or a namespace takes no parameters. Use a generic type in itsdata.V3016on@dictionary type Name<T>: a@dictionarytype takes no parameters, since a schema has one list of strings. Remove them.
Recursive types
A named type may contain itself, which is how you send a tree, a chain or a folder of folders. Add this to Game.volt:
-- A tree of named parts: each has up to 3 kids, at most 4 levels deep
@depth(4) struct Tree { name: string(0..8), kids: Tree[0..3] }
event Layout {
from: Server,
type: Reliable,
call: SingleAsync,
data: Tree,
}
On the server:
Network.Layout.fireAll({
name = "root",
kids = {
{ name = "a", kids = {} },
{ name = "b", kids = { { name = "c", kids = {} } } },
},
})
On the client:
Network.Layout.on(function(tree)
print(`{tree.name} has {#tree.kids} kids`)
end)
Each client prints root has 2 kids.
@depth(n) goes in front of the declaration and sets the deepest level a value of that type may sit at. A Tree in a message is at level 1, the Trees in its kids are at level 2, and so on, so under @depth(4) a Tree at level 4 must have empty kids. n is a whole number from 1 to 1,000. A recursive type with no @depth stops at 16. It also goes in front of export, as in @depth(4) export struct Tree { ... }, and on a generic it applies to every instantiation.
Types can also contain each other. Every named type on the way round counts as one level:
@depth(4) struct Folder { entries: Entry[0..3] }
@depth(4) enum Entry "kind" { File { size: u16 }, Sub { folder: Folder } }
A Folder in a message is level 1, its Entry is level 2, the Folder inside that is level 3 and its Entry is level 4. Each type keeps its own bound, so when they differ, the tightest is the one a value meets first.
A value past the bound never gets through:
- On a write, the fire or the invoke raises an error and nothing is sent, even with
writeValidationoff. The error readsTree: nested deeper than 4. A Luau table that holds itself is refused the same way. - On a read, the receiver refuses it before it reads a byte of that level. That is a
decodefailure, and the rest of the packet is dropped, so a cheating player cannot nest past the bound. The default handler warnsVolt: decode failure from Alice: Build: Tree: nested deeper than 4.
The compiler works out the largest size a recursive type can reach, the deepest and widest value its bounds and ranges allow, and holds it to the same limits as any other type. A tree that branches grows fast. Tree above triples at each level:
@depth | Largest Tree, in bytes |
|---|---|
| 4 | 400 |
| 5 | 1,210 |
| 6 | 3,640 |
| 7 | 10,930 |
| 16, the default | 215,233,600 |
So a tree a client sends usually needs a small @depth. What a client sends must fit in maxPacket, 8,192 bytes by default, and with no @depth a client's Tree event is refused with V3012:
Game.volt:5:7: error V3012: event Build can reach 215233601 bytes, over maxPacket 8192 with the 5-byte handshake
5 | event Build {
| ^^^^^
Lower @depth until it fits, here to 6 or less, or narrow the array's range. The same check covers a from: Both event and a function's data. An unreliable event must fit in unreliableBudget, so @depth(5) on this Tree is V3010, event A can reach 1211 bytes, over the unreliable budget of 900, and @depth(4) fits. The compiler sets no such limit on a from: Server reliable event or a function's return, so a deep tree the server sends compiles at the default of 16, and maxOutgoing is what limits it as the game runs. A type that does not branch stays small: struct Chain { value: u8, next: Chain? } fits in a client's event at 16 levels with no @depth. A recursive value has no byte limit of its own beyond these.
A recursive type must have a value that ends. One where every way through leads back to itself could never be finished, so the compiler refuses it with V3003:
Game.volt:4:8: error V3003: "Chain" has no finite value: every way through it leads back to it; an optional, a collection that may be empty or another variant on the way ends it
4 | struct Chain { next: Chain }
| ^^^^^
The fix is in the message. Make the field optional, as in next: Chain?, start a collection's range at 0, as in kids: Pairs[0..2] instead of kids: Pairs[2], or add a variant or a union member that does not lead back.
The other errors you can meet:
V3009: a union that is one of its own members, as intype Node = u8 | Node. That member takes every class the others do, so Volt could not pick between them. Put the loop inside a struct:type Node = u8 | Boxwithstruct Box { next: Node }.V3018:@depthon a type that does not contain itself, as in"Flat" is not recursive, so @depth changes nothing. Remove it.V3005: a@depthbelow 1 or above 1,000. Use a number in that range.V2005:@depthwith no number. Write@depth(4).V3015: a@deltaevent whosedatareaches a recursive type, as in@delta event Scene cannot carry Tree, which is recursive. Remove@deltafrom the event.
Waiting for an instance
With StreamingEnabled, a player's client has only the parts of the world near them, so an Instance the server sends can be one the client does not have yet. AwaitedInstance waits for it: the client holds the message until the instance has streamed in, then runs the listener with it. Add this to Game.volt:
-- The server tells every player a boss has spawned, which a player far away may not have streamed in yet
event BossSpawned {
from: Server,
type: Reliable,
call: SingleAsync,
timeout: 5,
data: (boss: AwaitedInstance(Model), health: u16),
}
On the server:
Network.BossSpawned.fireAll(workspace.Dragon, 500)
On the client:
Network.BossSpawned.on(function(boss, health)
print(`{boss.Name} spawned with {health} health`)
end)
Each client prints Dragon spawned with 500 health once the Dragon model has streamed in for that player.
- The listener always gets the instance, as the class the schema names, never
nil. timeoutis how many seconds a message waits: 5 here, and thetimeoutoption, 10 by default, for an event that does not set one. A message whose instance has not arrived by then is dropped, so its listener never runs, and the client reports aresolvefailure naming the event. The default handler warnsVolt: resolve failure: BossSpawned: instance 1 did not arrive within 5 seconds. An instance the server destroys, or keeps where players never get it, such as in ServerStorage, never arrives.- A waiting message holds back only later messages that name an instance it still waits for, so the messages about one instance arrive in the order they were fired. Every other message goes ahead of it, so a boss far from a player never delays the rest of that player's messages. Messages waiting for different instances arrive in the order their instances do. This is the one exception to reliable messages arriving in the order they were fired.
- An instance that arrives as another class, such as a Part where the event says
Model, is adecodefailure, and the message is dropped. - Each instance costs 4 bytes: an id the server gives it the first time a message names it, and keeps for as long as the instance exists. The server keeps one ObjectValue per id in a folder named
Referencesbeside the schema's remotes, and each goes when its instance does. - Only the server sends one.
AwaitedInstancecan only be in thedataof afrom: Serverevent that isReliableorUnreliable, and the compiler refuses it anywhere else withV3022. It can be optional, in an array or in a struct the event carries, but not in an exported type, a map key or a set element. Atimeouton an event whosedataholds noAwaitedInstancedoes nothing, and the compiler warns about it. - A bot gets every instance at once, since it lives on the server.
Choosing how a message travels
Events or functions
Use an event when the sender does not need an answer: a player pressed a button, the round started, a door opened. Events can go either way, or both ways with from: Both.
Use a function when one side needs the other's answer before going on: a player buying an item or loading an inventory, or the server asking a player to accept a trade. A function goes from a client to the server, or, with from: Server, from the server to one player (When the server asks a player).
Reliable or unreliable
A reliable message always arrives, exactly once, in the order it was fired. Use it for almost everything. The one exception to the order is a message waiting for an instance the player has not streamed in (Waiting for an instance).
An unreliable message can be lost, and unreliable messages are not kept in order. Use it for something sent many times a second where the next message replaces the last, such as a position. Each unreliable message must fit in 900 bytes (unreliableBudget in Options), and the compiler refuses one that could be larger, or that has no largest size at all, such as one with a string that has no range.
Unreliable, in order
Because unreliable messages are not kept in order, an old message can arrive after a newer one and undo it: a player's aim from two frames ago lands after the aim from the last frame. type: OrderedUnreliable stops that. Each message carries a count, and the side that hears it drops any message that is not newer than the last one it heard of that event from that sender. Add this to Game.volt:
-- Where a player aims, sent every frame; an older aim that arrives late is dropped
event Aim {
from: Client,
type: OrderedUnreliable,
call: SingleSync,
data: (yaw: q16(-3.2..3.2), pitch: q16(-1.6..1.6)),
}
Your scripts use it like any event. On the client:
Network.Aim.fire(1.5, 0.25)
On the server:
-- Runs for each aim newer than the last one this player sent
Network.Aim.on(function(player, yaw, pitch)
print(string.format("%s aims %.2f, %.2f", player.Name, yaw, pitch))
end)
With one player named Alice, the server prints Alice aims 1.50, 0.25.
- It is still unreliable. A message can be lost, and Volt never waits for one or sends it again. A newer message that arrives first makes the older one too old to use.
- The count takes 2 bytes per message, inside the 900-byte limit.
- The server keeps a count per player, and the client one per event. When the server sends to several players at once, such as with
fireAll, each player gets their own next count. - A message dropped for being old is counted in
stats()as received, and it is not a failure. It still counts toward the event'srate, so a player cannot get past the limit by sending old messages again. - The count runs from 1 to 65,535 and then wraps to 0. A side that misses 32,768 or more messages of one event in a row, over nine minutes of them at 60 a second, drops the next ones until the count passes the last one it heard.
Channels
Reliable messages from one side arrive in the order they were fired, one after another in a single line. A channel is a second line of reliable messages. Declare it once, then name it in the reliable events that use it:
-- Chat has its own line, so a burst of chat never crowds out the game's other messages
channel Social
event Chat {
from: Both,
type: Reliable,
call: ManySync,
channel: Social,
data: string(0..200),
}
Your scripts do not change. On the server:
-- Pass every chat line on to every player
Network.Chat.on(function(player, text)
Network.Chat.fireAll(`{player.Name}: {text}`)
end)
On the client:
Network.Chat.on(function(text)
print(text)
end)
Network.Chat.fire("hello")
With one player named Alice, the client prints Alice: hello.
What a channel changes:
- Messages on a channel arrive in the order they were fired on that channel. Messages on the default line, which every event without
channeland every function uses, arrive in the order they were fired on it. Between two lines nothing is promised, so aChatcan arrive before aPongfired just before it. - Each line has its own frame. A frame that is full on one line, past
maxPacketon the client ormaxOutgoingon the server, drops messages on that line only. A message that fails its checks drops the rest of its own packet only, and a sync listener that waits holds up only its own packet. - A function's call and its answer always use the default line. A handler's fires at its caller on the default line still arrive before its answer, as in Use it in your scripts; fires on a channel can arrive after it.
- A channel adds no remote. Its messages ride the scope's one
ReliableRemoteEvent, and Roblox sends all of one player's reliable messages over one connection, so a channel cannot get past a message the engine is still resending. - In a schema that declares a channel, every packet starts with one byte naming its line. Each packet, reliable or unreliable, costs one more byte, and an unreliable message must fit in one byte less, 899 bytes by default.
- Every line's packets count toward
maxPacketsPerSecond. A client that sends on a channel every frame sends up to 60 more packets a second, so raise the option in a schema whose client does. - Only a
Reliableevent can name a channel, and a schema declares at most 255. A channel can be declared inside a namespace, and an event finds it by name as it finds a type.
Listener modes
call picks how listeners run.
| Mode | Listeners | Where each listener runs | Use it when |
|---|---|---|---|
SingleSync | one | right away, inside the loop that reads the packet | one system owns the event and its listener never waits, such as hit registration, where the first packet to arrive is handled first |
ManySync | any number, called in the order they connected | right away, inside the loop | several systems watch the event and none of them waits |
SingleAsync | one | on a new thread for each message | one system owns the event and its listener may wait |
ManyAsync | any number | on a new thread for each listener and message | several systems watch the event and some of them wait |
Polling | none | your code reads the queue with iter | you want to handle the messages at a time you pick, such as once a frame |
A sync listener must not wait: no task.wait, no WaitForChild, no DataStore call. If one does, Volt reports a listener failure naming the event, and the rest of that packet waits until the listener resumes. The fix is in the listener, or in making the event Async. An error in a sync listener is reported the same way, and the packet goes on.
An async listener may wait. Each message costs one new thread per listener, and an error goes to the Output like any other thread's.
A function's handler always runs on its own thread.
Sending less
Two attributes cut the bytes of messages the server sends often. Each goes in front of a declaration, and your scripts call the same functions as before.
Only the fields that changed
@delta in front of an event makes the server send each player only the fields of the event's struct that changed since the last value it sent that player. Add this to Game.volt:
-- A player's vitals: sent whole the first time, then only the fields that changed
struct Vitals {
health: u8,
stamina: u8(0..100),
title: string(0..16),
}
@delta event Status {
from: Server,
type: Reliable,
call: SingleAsync,
data: Vitals,
}
The server sends each player their vitals when they join, and again whenever they change:
-- Each player's vitals, as the server last set them
local vitals = {}
-- A player who joins is sent their vitals whole
Network.onJoin(function(player)
vitals[player] = { health = 100, stamina = 50, title = "Scout" }
Network.Status.fire(player, vitals[player])
end)
Network.onLeave(function(player)
vitals[player] = nil
end)
-- A hit changes one field, and only that field is sent
local function hurt(player, damage)
local status = vitals[player]
status.health -= damage
Network.Status.fire(player, status)
end
The client listens as it would to any event:
Network.Status.on(function(status)
print(`health {status.health}, stamina {status.stamina}, {status.title}`)
end)
With one player named Alice, after hurt(alice, 10) the client prints:
health 100, stamina 50, Scout
health 90, stamina 50, Scout
The first message is 10 bytes. The second is 3: the event's id, one byte saying which fields follow, and the new health. Without @delta each is 9 bytes. A fire whose value has not changed costs 2 bytes and still reaches the listener, so sending a value again to be sure always lands.
How it works:
- The server keeps a copy of the value it last sent each player through each
@deltaevent. Each fire compares the value's fields with that copy and sends only the fields that differ. A table inside a field is compared all the way down, so a struct inside the value that you change in place counts as changed, and all of it is sent. - The first fire to a player sends every field, since there is nothing to compare with. Send that whole value from
onJoin, as above. Volt never sends a player who joins anything on its own: it keeps no current value of any event, and it replays no message fired before they joined. fire,fireAll,fireList,fireSetandfireExceptall work, and each player is sent the fields that changed for them.- The listener always receives the whole struct. Volt fills each field the message left out from the value it delivered last time.
- That struct is frozen with
table.freeze. Read it and never write into it, or into a table inside it, since the fields that did not change are the same tables as last time. Copy it withtable.clonewhen your code needs a version of its own. - When a message to a player is dropped because their frame went past
maxOutgoing(anoutgoingfailure), the server forgets every@deltavalue it sent them, so the next fire to them is whole again. A fire that raises an error, such as one with a value its type does not allow, sends nothing and changes nothing. - Which fields follow takes one bit per field: one byte for up to 8 fields and two for up to 16.
- Each fire copies the value once and compares it once with each copy its players hold. Players whose last value came from the same fire hold one copy, and players who need the same fields share one write, so
fireAllafterfireAllcompares and writes once. That is cheap for a small struct. A large struct where a few fields change often is cheaper as several@deltaevents. - A bot is sent
@deltamessages as a player is, and a@deltaevent can ride a channel.
The compiler refuses @delta with V3015 on an event that is not from: Server, that is not Reliable, or whose data is not one struct of 1 to 32 fields. It also refuses a struct with an unknown, a StreamedInstance or an AwaitedInstance anywhere inside it: the first two can arrive as nil and the last can make the message wait, and either way the client could not fill in the fields a later message leaves out correctly. It refuses a struct that reaches a recursive type too, since the server compares and copies each value all the way down before it writes it, and a table that holds itself would run that walk into Luau's call limit. A @delta event Score whose data is u16 gives:
Game.volt:11:8: error V3015: @delta event Score must carry one struct; it carries u16
11 | data: u16,
| ^^^
Strings sent as ids
@dictionary in front of a string type makes each of its values travel as a 2-byte id. The server sends each player each string once, just before the first packet that uses it, and from then on only its id. Add this to Game.volt:
-- Item names repeat in many messages, so each one is sent once and then as a 2-byte id
@dictionary type ItemName = string(1..32)
event Picked {
from: Server,
type: Reliable,
call: ManySync,
data: (item: ItemName, count: u8),
}
Your scripts use strings as before. On the server:
Network.Picked.fire(player, "Iron Sword", 1)
Network.Picked.fire(player, "Iron Sword", 2)
On the client:
Network.Picked.on(function(item, count)
print(`picked {count} {item}`)
end)
The client prints picked 1 Iron Sword, then picked 2 Iron Sword. The first fire costs that player 20 bytes: 16 to send the string Iron Sword and 4 for the message. The second costs 4. Without @dictionary each is 13 bytes, so the dictionary pays for itself from the second time a player is sent a string.
- The strings form one list per schema, kept by the server and shared by every
@dictionarytype in the schema. It grows as messages name new strings, and it never forgets one. - A player who joins is sent every string so far ahead of everything else, the messages held for them until their handshake included. Each player is sent each string exactly once. A bot is sent them as a player is.
- The list holds at most 4,096 strings. A fire that would add one more raises an error,
Picked.item: dictionary full, and sends nothing. Use@dictionaryfor a set of names that stays small, such as items, abilities or maps, and never for text players type or anything else whose values have no end. - The type must be a
stringor astring.utf8whose range allows at most 255 bytes, and the compiler refuses any other withV3016. Astring.utf8value is still checked as UTF-8 before it gets an id. - Only the server sends an id, on the default line of reliable messages. A
@dictionarytype can be in thedataof afrom: Server,Reliableevent with nochannel, and in thereturnof a function a player calls, including inside a struct, an array, a map or an optional. The compiler refuses it anywhere else withV3017: in an event a client fires, anUnreliableorOrderedUnreliableevent, an event on a channel, a function'sdata, thereturnof afrom: Serverfunction, or an exported type. Afrom: ClienteventUsewhosedatais anItemNamegives:
Game.volt:18:8: error V3017: @dictionary type ItemName travels only on the server's default reliable stream; Use is from: Client
18 | data: ItemName,
| ^^^^^^^^
Safety defaults
Volt checks everything the server receives, and these checks cannot be turned off.
Every value is checked
The server reads a packet from a player only after checking that it is a buffer, that it is at most 8,192 bytes (maxPacket), that the player has sent at most 240 packets in the last second (maxPacketsPerSecond), and, in a schema with a channel, that it starts with a byte naming the default line or a channel. Then it checks every value in every message against the schema: each number in its range and never NaN, each length within its bounds, each enum value known, each instance present and of its class, no key twice in a map or a set.
The sending side checks your values too, before anything is written, so a bad value raises an error where you fire it. option writeValidation = false removes those sending checks for speed. The receiving checks stay.
Rate limits
Each event a client fires is limited to 120 messages per second per player, and each function a client calls to 60 calls per second per player. Change them in the schema:
event Ping {
from: Client,
type: Reliable,
call: SingleAsync,
data: u8,
rate: 30,
}
rate: unlimited turns the limit off for one message. option rate = 200 and option functionRate = 30 change the defaults for the whole schema.
The server can also change a limit while the game runs. The second number is how many a player may save up, and it defaults to the first:
-- Let each player send 30 Pings a second, and save up at most 60
Network.rate("Ping", 30, 60)
On the client, Network.rate does nothing. A message over its rate is read and then dropped, and the rest of its packet goes on. A function call over its rate is answered with the reason rate limited.
What happens to a bad packet
A message that fails a check is dropped along with the rest of its packet, because Volt can no longer tell where the next message starts. Your listener never sees it. Volt counts it and reports a decode failure.
The schema-mismatch kick
Each module carries its schema's hash. When a client starts, the first thing it sends is that hash, a step called the handshake. If the hash differs from the server's, the server kicks the player with both hashes in the message. A client built from a different schema would read every message wrongly, so Volt stops it before it reads anything. This usually means one side's module is stale: compile again and publish both.
The server reads nothing from a player until their handshake arrives. Reliable messages it fires at them before then are held and sent, in order, right after the handshake. Unreliable ones are dropped.
Failure kinds
Every problem Volt finds is a failure of one of eleven kinds. Each one is counted, then handed to the failure handler.
| Kind | Cause | Scope | What happens | Default handling |
|---|---|---|---|---|
packet | A packet that is not a buffer or is over maxPacket; one sent before the handshake or by a player who has left; a message id cut short or naming no message; a second handshake; in a schema with a channel, a packet with no channel byte or one naming no channel, as in unknown channel 5, on either side; on a client with stamp, a server packet shorter than its stamp | packet | the packet is dropped, or the rest of it for a bad id | warn |
rate | Over maxPacketsPerSecond, every channel's packets counted together, or over an event's or a function's rate, which an OrderedUnreliable message dropped for being old still counts toward | packet for the packet rate, message for a message's rate | the packet is dropped, or the message is skipped | warn |
handshake | The client's schema hash differs from the server's | packet | the packet is dropped | kick, with both hashes in the message; a warning for a bot |
decode | Any other check while reading a message, including, on the client, an AwaitedInstance that arrives as another class, a @delta message that leaves out fields when the client has no earlier value to fill them from, a dictionary id the client was never sent a string for, and a dictionary message the client cannot take | message | the rest of the packet is dropped, or for an instance that arrived late, that message | warn |
resolve | On the client, an AwaitedInstance that did not arrive within its event's timeout | message | that message is dropped, and its listener never runs | warn |
listener | A sync listener raised an error or waited | message | the packet goes on | warn |
handler | A function's handler raised an error, or returned a value its return type does not allow, on the side that answers; on the client the player is nil | message | the caller gets the error as its reason | warn |
outgoing | A player's outgoing data for one send went past maxOutgoing; on the client, the reliable data for one send went past maxPacket. Each channel's send counts on its own. A call finds it at its own invoke, on either side | packet | the message that went past it is dropped, and on the server every @delta value sent to that player is forgotten, so the next fire to them is whole | warn |
queue | A queue was full | message | the oldest message is dropped | warn, once per event |
departed | A fire or a call at a player who has left or whose handshake failed; an answer to a caller who has left | packet | the message is dropped | nothing |
budget | A scope with a budget dropped unreliable messages to a player at one send, as in over the budget, unreliable messages dropped: 3 | packet | those messages are dropped unsent; reliable messages never are | nothing |
An OrderedUnreliable message dropped for being older than the last one heard is not a failure, since unreliable messages are expected to arrive out of order.
The default handler's warning reads Volt: <kind> failure from <Name>: <detail>, or from a bot for a bot, and Volt: <kind> failure: <detail> on the client. It warns at most once a minute per player and kind, so an attack cannot flood the Output, while the counts stay exact.
The detail of a message-scoped failure (a rate on a message, decode, resolve, listener, handler and queue) starts with the message's name, a colon and a space, exactly once, as in Ping: over 120 a second. A message in a namespace gives its full name, such as Combat.Hit: .... The message that carries dictionary strings is named Volt.dictionary, as in Volt.dictionary: out of order, a name none of your messages can have. The detail of a packet-scoped failure names no message, as in over 240 packets a second.
Handling failures yourself
Network.onFailure(handler) replaces the handler for every kind and returns the one it replaced, which the first time is Volt's default. Call that default for the kinds you leave to Volt:
local Volt = require(ReplicatedStorage.Packages.Volt)
local default: Volt.Failure
default = Network.onFailure(function(player, kind, detail)
if kind == "rate" then
return -- this game ignores rate failures
end
default(player, kind, detail)
end)
The handler receives the player, the kind and the detail. On the client the player is nil. The handler must not wait. If it raises an error, Volt warns Volt: the failure handler raised: ... and goes on.
Counters
Network.stats() returns the counts for everything this module has sent and received, and on the server Network.stats(player) returns one player's share. Each holds packetsIn, bytesIn, messagesIn, packetsOut, bytesOut, messagesOut, rejected (messages a hook dropped) and failures, a count per kind. A kind appears in failures the first time it happens, so read it as stats.failures.rate or 0. The tables update as the game runs. A player's counts go with them when they leave, and after that Network.stats(player) reads all zeros.
More tools
Hooks
A hook runs before a message is sent or after one is received, and returning false drops the message. On the server:
-- Drop any Ping whose value is 0 before the listener sees it
Network.hooks.afterReceive("Ping", function(player, value)
return value ~= 0
end)
-- Print every Pong just before it is sent
Network.hooks.beforeSend("Pong", function(target, value)
print(`sending Pong {value}`)
return true
end)
beforeSend(name, hook)takes an event this side fires. The hook receives the target and the data. The target is the player forfire, the list or set forfireListandfireSet, andnilforfireAll,fireExceptand every fire on the client.afterReceive(name, hook)takes an event or function this side receives. The hook runs after the checks and the rate limit, before the queue, the listener or the handler, and receives the player (nilon the client) and the data. Withnilas the name, the hook covers every message and runs before the message's own hook.- Each slot holds one hook. Registering again replaces it, and passing
nilclears it. - A dropped message is counted in
stats().rejected, and instats(player).rejectedwhen the hook had a player. It is not a failure. - A function call a hook drops gets no answer, so its caller waits until the timeout.
- A hook must not wait.
Exported serializers
export in front of a type gives the module a write and a read for it. A serializer turns a value into bytes and back, which is how you can keep a value in a DataStore or send it some other way. Add this to Game.volt:
-- A player's progress, turned into a buffer and back
export struct Save {
coins: u32,
level: u16,
}
Then, on either side:
local packet, side = Network.Save.write({ coins = 250, level = 3 })
local save = Network.Save.read(packet, side)
print(save.coins, save.level)
This prints 250 3. packet is a 6-byte buffer. side holds the instances and unknown values that travel beside the buffer, and it is nil here because Save has none. write refuses a bad value the way a fire does, and read checks every byte the way a received message is checked, raising an error on anything wrong. Neither one sends anything.
Player callbacks
The server module tells you about each player:
-- Runs once Volt has set up a player, and at once for every player already set up
Network.onJoin(function(player)
print(`{player.Name} joined`)
end)
-- Runs once the player's client has connected and what was held for them has gone out
Network.onHandshake(function(player)
Network.Pong.fire(player, 0)
end)
-- Runs just before Volt forgets the player
Network.onLeave(function(player)
local stats = Network.stats(player)
print(`{player.Name} sent {stats.messagesIn} messages`)
end)
Each one returns a function that disconnects it, and each callback runs on its own thread. onHandshake runs at the end of the first flush after the player's handshake is accepted, once that flush has sent the messages held for them. A fire inside it goes out with the next flush, so the player hears it after the held messages. A player who leaves before that flush never reaches onHandshake.
Network.traffic(player) returns two numbers: the bytes sent to that player in the last second, across every Volt schema on the server (scripts inside an Actor count their own), and the bytes written for them that have not been sent yet, which include what a budget is holding back.
Looking up messages by name
Network.events, Network.functions and Network.exports map each full name to the same entry the module has: Network.events["Combat.Hit"] is Network.Combat.Hit, and Network.exports["Save"] is Network.Save. A name that does not exist gives nil. This lets a framework connect messages by name.
The types module also exports a type for each kind of entry, so a framework can name the entries it holds. ServerEvent<A...> is an event the server fires, ServerListener<A...> and ServerPolling<A...> one it hears, ServerFunction<A..., R...> a function it answers, and ServerInvoke<A..., R...> or, with yield = promise, ServerPromise<A...> one it calls. The client's are ClientEvent, ClientListener, ClientPolling, ClientFunction, ClientPromise and ClientHandler, and an exported type's entry is Exported<T>. A... stands for the data's types and R... for the return's. A schema with no typesOutput exports each side's types from its own module instead.
When the server sent a message
option stamp = true makes the server write its clock, the workspace:GetServerTimeNow() of the frame that sends, at the start of every packet it sends. The client module gains Network.serverTime(), which returns that time for the message being handled. Add the option to Game.volt and compile again:
option stamp = true
Then, on the client:
Network.Pong.on(function(value)
local age = workspace:GetServerTimeNow() - Network.serverTime()
print(`Pong {value} left the server {math.round(age * 1000)} ms ago`)
end)
This prints a line such as Pong 8 left the server 50 ms ago.
serverTime()gives the time of the packet that held the message: inside a sync listener, an async listener before it first waits, a hook after a receive, and right after aninvokereturns.- A message that waited in a queue keeps its packet's time, inside
iterand when the firstontakes the queue. Anywhere elseserverTime()gives the time of the last packet, and 0 before the first. - The time is when the server's frame sent the packet. A message held for a player until their handshake carries the time it was sent, not the time it was fired.
- Each server packet costs 8 more bytes, and an unreliable message the server sends must fit in 892 bytes, 8 less than
unreliableBudget. A player's packets carry no time, since the server never trusts a player's clock. - The server module has no
serverTime, and the client module has it only when the option is on. Inpascalandsnakecasing it isServerTimeandserver_time, and in any schema, stamped or not, the compiler refuses a top-level declaration with the name in the schema's casing.
Capping what a player is sent
Network.budget(bytesPerSecond) makes one schema give way to a player once that player has been sent that many bytes in the last second. Past that point, its reliable messages to the player wait and its unreliable messages to them are dropped. Call it on the server, at any time while the game runs:
-- This schema gives way once a player has been sent 64 KB in the last second
Network.budget(64 * 1024)
-- This schema no longer gives way
Network.budget(nil)
Your fires do not change. Say that budget is set and Alice has been sent 70 KB in the last second. A reliable Network.Pong.fire(alice, 8) waits, and reaches her in the order it was fired. An unreliable fire at her is dropped, and the failure handler hears one budget failure for that send.
- It exists on the server module alone. The client module has no
budget. - It is one setting per scope, and calling it again replaces the last value. No schema option or attribute sets it, so a game sets it while it runs through that scope's own
Network. - It reads the first number
Network.traffic(player)returns: the bytes sent to that player in the last second across every Volt schema on the server. So every other schema's bytes count toward this schema's budget. It compares at each send, reliable messages first, and a bot is budgeted like a player. - With several schemas, the budgets are the ranking. A schema with a lower budget gives way first as the player's count rises, one with a higher budget gives way later, and one with no budget never does.
- A package built on Volt runs its own scope, and your game never holds its
Network, so nothing sets a budget on it. Volt never holds it back or drops anything from it. Its bytes still count toward the budgets your own schemas set.
What happens to reliable messages:
- They wait, in order, and the budget never drops one. When the schema next sends to that player, it sends everything that was waiting first, then the current frame, so events, calls and answers stay in the order they were fired. An answer stays behind the events its handler fired. Each channel waits on its own, in its own order.
- They wait at most about a second. What is waiting goes at the first send where any of these holds: the player's count is under the budget, the oldest packet has waited one second, holding this frame back too would leave more than
maxOutgoingof that player's bytes waiting on that channel, or the budget was cleared. - A frame goes whole, so a message larger than the whole budget still goes once its frame does. A frame sent while the count was under the budget goes whole even when it takes the count far past it. After that, this schema's later reliable messages to that player wait and its unreliable ones are dropped, for at most one second.
- The first packet a channel sends a player is never held back, so what was held for the handshake goes out and
onHandshakeruns on time. - A budget never causes an
outgoingfailure. What waits is limited bymaxOutgoingand is sent, instead of dropped, when one more frame would pass it. - A player who leaves takes their waiting packets with them, unsent and unreported.
What happens to unreliable messages, OrderedUnreliable ones included:
- At each send, the schema keeps a player's messages in the order they were fired while the count, plus what that send has already kept, is under the budget. It drops the rest unsent.
- Each send that drops any reports one
budgetfailure for that player, whose detail readsover the budget, unreliable messages dropped: 3. The default handler says nothing about it, as withdeparted, so a game that wants to know readsNetwork.stats(player).failures.budget or 0, which counts those sends, or handles the kind itself (Handling failures yourself).
A function's answer is a reliable message, so it can wait too. With flush = 1 at 60 frames a second, an answer leaves the server within a second and two frames of being written. The default timeout of 10 seconds is well past that, but a function given a timeout of about a second or less can fail with timeout while its answer waits. The same goes for a server's invoke to a player, whose question can wait in the same way, while its timeout counts from the invoke. Give a function under a budgeted schema a timeout longer than that wait plus the time a message takes there and back.
There is no priority per event. A budget treats every message of a kind in a schema alike, so a game that wants some of its messages to give way first slows those streams itself, by reading Network.traffic(player):
-- A cosmetic update skips a player who has had 48 KB this second
local function sendCosmetic(player, value)
local sent = Network.traffic(player)
if sent < 48 * 1024 then
Network.Pong.fire(player, value)
end
end
A budget changes when bytes leave and never what they are, so the schema hash leaves it out and nothing about it reaches the client. In a schema with option stamp = true, a packet that waited carries the time it left. The compiler refuses a top-level declaration named budget, in the schema's casing, since the server module uses that name.
Bots
A bot is a stand-in player that only exists on the server. Every server module treats it as a player, with its own counters, rate limits and handshake, so code that drives a bot goes through the same checks a player's client does. On the server of a running game:
Volt.addBot(name)adds a bot to every Volt schema on the server, including ones started later.Volt.removeBot(bot)removes it, and every server module hears it leave.Volt.connectBot(bot, scope)returns the client side of one scope for the bot, which a test harness starts a client module on.
The server can call a bot with a from: Server function as it calls a player. The client module a harness started on the bot's transport answers, and with none started the call ends with timeout.
A bot is a table { Name = name }, with no UserId and no Kick. A listener's player can be a bot, so strict code checks before it uses what only a Player has. Network.isBot(value) tells them apart. Volt never kicks a bot, and its warnings say from a bot.
The mock transport
The mock lets you test your networking without Studio. It stands in for the remotes and keeps every packet in memory. A transport is whatever carries a side's packets; the real one uses the remotes.
Volt.mock(spawn)makes a mock. Pass the scheduler:task.spawnfrom@lune/taskunder Lune, or Roblox's owntask.spawnin Studio.mock.serveris the server's transport.mock.playersis the list of players.mock:join(name)adds a player, tells the server, and returns the player and that player's client transport.mock:leave(player)tells the server the player is leaving, then forgets them.- A player's
Kick(message)keeps the message inplayer.kickedand makes the player leave. mock:step()moves time forward one frame.mock.timeis the server's clock, 0 until a test sets it. A schema withoption stamp = truewrites it into each packet the server sends, so once a test setsmock.time = 100, the client's listener of the next message the server sends reads 100 fromNetwork.serverTime().mock:addBot(name),mock:removeBot(bot)andmock:connectBot(bot)work like theVoltfunctions above.mock.players,join,leaveandstepnever see a bot.mock:hide(instance)makes an instance invisible to every player's client, as if it had not streamed in, so a message naming it as anAwaitedInstancewaits.mock:reveal(instance)makes it visible again, and each client hears of it at the start of the next step, before that step's packets. A bot still sees a hidden instance.Volt.start(schema, transport)starts a runtime over the transport given instead of the remotes.
A generated module calls Volt.start(schema) itself, so a test loads the module with a require that hands back a Volt whose start passes the mock's transport. This test runs under Lune, which you can add with rokit add lune-org/lune. It needs an alias named volt in your .luaurc that points at the folder holding Volt's init.luau:
local fs = require("@lune/fs")
local luau = require("@lune/luau")
local task = require("@lune/task")
local Volt = require("@volt")
-- Answers every index with itself, so ReplicatedStorage.Packages.Volt resolves to something
local anything = setmetatable({}, {
__index = function(self)
return self
end,
})
-- Loads a generated module so that its Volt.start runs over the transport given
local function load(path: string, transport: Volt.Transport): any
local environment = {
game = {
GetService = function()
return anything
end,
},
require = function()
return {
start = function(schema)
return Volt.start(schema, transport)
end,
}
end,
}
return luau.load(fs.readFile(path), { debugName = path, environment = environment })()
end
local mock = Volt.mock(task.spawn)
local server = load("src/Shared/Network/Server.luau", mock.server)
local alice, aliceTransport = mock:join("Alice")
local client = load("src/Shared/Network/Client.luau", aliceTransport)
server.Ping.on(function(player, value)
server.Pong.fire(player, value + 1)
end)
local heard = nil
client.Pong.on(function(value)
heard = value
end)
client.Ping.fire(7)
mock:step() -- the client's Heartbeat sends the Ping
mock:step() -- the server hears it, and its Heartbeat sends the Pong
mock:step() -- the client hears the Pong
assert(heard == 8, "the client should have heard Pong 8")
alice:Kick("Round over")
assert(alice.kicked == "Round over")
assert(#mock.players == 0)
print("passed")
A bot joins the same way, through its own client transport:
local bot = mock:addBot("Helper")
local botClient = load("src/Shared/Network/Client.luau", mock:connectBot(bot))
botClient.Ping.fire(3) -- the server's Ping listener hears it from the bot on the next step
Each mock:step() first delivers every packet that earlier flushes queued, in both directions, those bound for the server first, then fires one Heartbeat on every runtime, which is when each one sends. So with flush = 1, a fire made outside step reaches the other side on the second step, as the test above shows. A server fire at a player who has not handshaken waits for the step after their handshake arrives.
The mock differs from the real engine in nine ways, which a test that leans on it must know:
- A server packet for a player with no client runtime is dropped at the next step, where the engine keeps it until the client connects. Holding reliable messages until the handshake makes this rarely matter.
- Callbacks for a player who joins or leaves run at once inside
mock:joinormock:leave, in the order they were registered.joinruns them before it returns the client transport, andleaveruns them while the player is still inmock.players. - Reliable and unreliable packets share one queue per direction, which keeps their order, never loses one and never drops one for its size.
- Each side holds one receiver per player. A second server runtime on one mock, or a second client runtime for one player, replaces the first. Two scopes cannot share a mock, so a test with several scopes uses one mock per scope and translates players between them.
- Players are plain tables,
{ Name, UserId, Kick, kicked }, not frozen, withUserIdcounting up from 1. They are not instances, sotypeof(player)gives"table"and a player has noIsA. The same table reaches every callback, handler and listener, so a test may add fields to one. - Heartbeat callbacks get no
deltaTime. - An instance the server names in an
AwaitedInstanceis on every client at once unless the test hides it, where the engine streams it in by distance. - Steps take no time. The bytes a player was sent in the last second, the first number
Network.traffic(player)returns, fall only as real time passes. So over the mock, messages a budget holds back go only when holding more would passmaxOutgoing, when the budget is cleared, or after a real second. - A client counts steps the way the server counts frames, so with
flush = 1it sends on every step, where a client in a running game sends at most 60 times a second.
MicroProfiler labels
option profileLabels = true labels Volt's work in Roblox's MicroProfiler, so you can see what it costs in each frame. Add it to Game.volt and compile again:
option profileLabels = true
Each label starts with Volt and the schema's scope:
Volt Game receivewraps each packet a module handles: its checks, every message in it and any failure it reports.Volt Game Ping, inside it, wraps each message: reading it, then what happens when it arrives, such as a sync listener running, an async listener's thread or a handler's thread starting, or the message joining a queue. A message in a namespace uses its full name, as inVolt Game Combat.Hit.Volt Game flushwraps each Heartbeat's send, and eachNetwork.flush()your code calls. Every Heartbeat gets one, even a Heartbeat that sends nothing, such as the ones between sends withflush = 2.
When Alice's client fires Ping and calls Echo in one frame, the server labels her packet Volt Game receive, with Volt Game Ping and then Volt Game Echo inside it. Its Volt Game flush labels come separately, one per Heartbeat.
Firing a message has no label of its own. A fire's checks and writing run inside whatever label your own code opens around it, and its bytes go out inside Volt Game flush.
With the option off, which is the default, the modules are byte for byte what they are without it. With it on, each packet, each message and each flush costs two more calls. It changes nothing that is sent, so the schema hash leaves it out, and a client compiled with labels connects to a server compiled without them.
Lune's debug has no profiler, so under Lune a module compiled with profileLabels raises attempt to call a nil value at the first mock:step(). Compile the modules your tests load without the option, or put a debug table with profilebegin and profileend functions in the environment the test loads them with (The mock transport).
The packet inspector
PacketProfiler is a community tool that shows how much data each remote sends. All of a Volt schema's messages travel on its two remotes, so on its own PacketProfiler sees Volt's remotes and not the messages inside them. option inspectorOutput writes one more module, the packet inspector, which reads a packet back into the messages it holds. Add this to Game.volt and compile again:
option inspectorOutput = "src/Shared/Network/Inspector.luau"
The inspector module returns a function, which takes a remote and then everything that remote's event passed: on the server the player, the packet and its side array, and on the client the packet and its side array. It returns a list with one entry per message, each { Name = ..., Arguments = { ... } }, or nil for a remote outside the schema's folder, ReplicatedStorage.Volt.Game.
When Alice's client fires Ping with 7 and calls Echo with "hello" in one frame, it returns this for her packet. 2303537933 is the schema hash, 0x894D330D:
{
{ Name = "Volt handshake", Arguments = { 2303537933 } },
{ Name = "Ping", Arguments = { 7 } },
{ Name = "Echo (call)", Arguments = { "hello" } },
}
When the server answers with Network.Pong.fire(alice, 8) and its Echo handler returns "HELLO", it returns this for the server's packet to her:
{
{ Name = "Pong", Arguments = { 8 } },
{ Name = "Echo (reply)", Arguments = { true, "HELLO" } },
}
The entries it gives:
Volt handshake, with the schema hash, at the start of a client's first packet to the server.Volt stamp, with the server's time, at the start of each packet a client receives in a schema withoption stamp = true.- Each event by its full name, with its values. An
OrderedUnreliableevent's count comes first, and a@deltaevent gives the mask of the fields it carries, then a table of those fields. - A call as
Echo (call)with its data, and its answer asEcho (reply)withtrueand the returned values, orfalseand the reason. Volt dictionary, on the client, for the message that brings new@dictionarystrings: the first new string's id, then the strings.- An
AwaitedInstanceand a@dictionarystring appear as the numbers they travel as, since only the client's runtime knows what each number names. A channel byte is checked, and gets no entry.
A message that fails a check ends the list, as it ends the packet for the side that receives it. The entries before it stay, and one more is added: decode: and the message's name, with the error as its argument, or packet: and the problem for anything else wrong with the packet, such as a message id that names no message. One byte more, a 9, at the end of Alice's packet above adds { Name = "packet: unknown message 9", Arguments = { "unknown message 9" } }. The inspector never raises an error.
It reads each message with every check the receiving side makes, and only for display: nothing it reads reaches a listener, a handler, a hook, a queue or the counters. It requires no runtime, starts nothing and connects to nothing, so it is as safe to require in a plugin as in the game.
PacketProfiler 3.0.2 looks for a ModuleScript named RemoteName.profiler anywhere under ReplicatedStorage, requires it, and calls the function it returns for each remote call it records. Give the inspector that file name:
option inspectorOutput = "src/Shared/Network/RemoteName.profiler.luau"
Rojo builds the file as a ModuleScript named RemoteName.profiler, so with the project file from Install it sits in ReplicatedStorage.Shared.Network. A game with several Volt schemas has one inspector for each, and PacketProfiler takes one RemoteName.profiler, so write that module yourself: require each schema's inspector, and return the first answer that is not nil.
The inspector is never split into shards. One that would need more than 150 locals is refused with V4003, reported at the top of the options file, as in the inspector needs 154 module-level locals, more than one generated file holds (150). inspectorOutput changes nothing that is sent, so the schema hash leaves it out. volt writes the inspector and --check compares it like any other module.
Colors in VS Code
Volt comes with a small VS Code extension that colors .volt files. It colors comments, strings, keywords such as event and struct, types such as u8 and Vector3, the keys of an event or a function, fixed values such as Reliable and SingleSync, attributes such as @private, and numbers. It also marks the two mistakes volt finds while it reads a file character by character, a string with no closing quote and a character the language never uses, such as $, from that point to the end of the line; most themes show them in red. Toggle Line Comment (Ctrl+/) writes --, and VS Code closes brackets and quotes as you type.
The extension is not in the Wally package and not on the VS Code Marketplace. It lives in Volt's repository, in the folder .vscode/volt-syntax, so you need a copy of the repository on your computer, for example from git clone https://github.com/Fadeluc-123/Volt.git. It is three small JSON files, with nothing to build.
Install it once on each computer:
- Open VS Code. Any folder can be open, or none.
- Open the Command Palette with Ctrl+Shift+P (Cmd+Shift+P on a Mac).
- Type
Developer: Install Extension from Location...and press Enter. - In the folder picker, go into Volt's repository folder, then into
.vscode, select the foldervolt-syntaxand confirm. On a Mac the picker hides folders whose name starts with a dot until you press Cmd+Shift+. (period). - Open any
.voltfile. The language name at the right of the status bar, along the bottom of the window, readsVolt, and the file is colored.
VS Code uses the folder where it lies instead of copying it, so one install colors .volt files in every project you open on that computer. Two things follow from that:
- After the extension's files change, for example when you pull a newer Volt or edit the grammar, open the Command Palette and run
Developer: Reload Window, and VS Code reads the new files. - If you move or delete Volt's folder, the colors stop. Install the extension again from the folder's new place.
If a .volt file is colored as some other language, another extension claims .volt too; one for Phalcon's Volt templates uses the same file extension. Click the language name in the status bar, choose Configure File Association for '.volt'... and pick Volt.
Options
Options go at the top of a schema, one per line: option name = value. A path to a module is written with dots and starts with a service, such as ReplicatedStorage.Packages.Volt.
| Option | Default | What it does |
|---|---|---|
clientOutput | required | Where the client module is written, relative to the schema file (the options file, for a folder) |
serverOutput | required | Where the server module is written |
typesOutput | none | Where the types module is written; without it, none is written |
inspectorOutput | none | Where the packet inspector is written, relative to the schema file; without it, none is written (The packet inspector). It changes nothing that is sent, so the schema hash leaves it out |
runtime | ReplicatedStorage.Packages.Volt | Where the generated modules require the Volt runtime from |
scope | the schema file's name | The folder under ReplicatedStorage.Volt that holds this schema's remotes |
casing | camel | How the module's methods are named: camel (fireAll, onFailure), pascal (FireAll, OnFailure) or snake (fire_all, on_failure) |
writeValidation | true | Whether the sending side checks values before writing them; the receiving side always does |
manualReplication | false | When true, Volt does not send on Heartbeat, and your code calls Network.flush(); a flushBytes the schema sets still sends at its threshold |
flush | 1 | Send every this many Heartbeats on the server; a player's client in a running game sends at most 60 / flush times a second, whatever its frame rate |
flushBytes | none | Also send at the next Heartbeat once one target's unsent bytes reach this many, between the frames flush names and under manualReplication too; the compiler warns when every frame sends already (Use it in your scripts). It changes the schema hash only when a schema sets it |
maxPacket | 8192 | The largest reliable packet the server accepts from a player, in bytes; the client keeps each send's reliable data under it too, and a client above 60 frames a second sends several frames' data at once |
maxPacketsPerSecond | 240 | Packets per second the server accepts from each player, both remotes and every channel together |
maxOutgoing | 262144 | Bytes one player's outgoing data may hold between two sends, on each channel; the message that goes past it is dropped |
unreliableBudget | 900 | The most bytes in one unreliable remote call, and the largest an unreliable message may be, less the byte a channel adds and, for the server's messages, the 8 that stamp adds |
stamp | false | When true, every packet the server sends starts with its clock, which the client reads with Network.serverTime() (see When the server sent a message) |
queue | 64 | How many messages wait per event for a listener or for iter |
rate | 120 | Messages per second each player may fire per event; unlimited turns the limit off |
functionRate | 60 | Calls per second each player may make per function; unlimited turns the limit off |
timeout | 10 | Seconds before a call fails with timeout, and how long a message waits for an AwaitedInstance; decimals are allowed |
yield | coroutine | How invoke waits: coroutine pauses the calling thread, and promise returns a Promise |
promise | none | The path of your Promise library, such as ReplicatedStorage.Packages.Promise; required when yield = promise |
shardSize | none | The most entries (events, functions and exported types) one generated file holds; a side with more is split into shards, and a side past 150 locals is split without it (A schema too big for one module). It changes nothing that is sent, so the schema hash leaves it out and changing it never breaks a client's handshake |
profileLabels | false | When true, Volt labels each packet, each message and each flush in the MicroProfiler (MicroProfiler labels). It changes nothing that is sent, so the schema hash leaves it out |
With yield = promise, invoke returns a Promise that resolves with the answer, with no true in front, or rejects with the reason.
Keys of an event:
| Key | Values | Default |
|---|---|---|
from | Client, Server, Both | required |
type | Reliable, Unreliable, OrderedUnreliable | required |
call | SingleSync, SingleAsync, ManySync, ManyAsync, Polling | required |
data | a type, or a parameter pack such as (x: f32, y: f32) | none; the event carries nothing |
queue | a whole number | the queue option |
rate | a whole number, or unlimited | the rate option; on a Server event it means nothing and the compiler warns |
timeout | a number of seconds a message waits for its AwaitedInstance before it is dropped; only for an event whose data holds one, and the compiler warns on any other | the timeout option |
channel | the name of a channel the schema declares with channel Name; Reliable events only | none; the default line |
A schema declares a channel with channel Name on a line of its own, at the top level or in a namespace, and at most 255 of them (Channels).
Keys of a function:
| Key | Values | Default |
|---|---|---|
from | Client, Server: who calls it; the other side answers | Client |
data | a type, or a parameter pack | none |
return | a type, or a parameter pack | none |
yield | Coroutine, Promise | the yield option |
timeout | a number of seconds | the timeout option |
rate | a whole number, or unlimited | the functionRate option; on a from: Server function it means nothing and the compiler warns |
Attributes go in front of a declaration, as in @delta event Status { ... }:
| Attribute | Goes in front of | What it does |
|---|---|---|
@private | a type, struct or enum that is not exported | Keeps its Luau type inside the generated modules (Types) |
@delta | a from: Server, Reliable event whose data is one struct of 1 to 32 fields | Sends each player only the fields that changed since the last value they were sent (Only the fields that changed) |
@dictionary | a type that is a string or string.utf8 of at most 255 bytes | Sends each value as a 2-byte id, and each string to each player once (Strings sent as ids) |
@depth(n) | a type, struct or enum that contains itself, exported or not | Sets the deepest level a value of the type may sit at, from 1 to 1,000; without it the bound is 16 (Recursive types) |
Troubleshooting
Volt: Decree's schema was compiled by Volt 0.2.0 and the runtime is 0.1.3
A generated module was compiled by a volt whose version differs from the runtime's in its first two numbers, and require refuses it. The name before 's schema is the scope that needs updating: here a package called Decree, and for your own schema its file name, such as Game. Make the two versions match: compile your own schemas again with the volt that matches your runtime, or update the package or Volt so they agree.
Volt: schema mismatch (client 0x10E8CDEB, server 0x894D330D)
This is the message a player is kicked with when the client module and the server module came from different schemas. Run volt again and publish both modules. volt Game.volt --check in CI catches a stale module before it ships. Two different schemas that set the same option scope cause this too.
Volt: rate failure from Alice: Ping: over 120 a second
A player fired Ping more than 120 times in a second, and the server dropped the messages past the limit. If the game really needs more, raise rate on the event. Otherwise fire less often, for example once per change instead of once per frame.
Ping: expected u8
Input.dir: expected u8(0..8)
Echo: length out of range
A fire or an invoke was given a value its type does not allow, and nothing was sent. The text names the message, then the field for a parameter pack: Input.dir is the dir value of an event Input with data: (dir: u8(0..8), jump: boolean). Fix the value, or change the type in the schema.
Tree: nested deeper than 4
Volt: decode failure from Alice: Build: Tree: nested deeper than 4
A value of a recursive type went past its @depth. The first is the error your own fire or invoke raises, with nothing sent, so look for a table deeper than the bound or one that holds itself. The second is the server refusing bytes a player sent, which Volt's own client never writes. Raise @depth only if the game really needs the depth, and within what maxPacket allows (Recursive types).
Volt: resolve failure: BossSpawned: instance 1 did not arrive within 5 seconds
A message named an AwaitedInstance that this player's client did not get within the event's timeout, so the client dropped the message. The instance may have been destroyed, may sit where players never get it, such as ServerStorage, or may have stayed too far from the player to stream in. Fire the message only for instances the player can get, or raise timeout on the event (Waiting for an instance).
Picked.item: dictionary full
A fire named a new string of a @dictionary type when the schema's dictionary already held 4,096 strings, so it raised and sent nothing. The dictionary never forgets a string, so it fills only when its types take values with no end, such as text players type or names built from numbers. Keep those types without @dictionary (Strings sent as ids).
Volt: decode failure: Status: no baseline
The client got a @delta message that leaves out fields, for an event it has had no whole value of, so it had nothing to fill them from and dropped the message with the rest of its packet. Volt's server always sends a player the whole value first, and again after any message to them is dropped.
Volt: decode failure: Picked: Picked.item: unknown dictionary id
Volt: decode failure: Volt.dictionary: out of order
The first names a @dictionary string by an id the client was never sent. The second means the message that carries the strings could not be taken whole: its strings were not the next ones in order (out of order), it was cut short (truncated), it held none (no entries) or it would take the list past 4,096 (past 4096 entries). The client takes none of a message it refuses. Volt's server sends every player each string, in order, before the first packet that names it, so a client module and a server module from the same schema never see either.
Volt: queue failure from Alice: Ping: queue full, oldest dropped
Messages for Ping arrived while nothing was listening, and more than 64 piled up. Connect the listener earlier, read a Polling event more often, or raise queue.
Pong: a listener is already connected
on was called twice for a Single event. Luau puts the position of the line in Volt that raised it in front of this text. Disconnect the first listener before connecting another, or make the event ManySync or ManyAsync. A function gives Echo: a handler is already connected the same way.
Volt: still waiting for ReplicatedStorage.Volt.Game
The client module has waited 10 seconds for remotes the server has not created, and it keeps waiting and warning. The server creates them when it first requires its module, so make sure a server Script requires Server.luau. The warning names ReplicatedStorage.Volt alone when no schema's server module has run.
The system cannot find the path specified. (os error 3)
On Windows, volt prints this when the folder an output option points into does not exist. Create the folder and run volt again. Other systems word the message differently. Under --watch it follows volt: internal error:, and the watch goes on, so create the folder and save the schema again.
Game.volt: src/Shared/Network/ServerShard1.luau is no longer generated
volt --check found a shard file the schema no longer writes, because the schema shrank or lost its shardSize. Run volt Game.volt without --check, which deletes it, and commit the deletion (A schema too big for one module).
Unknown type 'Volt.Runtime'
The type checker cannot see Volt's types. Run rojo sourcemap and wally-package-types as in Install, after every wally install.
Versions
The compiler and the runtime share one version number, and you upgrade them together. This release is 0.1.0.
Each generated module records the version of the volt that wrote it, and Network.version returns it. When a module is required, the runtime compares the first two numbers of that version with its own and refuses a module that differs, with the error in Troubleshooting.
Wally reads 0.1.0 in wally.toml as any version from 0.1.0 up to, but not including, 0.2.0. A patch release such as 0.1.1 never changes how a module talks to the runtime, the failure kinds or anything a script calls, so taking one is safe. Anything that would change them comes as a new second number, such as 0.2.0, which the check at require catches.
To upgrade, change the version of fadeluc-123/volt in both rokit.toml and wally.toml, run rokit install and wally install, run the two type commands from Install, then run volt on every schema.
Working on Volt
The compiler lives in src/Compiler/ and runs under Lune. The runtime is the rest of src/, and it is the only part published to Wally. The tests are in tests/, with the schemas they compile in tests/Schemas/ and the expected generated modules in tests/Golden/.
Install the tools pinned in rokit.toml, then use the scripts in .lune/:
rokit install
lune run test # every test; lune run test Functions runs only files whose name contains Functions
lune run test --update # rewrites the golden files after a reviewed change to the generator
lune run analyze # luau-lsp over the source, the tests and the generated modules
lune run format # StyLua over every first-party file
lune run build # the volt binaries and their archives, in build/
lune run bench # the benchmark, compiled, built and run in Studio
selene src tests .lune place benchmark
CI runs the gates, the checks every change must pass, on each pull request and push to main.
Run the compiler from source with lune run src/Compiler <schema>.
The editor colors come from .vscode/volt-syntax/syntaxes/volt.tmLanguage.json. Four of its rules list words the compiler knows: keyword the lexer's keywords, primitive the rows of src/Compiler/Config/Primitives.luau, roblox the rows of Config/Roblox.luau, and value the fixed values in Config/Options.luau. tests/Grammar.test.luau fails when one of those lists and its source differ, printing both, so a word added to the compiler is added to its rule in the same change. The other rules match by shape and no test runs them, so after editing the grammar run Developer: Reload Window and read tests/Schemas/Example.volt and tests/Schemas/Console.volt; Developer: Inspect Editor Tokens and Scopes shows the scope of the text under the cursor.
The smoke place in place/ checks real remotes in Studio:
lune run src/Compiler tests/Schemas/Smoke.volt
rojo build place/place.project.json -o Smoke.rbxl
Open Smoke.rbxl, start a test with "Start Server + 1 Player", and both Output windows print Volt smoke: pass. The place turns on StreamingEnabled, so it also proves AwaitedInstance against real streaming: a part beside the spawn arrives, a part 5,000 studs away arrives once the server moves it beside the spawn, and a part kept in ServerStorage never does, which the client expects as its one resolve failure. It also sends a chain 1,000 levels deep each way, the deepest @depth allows, so the generated reads and writes run that deep on Roblox's own stack. Compiling Smoke.volt also writes its packet inspector, which the place holds as ReplicatedStorage["RemoteName.profiler"], so with PacketProfiler installed it shows each message of the run by name.
License
Volt is licensed under the Apache License 2.0. The full text is in LICENSE.
Package Details
Install command (Click to copy)
Version
0.1.0
License
Apache-2.0
Safe for commercial use
Modified files must carry a notice of changes. If the package ships a NOTICE file, its attributions must be preserved.
Automated license review — not legal advice.
