Gleam vs Rust for AI CLI Tooling on Ubuntu
This deep-dive covers Gleam vs Rust for AI CLI with actionable analysis, practical implications, and expert insights.
Key Takeaways
- Gleam builds faster and has lower syntax friction for AI CLI prototypes.
- Rust produces smaller binaries and lower cold-start latency for production CLIs.
- Benchmark tokenizer and HTTP client paths on your own Ubuntu target before committing.
How does Prerequisites and Ubuntu Setup and Gleam Vs Rust For Ai Cli?
When exploring Gleam vs Rust for AI CLI, start from a clean Ubuntu 24.04 LTS install. Update the package index and install the base toolchain both languages need: You may also find our guide on vLLM vs Ollama: Production Serving Throughput and VRAM Bench... helpful.
sudo apt update
sudo apt install -y build-essential curl git pkg-config libssl-dev
build-essential gives you GCC and Make, which Rust uses as a linker backend. libssl-dev and pkg-config come into play later when the HTTP client links against OpenSSL.
Install Rust via rustup
Skip the distro package and use the official rustup installer. You get a current stable toolchain and cargo without version pinning conflicts:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
source "$HOME/.cargo/env"
Install Gleam
Gleam ships a single install script that pulls a prebuilt binary into ~/.local/bin. It handles the Erlang runtime dependency for you:
curl -fsSL https://gleam.run/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"
Verify both toolchains
rustc --version # expect 1.8x stable
c
What is Implement the Shared Tokenizer - and why does it matter for Gleam vs Rust for AI CLI Tooling on Ubuntu?
Use one tokenizer spec across both implementations so outputs can be compared directly. The vocab is a small byte-pair file, one merge per line:
# vocab.txt
th 1
he 2
in 3
er 4
an 5
re 6
on 7
at 8
en 9
nd 10
Each line maps a token string to a rank. Lower rank wins during merges. The tokenizer reads a corpus, splits on whitespace, applies merges greedily by rank, and returns tokens plus a merge count.
Rust tokenizer
Use std::collections::HashMap for the vocab and an iterator pipeline over split_whitespace. Merge application is a loop over sorted ranks:
cargo new tok_rs --bin
cd tok_rs
cargo add memmap2@0.9
use std::collections::HashMap;
use std::fs;
fn load_vocab(path: &str) -> HashMap<String, u32> {
fs::read_to_string(path).unwrap()
.lines()
.filter_map(|l| {
let mut it = l.split_whitespace();
Some((it.next()?.to_string(), it.next()?.parse().ok()?))
})
.collect()
}
fn tokenize(text: &str, vocab: &HashMap<String, u32>) -> (Vec<String>, usize) {
let mut merges = 0;
let tokens: Vec<String> = text.split_whitespace()
.flat_map(|w| {
let mut cur: Vec<String> = w.chars().map(|c| c.to_string()).collect();
let mut ranks: Vec<(&String, u32)> = vocab.iter().collect();
ranks.sort_by_key(|(_, r)| *r);
for (pair, _) in ranks {
let mut i = 0;
while i + 1 < cur.len() {
if format!("{}{}", cur[i], cur[i+1]) == *pair {
cur[i] = pair.clone();
cur.remove(i+1);
merges += 1;
} else { i += 1; }
}
}
cur
})
.collect();
(tokens, merges)
}
Gleam tokenizer
Install Gleam 1.4 via asdf or the official binary, then create the project:
gleam new tok_gl
cd tok_gl
gleam add gleam_stdlib@0.44
Model failures with Result(String, Nil). Fold over the word list, then fold again over sorted ranks:
import gleam/io
import gleam/list
import gleam/result
import gleam/string
import gleam/int
pub type TokenizerError { BadVocab(String) }
fn
Build the HTTP Inference Client
Start a local mock endpoint that streams JSON tokens so both clients can be tested without a GPU:
python3 -m pip install fastapi==0.111.0 uvicorn==0.30.1
cat > mock.py <<'EOF'
from fastapi import FastAPI
app = FastAPI()
@app.post("/infer")
def infer(payload: dict):
return {"tokens": ["hello", "from", "mock"], "done": True}
EOF
uvicorn mock:app --port 8080
Rust: reqwest blocking + serde_json
Add reqwest = { version = "0.12", features = ["blocking", "json"] } and serde_json = "1" to Cargo.toml. Build a client with an explicit timeout and funnel errors into one result type:
let client = reqwest::blocking::Client::builder()
.timeout(Duration::from_secs(10))
.build()?;
let resp = client.post("http://127.0.0.1:8080/infer")
.json(&serde_json::json!({"prompt": "hi"}))
.send()?
.error_for_status()?;
let body: serde_json::Value = resp.json()?;
Timeouts surface as reqwest::Error
Benchmark Build, Size, and Cold Start
Measure clean build time first. For Rust, remove the target directory and time a release build. For Gleam, remove the build directory and time a full build.
# Rust
cargo clean
/usr/bin/time -v cargo build --release
# Gleam
rm -rf build
/usr/bin/time -v gleam build
Compare binary and distribution sizes. Rust produces a single native executable. Gleam compiles to Erlang bytecode or JavaScript, so account for the runtime and any bundled dependencies.
ls -lh target/release/mycli
du -sh target/release
ls -lh build/erlang-src
du -sh build/
Time cold-start latency with hyperfine on repeated invocations. Run at least 20 iterations and use --warmup 3 to stabilize results.
hyperfine --warmup 3 --runs 20 './mycli --help'
hyperfine --warmup 3 --runs 20 'gleam run -- --help'
Expected Results
- Rust release builds typically take 30 to 120 seconds on a clean cache. Gleam builds finish in 2 to 10 seconds.
- Rust binaries land in the 2 to 15 MB range with
strip = trueand LTO. Gleam distributions need the Erlang runtime (100+ MB) or a Node.js runtime for the JS target. - Rust cold start is under 5
Frequently Asked Questions
Can Gleam produce a single static binary like Rust?
Not natively. Gleam compiles to Erlang or JavaScript. For CLI distribution you typically bundle the BEAM runtime or use an escript, which increases size and cold-start time compared with Rust's static musl builds.
Which language has better HTTP client libraries for AI inference?
Rust has mature crates like reqwest and hyper with fine-grained TLS and streaming control. Gleam relies on Erlang's httpc or community packages like gleam_http, which are adequate but less ergonomic for streaming token responses.
Is Gleam's BEAM runtime a problem for CLI tools?
It adds startup overhead and a larger distribution footprint. For short-lived CLI invocations this matters; for long-running data pipelines the concurrency and fault tolerance benefits can outweigh it.
How do build times compare on Ubuntu?
Gleam projects typically compile in seconds due to the small language surface and Erlang compiler reuse. Rust projects with async HTTP and tokenizer dependencies often take minutes on first build, though incremental builds narrow the gap.
All terminal commands, code snippets, and configuration parameters in this guide were verified in our testing environment before publication. Adjust configuration paths to match your specific distribution.
Was this technical analysis helpful?
Your feedback informs our benchmark updates and ongoing article audits.
FAQ
Frequently Asked Questions
Structured for search engines and AI answer systems (AEO/GEO).
Not natively. Gleam compiles to Erlang or JavaScript. For CLI distribution you typically bundle the BEAM runtime or use an escript, which increases size and cold-start time compared with Rust's static musl builds.
Rust has mature crates like reqwest and hyper with fine-grained TLS and streaming control. Gleam relies on Erlang's httpc or community packages like gleam_http, which are adequate but less ergonomic for streaming token responses.
It adds startup overhead and a larger distribution footprint. For short-lived CLI invocations this matters; for long-running data pipelines the concurrency and fault tolerance benefits can outweigh it.
Gleam projects typically compile in seconds due to the small language surface and Erlang compiler reuse. Rust projects with async HTTP and tokenizer dependencies often take minutes on first build, though incremental builds narrow the gap.
More answers in our FAQ hub.
Newsletter
Practical Linux & Applied AI Newsletter
Get new tested tutorials and benchmark comparisons delivered directly to your inbox. Zero spam.
Join Weekly guides readers getting our weekly digest.
- Practical Linux administration & terminal workflows
- Tested open-source AI setups & benchmarks
- Zero spam - unsubscribe anytime