My Elixir app uses two Rust NIFs built with Rustler: one that parses and discovers feeds, and one that extracts readable articles from HTML. When I checked priv/native, they weighed 9.1 MB and 6.5 MB. That seemed like a lot for what they do.
Neither crate had a [profile.release] section, so both were built with Cargo's defaults. Those defaults optimise for speed and keep symbols, which isn't necessary for a NIF that mostly waits on I/O.
The fix
Add this to the Cargo.toml of each crate:
[profile.release]
opt-level = "s" # optimise for size
lto = true # whole-program dead-code removal
codegen-units = 1
strip = "symbols"
What each setting does:
opt-level = "s"tells the compiler to favour a smaller binary over the fastest possible code.lto = trueenables link-time optimisation across crates, so unused dependency code can be removed.codegen-units = 1gives the optimiser a single unit to work on. Builds are slower, but the result is smaller.strip = "symbols"removes symbol information from the shared library.
The result
| NIF | Before | After |
|---|---|---|
feed_parser.so |
9.1 MB | 4.7 MB (about 48% smaller) |
article_extractor.so |
6.5 MB | 5.0 MB (about 23% smaller) |
The feed parser benefited the most. It pulls in reqwest with rustls and aws-lc-rs through its HTTP support, leaving a lot of code for LTO to prune. The article extractor has no TLS stack, so there was less to remove.
A gotcha: don't use panic = "abort"
The usual advice for tiny Rust binaries includes panic = "abort". I tried it, but rustler failed to compile. Rustler relies on unwinding to turn a Rust panic into an Erlang error. Even if it had compiled, aborting would take down the entire BEAM VM instead of failing just one call, which is exactly what you don't want in a NIF.
Verifying it
"It compiles" isn't enough for a NIF, so after mix compile --force I called the functions with realistic input:
extract_article/2on a small HTML page returned an article with the correct title and markdown.parse_feed/1parsed an RSS document into a feed struct.find_feeds/2found a feed advertised in a<link>tag.- The existing test suite for both modules still passed.
I didn't benchmark the speed difference. opt-level = "s" can be slightly slower than the default, but both NIFs are dominated by network and parsing work rather than tight loops, so I don't expect it to matter. If your NIF is CPU-bound, measure before switching.
What's next
Profile settings only go so far. The biggest remaining cost in the feed parser is likely the HTTP and TLS stack. If fetching moved to the Elixir side and only parsing stayed in Rust, the TLS feature could be disabled entirely. A tool like cargo bloat --release --crates will show where the remaining bytes go.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.