I am working on v2 of my one-man startup (karmakit.io): embedding all of Reddit into vectors. A Linux systemd daemon that embeds Reddit content should not need 44 GB of RAM. Mine did - it climbed to 44 GB over a day, and looked like unbounded, non-reclaimable memory growth.
I could not see any of that until I started logging relevant metrics, so the post starts there: the observability that made the growth visible, the wrong fix I built (an arena cap), the right one (bounding run size in chunks on a non-dynamic model), and the Nix one-liners around it - journalctl as the metrics store, mimalloc reachable from the C++ library.
A companion post, Fastembed Is Fine, Its Model Table Isn’t, covers the loader in front of the engine. This is the engine’s memory.
First, make it visible
The reporting came first, for an unrelated reason: queries over an unindexed Lance dataset fell back to full scans, and I had no way to see which were slow or whether the cache helped.
So the daemon reports structured metrics once a minute and a small Rust CLI prints them as tables: journald stores (already structured, already per-unit), DataFusion queries, comfy-table renders. No exporter, no time-series database, no Grafana - the app, systemd, and one binary.
Generic app + server numbers are all reported by app, because you don’t know in advance which number matters: cgroup v2 cpu.stat, memory.current, memory.peak; /proc/self/io syscall bytes; /proc/stat and /proc/diskstats for box pressure; plus its own numbers: embed queue depth, chunks per interval, Lance cache size and hit rate, LLM calls, Redis INFO. Each is a structured tracing field, so journald keeps key/value pairs, not sentences.
Concretely, the reporting binary is a few hundred lines and the pipeline is deliberately dumb:
journalctl -o json → poller.jsonl → tall parquet (DataFusion) → comfy-table
The useful trick is the tall intermediate table: one row per (entry, field, value), carrying both the text and the parsed number, so every metric - including ones added next month - is queryable with static SQL and no dynamic columns:
SELECT field AS gauge, min(num) AS min,
round(median(num), 2) AS p50,
round(quantile_cont(num, 0.9), 2) AS p90,
max(num) AS max
FROM payload
WHERE field <> 'message'
GROUP BY field
That’s conceptually Prometheus + node_exporter + Grafana, or Vector + Loki - emit, store, query - except just fetch logs && logs -- live-reddit/poller.jsonl reuses infrastructure I already have.
The report has one block per subsystem - health warnings, API quota, the embed queue, the check scheduler, Redis, the Lance caches, host usage, LLM calls. Each is a summary over the window followed by the same gauges per minute (after the fix; before it, that memory row simply climbed):
host
┌─────────────────┬────────┬────────┬────────┬────────┐
│ gauge │ min │ p50 │ p90 │ max │
├─────────────────┼────────┼────────┼────────┼────────┤
│ app cpu % │ 45.85 │ 49.38 │ 51.58 │ 54.02 │
│ app mem GB │ 13.12 │ 18.51 │ 19.27 │ 19.83 │
│ app mem peak GB │ 13.73 │ 19.64 │ 20.03 │ 20.03 │
│ app read MB/s │ 115.97 │ 157.83 │ 176.75 │ 186.76 │
│ app write MB/s │ 0.01 │ 0.04 │ 0.08 │ 0.08 │
│ box cpu % │ 46.77 │ 49.75 │ 51.97 │ 54.30 │
│ box read MB/s │ 0.00 │ 0.00 │ 0.00 │ 0.00 │
│ box write MB/s │ 0.35 │ 0.66 │ 1.35 │ 1.68 │
└─────────────────┴────────┴────────┴────────┴────────┘
┌──────────┬───────────┬────────────┬───────────────┬────────────────┬───────────┬───────────────┬────────────────┐
│ time │ app cpu % │ app mem GB │ app read MB/s │ app write MB/s │ box cpu % │ box read MB/s │ box write MB/s │
├──────────┼───────────┼────────────┼───────────────┼────────────────┼───────────┼───────────────┼────────────────┤
│ 23:10:31 │ 49.97 │ 18.69 │ 176.52 │ 0.03 │ 51.04 │ 0.00 │ 0.58 │
│ 23:11:31 │ 51.98 │ 18.53 │ 164.35 │ 0.07 │ 52.28 │ 0.00 │ 0.68 │
│ 23:12:31 │ 49.84 │ 18.47 │ 140.35 │ 0.02 │ 50.83 │ 0.00 │ 0.47 │
│ 23:13:31 │ 54.02 │ 19.18 │ 139.92 │ 0.04 │ 54.30 │ 0.00 │ 1.39 │
│ 23:14:31 │ 49.72 │ 18.13 │ 137.85 │ 0.01 │ 50.69 │ 0.00 │ 0.35 │
└──────────┴───────────┴────────────┴───────────────┴────────────────┴───────────┴───────────────┴────────────────┘
embedding
┌─────────────────┬───────────┬───────────┬───────────┬───────────┐
│ gauge │ min │ p50 │ p90 │ max │
├─────────────────┼───────────┼───────────┼───────────┼───────────┤
│ embedded_chunks │ 644.0 │ 780.0 │ 908.0 │ 1030.0 │
│ pending │ 2561559.0 │ 2565579.0 │ 2568119.0 │ 2568716.0 │
└─────────────────┴───────────┴───────────┴───────────┴───────────┘
┌──────────┬─────────────────┬─────────┐
│ time │ embedded_chunks │ pending │
├──────────┼─────────────────┼─────────┤
│ 23:10:26 │ 773 │ 2561021 │
│ 23:11:31 │ 774 │ 2561000 │
│ 23:12:38 │ 776 │ 2560689 │
│ 23:13:41 │ 659 │ 2560571 │
│ 23:14:49 │ 709 │ 2560407 │
└──────────┴─────────────────┴─────────┘
The problem announced itself: a memory usage line that kept growing. Profiling came later, and dhat came last of all - it needs a hypothesis plus a feature flag, and by then the question had narrowed to “whose heap is this?”.
The symptom, and the wrong suspect
One Rust binary on a Hetzner box (12-core Ryzen 9 3900, 125 GB, NixOS, systemd unit from a declarative git repo): it polls Reddit, judges whether a post is worth embedding, and embeds the accepted ones through ONNX Runtime via fastembed, with a spec from my patterns library.
My first instinct was a leak in my own code. I swapped allocators (mimalloc) and nothing changed, because Rust’s heap was never the problem. That was the confusing part: a safe language, no unsafe of mine, and RSS growing without bound. The answer is boring once measured - the growth happened across the FFI boundary, in C++.
Getting a heap profiler onto the box was one word. The app is a flake input, and the profiling build is just another package inside it:
# reddit_v2/flake.nix
poller-dhat = craneLib.buildPackage (commonArgs // {
pname = "reddit-poller-dhat";
cargoBuildExtraArgs = "--bin poller --features dhat-heap";
# dhat backtraces need symbols: keep them, and skip the fixup strip
CARGO_PROFILE_RELEASE_DEBUG = "1";
dontStrip = true;
});# nix-servers/modules/apps/reddit_poller.nix
ExecStart = pkgs.lib.getExe reddit.poller; # reddit.poller-dhat to profile
The flag itself is a plain Cargo feature, dhat-heap = ["dep:dhat"], so the profiling build is a second package rather than a mutation of the service one - the normal poller stays reproducible and unprofiled, and both live in the same flake output.
A couple of hours of that build gave:
| measurement | value |
|---|---|
| Rust heap peak (dhat) | 910 MB |
| process RSS at the same moment | 18.5 GB |
| RSS immediately after dropping the sessions | 4.3 GB |
95% of the memory was not mine, and it was released the moment the ONNX sessions dropped - the signature of a C++ allocator holding buffers. The gauges are what let me see the climb, and the drop after it.
ONNX Runtime is supposed to keep memory. The question is why it kept growing.
Three attempts
ONNX Runtime’s CPU provider allocates through a best-fit arena that keeps freed blocks instead of returning them to the OS - great for a request-scoped process, pathological for a daemon whose tensor shapes keep changing. There were three ways to hold that down, and I tried them in the obvious order.
1. Turn the arena off. DisableCpuMemArena, and RSS settled around 5 GB and stayed there. Throughput halved. Paying 2× speed for a memory ceiling is a bad trade, so that was out.
2. Cap it. I exposed max_mem in the patterns loader: build an OrtArenaCfg, register it through CreateAndRegisterAllocatorV2, cap the CPU arena at 35 GB. Memory went flat - and hours later the backfill died:
The cap is a hard ceiling with no fallback path - AllocateRawInternal ends in ORT_THROW - so one 5 GB tensor with 1.9 GB of budget left is a crash.
3. Use the natural knob. What decided that a 5 GB buffer was needed was the number of chunks per ONNX run. That knob exists, but only some models let you turn it - which is the next part.
Dynamic quantization can’t be batched at all
Fastembed refuses to split a dynamic-quantized call, and its error message is the best documentation on the subject:
“Dynamic quantization cannot be used with batching. This is due to the dynamic quantization process adjusting the data range to fit each batch, making the embeddings incompatible across batches.”
Dynamic quantization computes activation scales per run, so the same text in two batches yields two slightly different vectors. Fine for a classifier; fatal for a shared index - doubly so when you store one sign bit per dimension, where tiny perturbations flip bits. For a dynamic model page = run: no ceiling, no independent control. That is why memory blew up.
The real fix, three layers deep:
- Use a non-dynamic artifact.
model_q4.onnxis weight-only int4 (MatMulNBits): activations stay fp32, nothing rescales per run, so it’s batch-invariant and slicing is legal. Same for fp32 and static int8; only dynamic activation quantization breaks it. - Cap chunks per run. Now possible, because the model is batchable: patterns talks to fastembed under the hood and now passes the chunk ceiling through.
with_batch_sizeonEmbeddingSpec, anensure!rejecting the cap for dynamic specs at load. - Delete the arena ceiling. With appetite bounded, the cap did nothing but convert growth into a crash. The arena still registers exact-size growth (
kSameAsRequestedinstead of doubling), it just has no maximum.
Numbers
| uncapped, dynamic int8, page = run | arena off, dynamic int8 (naturally capped) | q4, 64 chunks/run + MemoryHigh 24G | |
|---|---|---|---|
| RSS | 44.4 GB and growing | ~5 GB, fluctuating | 18-19 GB |
| single worst request | 5-7 GB | small | ≤ ~0.8 GB |
| throughput | ~650-770 chunks/min | ~half | ~776 chunks/min |
| just if you cap it | hard cap below appetite: ORT_THROW, restart | nothing to cap, the allocator stops hoarding | soft cap only: reclaim + throttle, no kill |
The q4 column is not “q4 alone”: inside ONNX Runtime the arena has no ceiling any more, so the only cap left is the cgroup one, which is soft by nature. What holds the process near 19 GB is that soft limit (next section).
Guardrail: a soft cap only exists for RAM
With the arena ceiling gone there is no in-process tripwire, which is fine: the kernel has something ONNX Runtime doesn’t, pressure before the wall. MemoryHigh is a cgroup v2 soft limit - above it the kernel reclaims and throttles, no kill.
# nix-servers/modules/apps/reddit_poller.nix
systemd.services.reddit-poller = {
wantedBy = ["multi-user.target"];
serviceConfig = {
ExecStart = pkgs.lib.getExe reddit.poller;
Restart = "always"; # a crash is a restart, not an outage
RestartSec = 10;
# soft cap: reclaim pressure, not an allocator hard fail
MemoryHigh = "24G";
};
};| control | when exceeded | outcome |
|---|---|---|
| arena cap (removed) | on any big allocation | ORT_THROW, process exits |
MemoryHigh | gradually | reclaim + throttle, keeps running (slower during reclaim batch) |
This is why GPU tuning looks different: discrete VRAM isn’t reclaimable, so the ceiling has to live inside the allocator (gpu_mem_limit, trt_max_workspace_size) and the batch is sized to fit. The CPU has a soft lever, so we use the kernel’s.
ONNX Runtime’s memory-tuning notes also suggest preloading mimalloc on Linux. The Rust mimalloc crate doesn’t help: it only replaces Rust’s allocator, while the churn happens in the C++ library past the FFI boundary. That is why it has to be LD_PRELOAD, which normally means hunting for a shared object. On NixOS the store path is a build-time value:
# nix-servers/modules/apps/reddit_poller.nix, inside the same serviceConfig
Environment = [
"EMBED_MODEL_DIR=/var/cache/reddit-poller/models"
"LD_PRELOAD=${pkgs.mimalloc}/lib/libmimalloc.so"
"EMBED_THREADS=12"
"EMBED_BATCH_CHUNKS=64"
...
];The checklist
- Reject the wrong quantization up front. Dynamic activation quantization can’t be bounded: run size is whatever the page happened to contain, and forcing a smaller batch either errors or yields vectors that are not comparable with each other. Stick to weight-only (int4/int8), statically calibrated or the original fp32 artifact - all batchable, fp32 just slower.
- Bound the run, not the ceiling. Peak memory follows run size (
chunks × heads × seq²), so a smaller run means a smaller appetite. A ceiling never reduces the appetite; it only decides whether the excess turns into an error or into swap. - Get the growth strategy right.
kNextPowerOfTwodoubles regions and keeps them;kSameAsRequestedgrows by exactly what was asked - registering any arena config is what selects it. - Put the guard where the failure is soft. A cgroup throttles; an allocator throws.
Most of the items above are enforced by code rather than discipline. The loader I use, patterns, sits on top of fastembed and accepts only sensible combinations: a pinned artifact, an explicit pooling and quantization mode, and a chunk cap that it refuses to apply to a dynamic-quantized model. Choose the wrong pair and the load fails with the reason, so the mistake surfaces in an integration test.
Written with LLM assistance; the config is real and really deployed.