Rewriting my health calculator site in Rust + WebAssembly
By Cowboy ·
I run calculateyourhealthdata.online, a set of free health calculators: calories (TDEE), macros, BMI, water, protein, body fat, waist-to-height ratio, a prediabetes risk test and a child BMI-percentile calculator. The first version ran on Deno Deploy. When that platform started winding down and then suspended the app for exceeding its usage limits, I rebuilt the whole thing as a static site with the math in Rust, compiled to WebAssembly.
This post covers how it's put together, the bugs the rewrite turned up, and what it costs to run (nothing, apart from the domain).
The shape of it
It's one Cargo workspace with three crates:
crates/
health/ pure math: plain Rust, no dependencies, unit tests
health-wasm/ a thin cdylib that exports the math to the browser
site/ a static site generator that writes every HTML page
web/app.js ~400 lines of glue: read the form, call wasm, fill in results
cargo test runs the math tests. build.sh builds the wasm module, runs the generator, and drops everything in dist/. There's no server. Every calculation happens in the visitor's browser, so nothing they type ever leaves their device.
No wasm-bindgen
The browser side needs exactly one thing from Rust: "here are some numbers, give me some numbers back." For that, wasm-bindgen and its generated JS felt like more machinery than the problem needs. So the exports are plain extern "C" functions that take numbers and return a pointer to a static array of f64s:
static mut OUT: [f64; health::Results::N] = [0.0; health::Results::N];
/// Returns a pointer to `Results::N` f64s, or 0 if the input is invalid.
#[no_mangle]
pub extern "C" fn calculate(
age: f64, weight_lb: f64, height_in: f64, sex: u32,
goal_weight_lb: f64, activity: u32, deficit: f64,
) -> usize {
match health::calculate(/* build an Input from the args */) {
Some(r) => unsafe {
// Single-threaded wasm: nothing else can touch OUT.
let out = &mut *core::ptr::addr_of_mut!(OUT);
*out = r.to_array();
out.as_ptr() as usize
},
None => 0,
}
}
On the JS side it's WebAssembly.instantiateStreaming, a call, and a Float64Array view over the module's memory:
const ptr = wasm.calculate(age, weightLb, heightIn, sex, goalLb, activity, deficit);
if (!ptr) return showError("Please check your numbers.");
const vals = new Float64Array(wasm.memory.buffer, ptr, FIELDS.length);
FIELDS.forEach((name, i) => (results[name] = vals[i]));
The obvious risk is the Rust array order and the JS names drifting apart. They can't, because JS never hard-codes the list. Each result struct has a FIELDS constant, and the site generator writes it into app.js at build time:
impl Results {
pub const N: usize = 25;
pub const FIELDS: [&'static str; Results::N] =
["bmr", "bmi", "category", "tdee", /* … */];
}
let js = fs::read_to_string("web/app.js")?
.replace("/*FIELDS*/", "ed(health::Results::FIELDS))
.replace("/*CM_PER_IN*/", &format!("{:?}", health::CM_PER_IN));
Category labels ("Overweight", "Healthy weight", …) and the unit-conversion constants get injected the same way, so Rust is the single source of truth. Each newer calculator (body fat, waist, prediabetes, child BMI) is its own small export following the same pattern.
With opt-level = "s", LTO, one codegen unit, panic = "abort" and strip, the whole module is about 66 KB, or 38 KB compressed on the wire. Nearly 20 KB of that is a CDC data table I'll get to below. A full calculator page (HTML, CSS, JS and wasm) is around 52 KB compressed. One calculate call takes roughly 0.1 µs, so speed was never going to be the issue.
A small static site generator
The pages are written with maud, which turns HTML into a Rust macro that's checked at compile time. Every calculator page is just data:
Calc {
path: "/body-fat-calculator",
title: "Body Fat Calculator — US Navy Tape Measure Method",
h1: "Body Fat Calculator",
fields: &[F::Units, F::Sex, F::Height, F::Weight, F::Neck, F::Waist, F::Hip],
cards: &[C::BodyFat, C::Bmi],
how: &["This calculator uses the US Navy circumference method…"],
faq: &[("How do I measure my neck, waist and hips?", "…")],
},
From that one entry the generator builds the form, the result cards, the "How it works" and FAQ sections, the schema.org JSON-LD for search engines, the header dropdown, the footer links, the "More calculators" grid and the sitemap. Adding a calculator means writing the math with tests, adding a Calc entry and wiring up a few lines of JS. Because Field and Card are enums, forgetting to handle a new input is a compile error, not a blank spot on the page.
The rewrite found real bugs
Moving the math into a tested Rust crate meant checking every formula against its source. Two problems turned up in the original version:
- The activity multipliers were wrong. TDEE is BMR times an activity factor. The standard factors are 1.2 (sedentary) up to 1.9 (very active), but the old version used 1.0–1.5. That undercounted everyone's calories by roughly 17–23%, depending on activity level. A test now pins a reference case: 80 kg, 180 cm, 30-year-old man, moderately active → BMR 1,780, TDEE 2,759.
- It could recommend dangerously low calorie targets. A smaller person picking a big deficit could be told to eat around 970 kcal a day. The site now warns below 1,200 kcal (women) and 1,500 kcal (men).
The newer calculators are tested against published reference values. The child BMI calculator uses the CDC 2000 growth-chart tables (the LMS method). Its tests check that the computed percentiles land on the CDC's own published 5th, 50th, 85th and 95th percentile values across ages for both sexes. The data table is embedded with include_str!, and its SHA-256 was checked against the copy on cdc.gov.
Hosting: Cloudflare Workers static assets
The dist/ folder is served by Cloudflare Workers static assets on the free plan, and Cloudflare's own build service does the building. Its build image doesn't ship Rust, so the build script installs a minimal toolchain first:
if ! command -v cargo >/dev/null 2>&1; then
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
| sh -s -- -y --profile minimal --target wasm32-unknown-unknown
. "$HOME/.cargo/env"
fi
cargo test --workspace
bash build.sh
A failing test fails the deploy. Every branch gets its own preview URL, which is how each new calculator gets checked in a real browser before it goes live. No API tokens or CI secrets are involved. The ongoing cost is the domain name.
What I'd do differently
- The static
OUTbuffer is a shortcut. It's fine for a single-threaded module where JS copies the values out before the next call. It wouldn't survive threads, and recent Rust warns about taking references to astatic mut, henceaddr_of_mut!. - Unit handling lives at the edges. The Rust math works in pounds and inches, and JS converts metric input before calling in. That keeps the formulas identical to their published (mostly US) sources. The catch is that converting at the edge is something you have to keep remembering to do.
The source
The repository is private for now. Ask in the comments if you'd like to see more of any particular piece.
Try the calculators: all-in-one, TDEE, body fat, child BMI and more.