Your first federate in Rust
This tutorial builds a small HLA 4 federate in Rust with the microrti-client crate. You run two copies
of it, alice and bob, against a local MicroRTI server and watch them greet each other through the
RTI. You need to know a little Rust; no HLA knowledge is assumed. Each step links to the HLA concept it
uses, on The concepts of HLA, one by one; the glossary
has the short definitions.
What you need
- Rust 1.88 or later (
rustc --versiontells you which one you have). - The
micrortiserver.cargo install micrortibuilds and installs it; Install and run the RTI lists the other ways. - Three terminals: one for the server and one for each federate.
What you are building
In HLA, the programs that take part in a simulation are federates. They do not talk to each other directly: each one connects to the Run-Time Infrastructure (the RTI), and the RTI passes data between them. A running simulation is a federation execution. Its federates agree on what they exchange through a Federation Object Model (the FOM), made of one or more XML files called FOM modules.
Your FOM module has one interaction class, Greeting, with two parameters, Sender and Text. An
interaction is a message that is sent once and leaves nothing behind; HLA also has objects, whose
attributes keep their values over time, but this tutorial does not use them. Each federate sends five
greetings, two seconds apart, and prints the greetings it receives from the others.
Create the project
cargo new hello-federate
cd hello-federate
cargo add microrti-client@0.5Cargo.toml now has the dependency:
[dependencies]
microrti-client = "0.5"The crate’s default feature, fedpro, is the client side of the HLA Federate Protocol: it reaches an RTI
over TCP, TLS, WebSocket or secure WebSocket. The build needs no protoc: the protobuf files of the
protocol are compiled by a Rust build script.
Write the FOM module
Save this as Greetings.xml, next to Cargo.toml:
<?xml version="1.0" encoding="UTF-8"?>
<objectModel xmlns="http://standards.ieee.org/IEEE1516-2025">
<modelIdentification>
<name>Greetings</name>
<type>FOM</type>
<version>1.0</version>
<description>Federates that say hello to each other</description>
</modelIdentification>
<interactions>
<interactionClass>
<name>HLAinteractionRoot</name>
<interactionClass>
<name>Greeting</name>
<sharing>PublishSubscribe</sharing>
<transportation>HLAreliable</transportation>
<order>Receive</order>
<semantics>A federate says hello</semantics>
<parameter>
<name>Sender</name>
<dataType>HLAunicodeString</dataType>
<semantics>Name of the federate that says it</semantics>
</parameter>
<parameter>
<name>Text</name>
<dataType>HLAunicodeString</dataType>
<semantics>What it says</semantics>
</parameter>
</interactionClass>
</interactionClass>
</interactions>
</objectModel>What the parts mean:
- The namespace
http://standards.ieee.org/IEEE1516-2025marks a module in the HLA 4 format (IEEE 1516.2-2025). Greetingsits underHLAinteractionRoot, the root of every interaction class.PublishSubscribelets a federate both send and receive greetings.HLAreliableasks for reliable delivery, andReceiveorder means greetings are delivered as they arrive, without logical time.HLAunicodeStringis a data type of the standard MIM (the MOM and Initialization Module), which the RTI adds to every federation execution, so your module does not define it.
The RTI checks the module when the federation execution is created. A class with transportation but no
order, for example, is refused with the exception InvalidFOM, and a file that is not XML with
ErrorReadingFOM.
Write the federate, step by step
The program takes two command line arguments: the federate name and the RTI address. The HLA work
happens in a function run, so that the last section of this page can call it twice in one process. Start
src/main.rs with the imports and main:
use std::sync::mpsc;
use std::time::{Duration, Instant};
use microrti_client::fedpro::DEFAULT_RTI_ADDRESS;
use microrti_client::{
Callback, CallbackFn, CallbackModel, ExceptionKind, FomModule, ParameterHandle,
ParameterHandleValueMap, ResignAction, RtiAmbassador, RtiConfiguration, RtiResult,
decode_hla_unicode_string, encode_hla_unicode_string,
};
const FEDERATION: &str = "Greetings";
const FOM: &str = include_str!("../Greetings.xml");
fn main() -> RtiResult<()> {
let mut args = std::env::args().skip(1);
let name = args.next().unwrap_or_else(|| "alice".to_owned());
let address = args.next().unwrap_or_else(|| DEFAULT_RTI_ADDRESS.into());
run(&name, &address)
}Every RTI service returns an RtiResult<T>. The ? operator passes an error up to main, which prints
it and ends the program with exit status 1. DEFAULT_RTI_ADDRESS is tcp://localhost:15164, where a
microrti started without options listens.
Step 1: connect to the RTI
fn run(name: &str, address: &str) -> RtiResult<()> {
// 1. Connect. The federate ambassador receives the callbacks; this one hands the
// parameter values of every interaction it receives to the loop of step 7.
let (inbox, received) = mpsc::channel();
let federate_ambassador = CallbackFn::new(move |callback| {
if let Callback::ReceiveInteraction {
parameter_values, ..
} = callback
{
let _ = inbox.send(parameter_values);
}
Ok(())
});
let rti = RtiAmbassador::new();
let configuration = RtiConfiguration::new().with_rti_address(address);
rti.connect_with_configuration(federate_ambassador, CallbackModel::Evoked, &configuration)?;
println!("[{name}] connected to {address}");A federate talks to the RTI through two objects (see
ambassadors and callbacks). The RTI ambassador,
RtiAmbassador, carries your requests to the RTI: each of its methods is one RTI service, and it blocks
until the RTI answers. The federate ambassador works the other way round: the RTI calls it to
deliver callbacks, such as an interaction sent by another federate.
Here the federate ambassador is a closure wrapped in CallbackFn. It receives every callback as a value
of the Callback enum, keeps only ReceiveInteraction, and puts its parameter values on a channel. The
channel is there because the federate ambassador is handed over at connect time, before the program has
the handles it needs to read the values (step 4).
The second argument of connect_with_configuration, the callback model, decides when callbacks run.
With CallbackModel::Evoked, they run only when your code asks for them, on your own thread (step 7).
The other model, CallbackModel::Immediate, runs them on a thread of the RTI ambassador as soon as
they arrive.
The RTI address goes into an RtiConfiguration. Its scheme picks the transport: tcp://, tls://,
ws:// or wss://.
Step 2: create the federation execution
// 2. Create the federation execution, unless another federate already did.
let fom = FomModule::content("Greetings.xml", FOM);
match rti.create_federation_execution(FEDERATION, &fom) {
Ok(()) => println!("[{name}] created the federation execution {FEDERATION}"),
Err(error) if error.kind == ExceptionKind::FederationExecutionAlreadyExists => {
println!("[{name}] the federation execution {FEDERATION} already exists")
}
Err(error) => return Err(error),
}FomModule::content sends the module as text. include_str! copied the file into the program at compile
time, so the program does not depend on the directory you start it from.
An RTI holds at most one federation execution of a given
name. The first federate creates it; the second one gets the exception
FederationExecutionAlreadyExists, which here only means “it is already there”. An error is an
RtiError with a kind, the standard exception, and a message for humans. Matching on kind handles
this one case and still passes every other error up.
Step 3: join
// 3. Join it.
rti.join_federation_execution_with_name(name, "Greeter", FEDERATION)?;
println!("[{name}] joined {FEDERATION}");Joining makes the program a member of the federation execution. The arguments are:
- the federate name, which must be unique in the federation execution (a second
alicegetsFederateNameAlreadyInUse); - a federate type, free text saying what kind of federate this is;
- the name of the federation execution.
Step 4: get the handles
// 4. Get the handles of the interaction class and of its parameters.
let greeting = rti.get_interaction_class_handle("Greeting")?;
let sender = rti.get_parameter_handle(&greeting, "Sender")?;
let text = rti.get_parameter_handle(&greeting, "Text")?;RTI services take handles, short
values that stand for names. The RTI hands them out for each federation execution, so you ask for them
after joining. "Greeting" is enough as the class name; the full name
"HLAinteractionRoot.Greeting" gives the same handle. A name that is not in the FOM fails with
NameNotFound.
Step 5: publish and subscribe
// 5. Say what this federate sends and what it wants to receive.
rti.publish_interaction_class(&greeting)?;
rti.subscribe_interaction_class(&greeting)?;Publishing tells the RTI that
this federate sends greetings; sending without publishing fails with InteractionClassNotPublished.
Subscribing asks the RTI to deliver the greetings that other federates send. A federate does not
receive its own interactions.
Step 6: send a greeting
for round in 1..=5 {
// 6. Send a greeting.
let said = format!("Hello from {name} ({round} of 5)");
let values = ParameterHandleValueMap::from([
(sender.clone(), encode_hla_unicode_string(name)),
(text.clone(), encode_hla_unicode_string(&said)),
]);
rti.send_interaction(&greeting, &values, b"")?;
println!("[{name}] sent: {said}");The values of an
interaction’s parameters travel as
bytes. ParameterHandleValueMap is a BTreeMap from parameter handle to Bytes, and each value holds
the encoding of the parameter’s data type: for HLAunicodeString, that is what
encode_hla_unicode_string produces. The last argument of send_interaction is the user-supplied tag,
a few bytes of your own that the receivers get with the interaction; this program sends an empty one.
Step 7: receive greetings through callbacks
The loop goes on with the listening part:
// 7. Listen for two seconds. Callbacks run inside evoke_callback, on this thread.
let until = Instant::now() + Duration::from_secs(2);
while Instant::now() < until {
rti.evoke_callback(Duration::from_millis(100))?;
for heard in received.try_iter() {
let who = parameter_text(&heard, &sender);
let what = parameter_text(&heard, &text);
println!("[{name}] heard {who}: {what}");
}
}
}In the evoked callback model, nothing reaches the
federate ambassador until you call evoke_callback. Each call delivers at most one callback, on the
calling thread; when none is waiting it waits for one, up to the time you give (100 ms here). It returns
true when more callbacks are pending. The loop calls it for two seconds and prints what the closure
put on the channel. evoke_multiple_callbacks delivers several callbacks in one call. In both models,
the callbacks of one federate never run at the same time.
Add this helper at the end of the file, after run:
/// The text of one parameter: empty when it is missing or is not an HLAunicodeString.
fn parameter_text(values: &ParameterHandleValueMap, parameter: &ParameterHandle) -> String {
match values.get(parameter) {
Some(value) => decode_hla_unicode_string(value).unwrap_or_default(),
None => String::new(),
}
}The bytes come from another program, so the helper does not trust them: decode_hla_unicode_string fails
on bytes that are not a valid HLAunicodeString, and the helper then returns an empty string instead of
stopping the federate.
Step 8: resign and destroy
// 8. Resign, then try to destroy the federation execution.
rti.resign_federation_execution(ResignAction::NoAction)?;
println!("[{name}] resigned");
match rti.destroy_federation_execution(FEDERATION) {
Ok(()) => println!("[{name}] destroyed the federation execution {FEDERATION}"),
Err(error)
if error.kind == ExceptionKind::FederatesCurrentlyJoined
|| error.kind == ExceptionKind::FederationExecutionDoesNotExist =>
{
println!("[{name}] did not destroy {FEDERATION}: {}", error.kind)
}
Err(error) => return Err(error),
}Resigning ends the membership. The resign action says what the RTI
does with the objects the federate owns; this one owns none, hence ResignAction::NoAction. A
federation execution can be destroyed only when nobody is joined any more: while bob is still there,
alice gets FederatesCurrentlyJoined. When two federates finish at the same moment, the second one
may find the federation execution already gone (FederationExecutionDoesNotExist). Both cases are
normal for this program.
Step 9: disconnect
// 9. Disconnect.
rti.disconnect()?;
println!("[{name}] disconnected");
Ok(())
}disconnect is the counterpart of Connect: it ends the Federate
Protocol session, closes the connection and drops the federate ambassador.
Run two federates
In the first terminal, start the RTI on the loopback interface. Port 0 lets the system choose a free port:
microrti --listen tcp://127.0.0.1:0The server prints the address it listens on (listening on ...) among its log lines. The first lines
look like this:
2026-12-02T20:48:11.250781Z INFO microrti: microrti starting version="0.5.0"
2026-12-02T20:48:11.250854Z INFO microrti::server: FOM modules and MIMs named by file:, http: or https: URL are read wherever they are: set fom_urls = "none" or fom_url_directory to restrict this when federates outside a trusted network can reach the RTI timeout=30s
2026-12-02T20:48:11.250866Z INFO microrti::server: federation saves are kept in memory and lost when the RTI stops: set save_directory to keep them in files
2026-12-02T20:48:11.251135Z INFO microrti::server: RTI listening endpoint=tcp://127.0.0.1:58387
listening on tcp://127.0.0.1:58387
2026-12-02T20:48:11.251186Z INFO microrti_fedpro::server: Federate Protocol listener ready address=127.0.0.1:58387 transport=tcpIn the second terminal, from the hello-federate directory, start alice with the address your server
printed:
cargo run --quiet -- alice tcp://127.0.0.1:58387In the third terminal, within a few seconds, start bob:
cargo run --quiet -- bob tcp://127.0.0.1:58387This is what alice printed, with bob started three seconds after her:
[alice] connected to tcp://127.0.0.1:58387
[alice] created the federation execution Greetings
[alice] joined Greetings
[alice] sent: Hello from alice (1 of 5)
[alice] sent: Hello from alice (2 of 5)
[alice] heard bob: Hello from bob (1 of 5)
[alice] sent: Hello from alice (3 of 5)
[alice] heard bob: Hello from bob (2 of 5)
[alice] sent: Hello from alice (4 of 5)
[alice] heard bob: Hello from bob (3 of 5)
[alice] sent: Hello from alice (5 of 5)
[alice] heard bob: Hello from bob (4 of 5)
[alice] resigned
[alice] did not destroy Greetings: FederatesCurrentlyJoined
[alice] disconnectedAnd bob:
[bob] connected to tcp://127.0.0.1:58387
[bob] the federation execution Greetings already exists
[bob] joined Greetings
[bob] sent: Hello from bob (1 of 5)
[bob] heard alice: Hello from alice (3 of 5)
[bob] sent: Hello from bob (2 of 5)
[bob] heard alice: Hello from alice (4 of 5)
[bob] sent: Hello from bob (3 of 5)
[bob] heard alice: Hello from alice (5 of 5)
[bob] sent: Hello from bob (4 of 5)
[bob] sent: Hello from bob (5 of 5)
[bob] resigned
[bob] destroyed the federation execution Greetings
[bob] disconnectedbob never heard greetings 1 and 2 of alice: she sent them before he subscribed. The RTI delivers an
interaction to the federates that are subscribed when it is sent, and does not keep it for later ones. In
the same way, alice missed greeting 5 of bob, sent after she had resigned. alice left first and
could not destroy the federation execution; bob was the last one and did. The server log follows each
step, with lines such as federate joined ... federation=Greetings federate=alice federate_type=Greeter and
federation execution destroyed. Stop the server with Ctrl-C.
If nothing listens at the address, Connect fails with ConnectionFailed:
cargo run --quiet -- alice tcp://127.0.0.1:1Error: RtiError { kind: ConnectionFailed, message: "cannot reach the RTI: tcp://127.0.0.1:1: transport error: cannot connect to tcp://127.0.0.1:1: Connection refused (os error 61)" }The text after Connection refused comes from the operating system (this run was on macOS).
The complete program
src/main.rs, as built by the steps above:
use std::sync::mpsc;
use std::time::{Duration, Instant};
use microrti_client::fedpro::DEFAULT_RTI_ADDRESS;
use microrti_client::{
Callback, CallbackFn, CallbackModel, ExceptionKind, FomModule, ParameterHandle,
ParameterHandleValueMap, ResignAction, RtiAmbassador, RtiConfiguration, RtiResult,
decode_hla_unicode_string, encode_hla_unicode_string,
};
const FEDERATION: &str = "Greetings";
const FOM: &str = include_str!("../Greetings.xml");
fn main() -> RtiResult<()> {
let mut args = std::env::args().skip(1);
let name = args.next().unwrap_or_else(|| "alice".to_owned());
let address = args.next().unwrap_or_else(|| DEFAULT_RTI_ADDRESS.into());
run(&name, &address)
}
fn run(name: &str, address: &str) -> RtiResult<()> {
// 1. Connect. The federate ambassador receives the callbacks; this one hands the
// parameter values of every interaction it receives to the loop of step 7.
let (inbox, received) = mpsc::channel();
let federate_ambassador = CallbackFn::new(move |callback| {
if let Callback::ReceiveInteraction {
parameter_values, ..
} = callback
{
let _ = inbox.send(parameter_values);
}
Ok(())
});
let rti = RtiAmbassador::new();
let configuration = RtiConfiguration::new().with_rti_address(address);
rti.connect_with_configuration(federate_ambassador, CallbackModel::Evoked, &configuration)?;
println!("[{name}] connected to {address}");
// 2. Create the federation execution, unless another federate already did.
let fom = FomModule::content("Greetings.xml", FOM);
match rti.create_federation_execution(FEDERATION, &fom) {
Ok(()) => println!("[{name}] created the federation execution {FEDERATION}"),
Err(error) if error.kind == ExceptionKind::FederationExecutionAlreadyExists => {
println!("[{name}] the federation execution {FEDERATION} already exists")
}
Err(error) => return Err(error),
}
// 3. Join it.
rti.join_federation_execution_with_name(name, "Greeter", FEDERATION)?;
println!("[{name}] joined {FEDERATION}");
// 4. Get the handles of the interaction class and of its parameters.
let greeting = rti.get_interaction_class_handle("Greeting")?;
let sender = rti.get_parameter_handle(&greeting, "Sender")?;
let text = rti.get_parameter_handle(&greeting, "Text")?;
// 5. Say what this federate sends and what it wants to receive.
rti.publish_interaction_class(&greeting)?;
rti.subscribe_interaction_class(&greeting)?;
for round in 1..=5 {
// 6. Send a greeting.
let said = format!("Hello from {name} ({round} of 5)");
let values = ParameterHandleValueMap::from([
(sender.clone(), encode_hla_unicode_string(name)),
(text.clone(), encode_hla_unicode_string(&said)),
]);
rti.send_interaction(&greeting, &values, b"")?;
println!("[{name}] sent: {said}");
// 7. Listen for two seconds. Callbacks run inside evoke_callback, on this thread.
let until = Instant::now() + Duration::from_secs(2);
while Instant::now() < until {
rti.evoke_callback(Duration::from_millis(100))?;
for heard in received.try_iter() {
let who = parameter_text(&heard, &sender);
let what = parameter_text(&heard, &text);
println!("[{name}] heard {who}: {what}");
}
}
}
// 8. Resign, then try to destroy the federation execution.
rti.resign_federation_execution(ResignAction::NoAction)?;
println!("[{name}] resigned");
match rti.destroy_federation_execution(FEDERATION) {
Ok(()) => println!("[{name}] destroyed the federation execution {FEDERATION}"),
Err(error)
if error.kind == ExceptionKind::FederatesCurrentlyJoined
|| error.kind == ExceptionKind::FederationExecutionDoesNotExist =>
{
println!("[{name}] did not destroy {FEDERATION}: {}", error.kind)
}
Err(error) => return Err(error),
}
// 9. Disconnect.
rti.disconnect()?;
println!("[{name}] disconnected");
Ok(())
}
/// The text of one parameter: empty when it is missing or is not an HLAunicodeString.
fn parameter_text(values: &ParameterHandleValueMap, parameter: &ParameterHandle) -> String {
match values.get(parameter) {
Some(value) => decode_hla_unicode_string(value).unwrap_or_default(),
None => String::new(),
}
}Run it without a server
The cargo feature embedded puts an RTI inside your program: the same engine as the microrti server,
reached by function calls instead of the network. It is handy for tests and for simulations that run in
one process.
cargo add microrti-client@0.5 --features embedded[dependencies]
microrti-client = { version = "0.5", features = ["embedded"] }In src/main.rs, replace the line use microrti_client::fedpro::DEFAULT_RTI_ADDRESS; with
use microrti_client::embedded::{EmbeddedRti, RtiConfig};and replace main with this one. run stays as it is.
fn main() -> RtiResult<()> {
// An RTI inside this process, reached with the RTI address "embedded:".
EmbeddedRti::new(RtiConfig::default()).register("embedded");
let bob = std::thread::spawn(|| run("bob", "embedded:"));
run("alice", "embedded:")?;
bob.join().expect("the thread of bob panicked")
}EmbeddedRti::new starts the RTI, and register("embedded") makes it the connector for RTI addresses
whose scheme is embedded. The RtiAmbassador::new() inside run finds it through the address
embedded:. alice and bob are now two threads of one process, each with its own RTI ambassador:
cargo run --quiet[alice] connected to embedded:
[bob] connected to embedded:
[alice] created the federation execution Greetings
[bob] the federation execution Greetings already exists
[alice] joined Greetings
[bob] joined Greetings
[bob] sent: Hello from bob (1 of 5)
[alice] sent: Hello from alice (1 of 5)
[alice] heard bob: Hello from bob (1 of 5)
[bob] heard alice: Hello from alice (1 of 5)
[alice] sent: Hello from alice (2 of 5)
[bob] sent: Hello from bob (2 of 5)
[bob] heard alice: Hello from alice (2 of 5)
[alice] heard bob: Hello from bob (2 of 5)
[bob] sent: Hello from bob (3 of 5)
[alice] sent: Hello from alice (3 of 5)
[bob] heard alice: Hello from alice (3 of 5)
[alice] heard bob: Hello from bob (3 of 5)
[bob] sent: Hello from bob (4 of 5)
[alice] sent: Hello from alice (4 of 5)
[alice] heard bob: Hello from bob (4 of 5)
[bob] heard alice: Hello from alice (4 of 5)
[bob] sent: Hello from bob (5 of 5)
[alice] sent: Hello from alice (5 of 5)
[bob] heard alice: Hello from alice (5 of 5)
[alice] heard bob: Hello from bob (5 of 5)
[bob] resigned
[alice] resigned
[bob] destroyed the federation execution Greetings
[alice] did not destroy Greetings: FederationExecutionDoesNotExist
[bob] disconnected
[alice] disconnectedThe two threads start together, so the order of the lines changes from one run to the next. In this run
both had subscribed before the first greeting, and each heard all five of the other’s. The two also
finished together: bob destroyed the federation execution, and alice, a moment later, found it gone
(FederationExecutionDoesNotExist). In other runs one of them sends a greeting before the other has
subscribed, and that greeting is not heard.
Next steps
- Rust client: connection settings, TLS, the
FederateAmbassadortrait, data encoding and errors. - The concepts of HLA, one by one: objects, ownership, time and the rest of HLA.
- Logical time, explained: for federates that advance a simulation clock together.
- An RTI inside your process: more about the
embeddedfeature.