Tuning under load
StoatFlow ships with measured defaults that work for most topologies, and the parts that need to adapt to your workload โ commit cadence and epoch size โ self-tune within the bounds you set. This page starts with goal recipes โ a configuration per goal, with its measured trade-off โ and then covers the knobs you set: lane count, the commit-cadence bounds, the memory and uncommitted-state limits, sizing the container's memory, and running in a small pod. Each knob section starts from a symptom so you know when to reach for it.
For the why behind these mechanics, see Lanes and parallelism, Exactly-once, and State and thread safety. For where each value comes from and how it's merged, see the Configuration model and Defaults and the memory plan.
Before you tune
Tune one thing at a time, and tune against a representative load, not a synthetic burst. The defaults are deliberately conservative; most workloads need at most one or two of the knobs below. Always confirm the symptom first โ reach for /metrics and the /debug/barriers endpoint (see REST API) rather than guessing.
stoatflow.* and an environment-variable override โ the YAML path in capitals, every . and - as _ (stoatflow.commit-barrier.max-interval-ms is STOATFLOW_COMMIT_BARRIER_MAX_INTERVAL_MS). The full list โ with types, ranges, and overrides โ is in the Configuration reference.Goal recipes
The defaults are the balanced choice: two platform-thread lanes per sub-topology on pods up to 11 cores, zstd-compressed output, and a self-tuning commit cadence. When you have a specific goal, start from the recipe below. Each was measured on StoatFlow's benchmark apps (a stateless pipeline, a multi-source stateless topology, word-count, and a five-table join chain) on 8-core pods, against the defaults; your workload's numbers will differ, the direction should not.
Keys are written as they go into application.yaml, under stoatflow:.
| Goal | Recipe | Measured trade-off |
|---|---|---|
| Low latency, stateless or exactly-once | commit-barrier.interval-ms: 250, commit-barrier.min-interval-ms: 130, commit-barrier.interval-factor: 1.2 | P99 โ8 to โ17 % on the stateless apps under exactly-once, at the same CPU. More commits per second. |
| Low latency, stateful, eager emission | lanes.count at half the cores (4 on 8 cores) | P99 โ10 to โ14 %, CPU +23 to +49 % (word-count). |
| High throughput, CPU-bound stateful | Raise lanes.count toward the cores โ or withNumberOfLanes(n) for one sub-topology โ when consumer lag grows while the CPU is idle. The signal: stoatflow.lane.queue.size near stoatflow.lane.queue.capacity and a rising stoatflow.lane.queue.full.total. | Two lanes topped out word-count at roughly 15,000โ20,700 lines/s on 8 cores. Each extra lane costs CPU per record. For comparison, Kafka Streams runs one stream thread by default. |
| Consistent, cheap aggregations | emit.mode: on-barrier and commit-barrier.min-interval-ms: 250, where one update per key per commit is acceptable โ this changes what downstream sees, not just how fast | The best word-count configuration at every load: โ42 % CPU and โ57 % P99 against the defaults at a quarter of the full load. |
| Resource saver, high-volume stateless | kafka.producer โ linger.ms: 50 | โ14 to โ17 % CPU, +11 to +34 % P99. Not a word-count recipe (โ6 %, within noise). |
| Resource saver, high-volume at-least-once output | kafka.producer โ compression.type: lz4 | โ30 % CPU, at 1.8โ2.1ร the output bytes, +23 % P99 and ~1 GB more memory on the multi-source app. Not under exactly-once (P99 ร2.3). JVM only: a native image ships no lz4 support yet. |
| Resource saver, small pod, stateless | lanes.count: 1 | โ3 to โ34 % CPU. P99 doubles as load approaches one lane's capacity. |
| Blocking I/O in user code | Many lanes and lanes.thread-type: VIRTUAL. The thread type applies to every sub-topology's lanes. | Throughput โ lanes รท call latency: a lane blocked on a call processes nothing else. |
| At-least-once, stateless | processing.dispatch-mode: DIRECT, processing.direct-dispatch-threads: 2 โ experimental. processing.dispatch-mode: AUTO picks DIRECT by itself for an eligible stateless at-least-once topology. | 0.80 against 1.06 cores on lane dispatch at 7,000 msg/s (multi-source app). Refused under exactly-once. |
| Large state, RocksDB-heavy | A larger block cache: the state-heavy memory profile (STOATFLOW_MEMORY_PROFILE, or memoryProfile in the build), or a larger container limit. Confirm with the block-cache verdict first (Sizing memory), and test a restart into a backlog on the smaller heap. | A 4ร larger cache measured โ17 % CPU on the join chain at the same latency, with the cache full at both sizes. |
| Resource saver, small low-rate app | The lean memory profile in a small container โ 256 MiB stateless, 512 MiB stateful with a few stores on the JVM โ or the native image at half that. See Small pods. | At ~50 records/s the JVM apps stayed at 160โ215 MiB resident, the native ones at 16โ55 MiB. Higher rates were not measured at these sizes. |
The two producer recipes go in the producer map, not as flat keys:
stoatflow:
kafka:
producer:
linger.ms: 50
Change one recipe at a time and confirm the effect on your own load โ see Watching the effect.
Lane count vs cores
Knobs: stoatflow.lanes.count โ default max(2, CPU cores / 4); stoatflow.lanes.thread-type โ default PLATFORM.
Lanes are the unit of per-key parallelism: every record is routed to a lane by its key, and each lane processes its keys in order on its own thread. The default is deliberately small โ 2 lanes per sub-topology on pods up to 11 cores, 3 at 12, 4 at 16 โ on platform threads. Measured from 1.5 to 8 CPU cores, two lanes were the cheapest configuration at every limit, and as fast as more lanes on stateless work; every extra lane costs CPU per record. A per-sub-topology withNumberOfLanes(n) (on Consumed, Grouped or Repartitioned) overrides the count for that sub-topology.
stoatflow:
lanes:
count: 16
How to size it:
- CPU-bound processing (pure transforms, local aggregation): start at the default. Raise it toward the core count only when consumer lag grows while the CPU has headroom โ two lanes can cap a CPU-bound stateful sub-topology (see High throughput in the goal recipes).
- I/O-bound processing (enrichment calls, blocking lookups, external APIs): a lane blocked on a call processes nothing else, so go well above the core count and switch to virtual threads, which park cheaply while blocked โ
lanes.countat 4รโ8ร cores withlanes.thread-type: VIRTUAL. This is the case where raising the lane count pays off most. - Few distinct keys: lanes only help if keys spread across them. If your traffic is dominated by a handful of hot keys, extra lanes sit idle โ the hot keys still serialize onto their assigned lanes. Fix the key distribution first.
| Symptom | Likely cause | Reach for |
|---|---|---|
| Consumer lag grows while the CPU has headroom, no blocking calls | Too few lanes for a CPU-bound stateful sub-topology | Raise lanes.count toward the core count |
| Cores underused, throughput plateaus, processing involves blocking calls | Too few lanes for an I/O-bound topology | Raise lanes.count (4รโ8ร cores) and set lanes.thread-type: VIRTUAL |
| High CPU, lots of context switching, no throughput gain from more lanes | Over-provisioned lanes | Lower lanes.count toward the default |
| A few keys dominate; most lanes idle | Skewed key distribution, not a lane-count problem | Re-key upstream; lane count won't help |
Record lanes: โฆ names each sub-topology's lane count, the thread type, and where each came from, and a sub-topology with more PLATFORM lanes than CPU cores logs a WARN naming the remedy. See Lanes and parallelism.Lane queue capacity
Knob: stoatflow.lanes.queue-capacity โ default 300.
Each lane has a bounded queue; when a lane fills, the dispatcher applies backpressure. Raise it if you see bursty input stalling dispatch and you have memory headroom; the default is sufficient for steady-state load.
stoatflow:
lanes:
queue-capacity: 500
Commit cadence
StoatFlow commits in epochs โ the work between two commit barriers becomes one Kafka transaction plus one state-store flush (see Exactly-once). The cadence โ how often a barrier fires โ is self-tuning: the engine adapts it within the bounds you configure, so you set the envelope, not the exact interval. The algorithm itself stays in the source; what you control is the floor and ceiling.
The bounds you set:
| Knob | YAML key | What it does |
|---|---|---|
| Seed interval | commit-barrier.interval-ms | Starting interval before the cadence settles |
| Interval factor | commit-barrier.interval-factor | Target interval as a multiple of measured commit duration |
| Minimum interval | commit-barrier.min-interval-ms | Floor โ barriers never fire closer together than this |
| Maximum interval | commit-barrier.max-interval-ms | Ceiling โ barriers never fire further apart than this |
Defaults and StreamsConfig field names for every commit-barrier.* knob are in Engine configuration โ Commit-barrier cadence.
stoatflow:
commit-barrier:
min-interval-ms: 150
max-interval-ms: 5000
interval-factor: 1.5
The trade-off is the classic latency-vs-throughput one:
- Tighter, more frequent commits (lower
max-interval-ms, lowerinterval-factor) reduce end-to-end latency and bound how much work a crash replays โ at the cost of more transaction and flush overhead per record. - Looser, less frequent commits (higher bounds) amortize commit overhead over more records, raising throughput โ at the cost of higher latency and a larger replay window after a restart.
| Symptom | Likely cause | Reach for |
|---|---|---|
| End-to-end latency too high; output lags input | Cadence too loose; records wait for the next barrier | Lower max-interval-ms (and/or interval-factor) |
| Throughput capped; commit overhead dominates a profile | Cadence too tight for the volume | Raise max-interval-ms |
| Output is bursty in lockstep with commits | Working as designed โ output is released at barriers | Tighten cadence if the burstiness hurts downstream |
commit-barrier.timeout-ms is a safety bound, not a cadence knob. It caps how long a commit may take; if a commit stalls past it, the engine aborts the in-flight transaction and the process restarts rather than freezing silently. Don't lower it to force faster commits โ see Probes.Epoch size
You normally don't touch epoch size โ it self-tunes within the bounds above. Two knobs exist for the edges:
| Knob | YAML key | When to use |
|---|---|---|
| Hard cap on records per epoch | commit-barrier.max-epoch-records | Unset by default (no cap) โ set only if you need a deterministic upper bound on epoch size regardless of self-tuning |
| Initial cap before warmup | commit-barrier.initial-max-epoch-records | Lower for conservative startup on heavy-state topologies; -1 for an unlimited first epoch |
stoatflow:
commit-barrier:
initial-max-epoch-records: 1024 # conservative startup for heavy-state topologies
# max-epoch-records: 25000 # optional deterministic ceiling
Memory and uncommitted state
Between commits, a stateful topology accumulates uncommitted state in memory โ the writes buffered since the last barrier, held until the transaction commits (KIP-892 transactional state stores). On topologies where one input record fans out into many state writes (multi-way joins, foreign-key joins, high-cardinality aggregations), this is the value most likely to threaten container memory.
Knob: stoatflow.state.uncommitted-max-bytes โ default unset: derived from the heap, a quarter of the heap ceiling, at least 16 MiB and at most 256 MiB. Every heap of 1 GiB or more gets 256 MiB; an explicit value always wins.
When buffered uncommitted bytes approach this limit, the engine triggers an early commit barrier to flush state and bound peak memory. This is the backstop that keeps a high-fan-out epoch from running the container out of memory. Timer registrations and deletions count toward it as well, on every timer backend, so a topology that registers many timers per record can trigger these barriers even when it has no other state store.
Under exactly-once, output counts as well. While one epoch commits, a processing thread that has already crossed the next barrier holds that epoch's output back until the commit is done, then sends it into the next transaction. A topology with high fan-out and large output records, or with slow commits, can therefore trigger these barriers with no state store at all. While a commit is running, a tripped limit pauses dispatch of new records until the commit completes.
Kafka Streams' statestore.uncommitted.max.bytes sets the same limit, so a ported application keeps its value. Without one, the defaults differ on purpose: Kafka Streams uses a fixed 64 MiB, StoatFlow derives the limit from the heap, because a commit's writes stay in memory until they reach RocksDB while the next epoch's accumulate, and because the limit also caps how large an epoch can grow โ a large heap gets 256 MiB, and a small pod's heap is not half taken by it. Gauges sampled about once a second show how close a topology runs to it: stoatflow.barrier.epoch.uncommitted.bytes is the state total the limit applies to (the timer store included, on every timer backend), and stoatflow.store.uncommitted.bytes breaks it down per store, which tells you which store to look at when memory-pressure commits start. The timer store has no series of its own: its share is the total minus the per-store sum. Under exactly-once, stoatflow.eos.send.buffer.bytes is the output held back during a commit, which the limit counts with the state total. The engine checks its own projection of the next records' cost against the limit, so a commit can fire a little before the gauge reaches it.
stoatflow:
state:
uncommitted-max-bytes: 536870912 # 512 MiB, explicit โ unset, a quarter of the heap (16โ256 MiB)
The global ceiling has two per-store companions under stoatflow.caching: max-estimated-bytes (default 256 MiB per caching store) and max-entries (default unbounded). Exceeding a per-store cap fires the same early commit barrier โ tagged CACHE_PRESSURE on the barrier-trigger metric โ so one hot store can't monopolise the buffer. In practice uncommitted-max-bytes measures a superset and fires first; leave max-entries unbounded unless a specific store must bound its per-epoch key cardinality.
The default against the container with the default balanced memory profile, and starting points for raising it โ never benchmarked. Raise the limit only while memory-pressure barriers end most epochs (the MEMORY_PRESSURE share of stoatflow.barrier.trigger.total) and the heap has room for it. Every byte counts twice: the heap holds the epoch, and the memory plan reserves the same amount beside RocksDB's block cache for the commit's native write batch, so raising the limit also shrinks the cache.
| Container memory limit | Heap (balanced) | Default uncommitted-max-bytes | Starting point |
|---|---|---|---|
| 1 GiB | 512 MiB | 128 MiB | The default: on a small pod the cache needs the memory more |
| 2 GiB | 819 MiB | about 205 MiB | The default |
| 4 GiB | 1434 MiB | 256 MiB | The default: leaves the rest of the heap for the producer's send buffer, your objects and GC |
| 8 GiB | 2048 MiB | 256 MiB | 256โ512 MiB: more room for GC and producer buffers |
| 16 GiB | 3277 MiB | 256 MiB | 512 MiBโ1 GiB, for heavy stateful topologies; the heap-heavy profile or STOATFLOW_HEAP_MB gives more heap |
uncommitted-max-bytes is one of several memory consumers in the process. It does not count the heap's other users โ the Kafka producer's send buffer (buffer.memory, 256 MiB, which lives on the heap), the consumer's fetch buffers, your own objects โ nor RocksDB's native memory (Sizing memory); only the output StoatFlow holds back during a commit counts with it. On small-heap deployments with both heavy state writes and heavy sink output, leave generous headroom and watch container memory before raising it. Defaults and the memory plan draws the plan and the heap's caps to scale against a container, which is the quickest way to see how much of the limit the defaults already spend.| Symptom | Likely cause | Reach for |
|---|---|---|
| Container memory spikes near the limit; OOMKills under load | Uncommitted state per epoch too large for the container | Lower uncommitted-max-bytes, or raise the container limit if you have hardware; read the memory report for which pool is short |
| Very frequent commits; throughput suffers on a stateful topology | Early barriers firing on memory pressure (MEMORY_PRESSURE trigger) or a per-store cache cap (CACHE_PRESSURE trigger) โ the barrier-trigger metric tells you which | Raise uncommitted-max-bytes, or the tripping store's caching.max-estimated-bytes (only if the container has the headroom) |
Exactly-once throughput dips with dispatcher stalls (stoatflow.dispatcher.stall.latency) while the state total is low | Output held during commits passes uncommitted-max-bytes โ a high stoatflow.eos.send.buffer.bytes (high fan-out, large output records, slow commits) โ so dispatch pauses until each commit is done | Raise uncommitted-max-bytes (only if the container has the headroom) |
| Slow time-to-first-commit on a heavy-state topology at startup | First epoch buffering too much before warmup | Lower commit-barrier.initial-max-epoch-records |
Sizing memory
The container's memory limit is the one number you size: the memory plan splits it between the JVM's native memory, the heap, a headroom and RocksDB. The goal is not the largest limit that runs fastest but the smallest at which the container, the heap and the native memory stay comfortable, with a margin for growth and restores โ the block cache may run tight when the read latency it costs is acceptable. The engine's memory report tells you where that is; Right-sizing memory is the procedure around it: a starting size, what to observe and for how long, what each verdict costs, and the alerts.
The memory report
GET /memory (REST API) returns the plan the engine runs on, what each pool used over the last window, a verdict per pool, and two numbers:
fitsMibโ the smallest container limit at which every pool holds what it uses: twice the heap's after-GC peak, the measured native residue (while it is unmeasured โ no cgroup to read, on bare metal or macOS โ the native reserve the plan at that size holds), and the block cache's need plus the memtables' bound ฮฃ with the allocator slack, solved back through the profile's brackets. The cache's need follows its verdict: acomfortableoroversizedcache serves its reads at its size, so it needs what it holds โ its capacity less ฮฃ, at most the working set โ however large the state; atight,starvedorunknowncache needs the working set; with simulated cache points, the smallest simulated size that keeps the best hit ratio. The part of the residue that is the JVM's own memory, which the plan's JVM term covers, is counted once. Above it, more memory buys little.nulluntil the engine has measured.slackMibโ how far the current limit is abovefitsMib.
When the split rather than the size is wrong, a hint says so โ for example "heap oversized and cache starved: try state-heavy", or, for an application with no RocksDB store, heap-heavy or a smaller pod. The hint reads the steady state, where a heap is usually oversized: on a stateful application that headroom is what a restart into a backlog uses, so test a catch-up on the smaller heap before you take the hint (Defaults โ profiles).
The engine samples its signals at the default recording level, cheaply: the heap's occupancy after GC โ each heap pool as the latest collection that covered it left it, so on G1 a young collection's view of the old generation counts too โ and the GC time share (pause time โ a concurrent collector's cycles, ZGC's or Shenandoah's, do not count); the block cache's capacity, usage and data hit ratio (from RocksDB's ticker statistics, which are on by default โ no statistics-enabled needed); the working set, the uncompressed live data in the stores' SST files; the memtables against ฮฃ, write stalls and L0 file counts; and the container's anonymous memory and memory.events from the cgroup. (A native image publishes no heap occupancy after GC, so there the heap verdict reads unknown and fits stays empty.) The report samples from start-up on, a state restore included. While any verdict is tight or starved, it logs one Memory report: โฆ line every 15 minutes โ at INFO, or WARN while the pressure valve is active โ and when a whole window shows the container comfortable with fitsMib at least 25 % below the limit, it says once, at most every six hours, that the application could run in a smaller container.
| Verdict | Heap (after-GC peak, of the ceiling) | Block cache | Memtables | Native residue | Container (anonymous memory, of the limit) |
|---|---|---|---|---|---|
oversized | below 25 % | the working set fits in less than 70 % of its data capacity | โ | โ | โ |
comfortable | 25โ60 % | data hit ratio at least 0.95, or the working set fits | no write stalls, L0 below the slowdown trigger | within its budget (below) | below 85 % |
tight | 60โ80 % | data hit ratio 0.85โ0.95 with the cache full | write stalls, or 20 or more L0 files | up to 1.5 ร the budget | 85โ95 % |
starved | above 80 %, or GC more than 5 % of the time | below 0.85 with the cache full and a working set more than twice its capacity | sustained stalls, or 36 or more L0 files | beyond 1.5 ร the budget | above 95 %, a memory.high or oom event, or the valve active |
A pool without enough signal yet reads unknown. The cache counts as full at 95 % of its capacity, and the hit ratio needs 1,000 lookups in the window โ an application that reads little is judged on its working set; a stall time above 1 % of the window is sustained. These thresholds are a first calibration and may move as more applications are measured. The verdicts, fitsMib, the limit, the residue and the valve steps are also meters โ see Metrics.
Why cache usage alone misleads
An LRU cache fills to its capacity whenever the data is larger, so a full cache says nothing about need: it reads the same at 1 GiB and at 4 GiB. The need shows in the hit ratio at other sizes and in the working set, which is what the cache verdict, fitsMib and the simulated cache points read. Resident memory misleads the other way: it includes native memory no RocksDB statistic reports, which is what the native residue and the container verdict cover.
Two ways to size
| By limit (the default) | By cache (RocksDB first) | |
|---|---|---|
| For | most applications: choose the container, let the plan split it | applications whose read latency depends on a cache size you want to choose and keep, whatever the container |
| Steps | 1. a generous limit; 2. a representative load, with a restart and a restore; 3. read the verdicts and fitsMib; 4. the squeeze | 1. find the cache size from measured hit ratios โ the simulated cache points, or runs at two or three sizes; 2. pin it (stoatflow.rocks-db.memory-mb, or RocksDbMemory.absolute in code); 3. ask GET /memory/what-if?cache=<MiB> for the limit that holds it; 4. set that limit and run the same load |
| What moves | the limit; the plan re-splits it | the limit only; the cache stays as pinned |
Both end with the same check, over a window that includes the daily peak, a restart and a restore: the container verdict comfortable, no pool starved โ a starved block cache only as a choice you made โ the native residue no worse than tight and not growing, and no memory.high or oom event.
The second way is the one Kafka Streams users know, where the RocksDB budget is a RocksDBConfigSetter and the container is sized around it. Here the arithmetic from the cache to the limit is the what-if's, so a pinned cache cannot overcommit the container unnoticed โ and if it does, the engine WARNs at start.
The squeeze
Below fitsMib, how far is safe depends on how skewed your reads are, which the engine cannot see. Find it by squeezing:
- Run a representative load, with a restart and a restore, at a generous limit.
- Read
fitsMiband the verdicts. - Step the limit down by about 15 % at a time, as long as the container stays
comfortable, no pool turnsstarved, the native residue stays no worse thantight, and the P99 holds. - Keep one step above the last good one as margin.
Each step's cost shows directly in the data hit ratio and the P99. The simulated cache points show the hit ratio at nearby cache sizes without the steps.
The what-if
GET /memory/what-if runs the plan's own function โ the one the engine ran at start, with this topology's databases, ฮฃ, background jobs and epoch batches โ on another input. It changes nothing.
| Query | Answers |
|---|---|
?limit=4096 | the split at another container limit: heap, RocksDB pool, reserve, cache, ฮฃ and the WARNs it would raise โ "what would a 4 GiB pod give this app?" |
?cache=2048 | the smallest limit whose plan gives at least this block cache, and the split there โ "I want a 2 GiB cache: which limit?" |
?heap=1536 | the smallest limit whose brackets give at least this heap |
&profile=state-heavy | any of the above under another memory profile |
Sizes are MiB, and a question asks for at most one of limit, cache and heap; anything else answers 400. With no size, the answer is the plan the engine runs on โ the one GET /memory shows, its heap the one the JVM was given (also in a container with no limit); before the application has started, 503. For the 15-store example of the plan table, ?cache=2048 answers a limit of 4,955 MiB, with a 1,562 MiB heap and a 2,633 MiB RocksDB pool. Each answer also carries what the engine has measured that bears on it: the data hit ratio at the current capacity, the simulated hit ratio nearest the asked cache, and the residue's peak.
curl -s 'localhost:8080/memory/what-if?cache=2048'
curl -s 'localhost:8080/memory/what-if?limit=8192&profile=state-heavy'
Simulated cache points
Knob: stoatflow.rocks-db.simulated-cache.enabled โ default false.
RocksDB's simulated cache wraps the block cache and counts the hits and misses a cache of another size would have had, without allocating that memory. With the points on, the engine steps it through ยฝร, 1ร, 2ร and 4ร the current capacity, one 15-minute window each โ the first five minutes of each step warm the simulated cache up, the rest measures it โ and keeps the last hit ratio for each size: four points of the hit-ratio curve around the current size, the current one included, so fitsMib can find that the cache the application has is enough. GET /memory lists them under simulated, stoatflow.memory.cache.simulated.hit.ratio{capacity} publishes them, and fitsMib and the what-if use them: the working set alone overstates the cache a skewed workload needs, so fitsMib takes the smallest simulated size whose hit ratio is within 0.01 of the best simulated one. The simulated points are compared with each other, never with the real cache's ratio: they count every block lookup, the real cache's ratio data blocks alone.
Every block access also looks up the simulated cache, which is why the points are opt-in. The simulated cache also keeps an entry for every block a cache of its size would hold โ at the 4ร point four times the real cache's blocks, about 100 bytes each โ and the plan reserves that memory while the points are on: with 4 KiB blocks about 10 % of the cache, shown as simulated cache in the start-up line's native reserve and as simulated-cache in GET /memory's plan. The cache is that much smaller while the points are on; turning them off gives it back. They work on both RocksDB backends, on Linux (glibc, x86-64 and aarch64) and macOS; anywhere else โ a musl-based image, another operating system โ the engine logs one WARN at start and runs without them.
stoatflow:
rocks-db:
simulated-cache:
enabled: true
The native residue
The kernel kills a container on its resident memory, not on what the JVM accounts. RocksDB allocates outside the heap and outside the JVM's native-memory tracking, and so do the Kafka clients' native compression libraries. The engine computes what nobody accounts for:
residue = the cgroup's anonymous memory
โ heap committed โ JVM non-heap committed โ direct and mapped buffers
โ RocksDB's accounted memory (block cache usage, table readers)
and publishes it as stoatflow.memory.native.unaccounted.bytes. Its verdict reads it against a budget: the plan's native reserve and allocator slack, plus the part of the JVM's native share that the JVM's own memory pools do not report โ the garbage collector's structures, thread stacks โ since the residue carries that part too. A stateless application in a container with a memory limit has no RocksDB pool, so its budget is that JVM part alone, and it gets a residue verdict as well. Within the budget the residue is comfortable, up to 1.5 ร the budget tight, beyond that starved. A residue that keeps growing is the allocator's fragmentation or native memory outside every pool; the entrypoint sets MALLOC_ARENA_MAX=2 so glibc does not keep an arena per thread. The container verdict reads anonymous memory against the limit, not memory.current, which includes the reclaimable page cache.
The pressure valve
The block cache is the one pool that can give memory back while running. When anonymous memory passes 90 % of the limit, or the cgroup's memory.high event count rises (clusters that set memory.high, such as Kubernetes with MemoryQoS), the engine lowers the cache's capacity by 20 % per step โ at most one step every 30 s, never below 32 MiB โ and logs each step at WARN. Reads get slower; the pod stays alive. A cache whose evictable part โ its usage less the memtables' reservations and pinned blocks, which a lower capacity cannot evict โ is no more than a step would leave is not stepped: once the cache can give no more โ at its floor, or with the memory elsewhere โ the engine says so once, at WARN, naming the heap, the JVM's own memory and native allocations as where the memory is. After 5 minutes below 80 %, it raises the cache again in steps of 10 % of its planned capacity. stoatflow.memory.valve.steps.total counts the steps, and GET /memory shows valve.active. Memory the valve frees returns to the operating system only as far as the allocator gives it back.
A valve that steps is a container that is too small for what runs in it: the fix is a larger limit or a smaller heap, not the valve.
| Symptom | Likely cause | Reach for |
|---|---|---|
block-cache starved: data hit ratio below 0.85 with the cache full and a working set more than twice its capacity | The working set is much larger than the cache | A larger limit, or state-heavy; ask ?limit= or ?cache= first |
heap oversized and block-cache tight or starved | The split, not the size | state-heavy โ the report's hint says so |
heap starved | In-memory stores, suppress buffers or a large uncommitted-max-bytes on a small heap | heap-heavy, STOATFLOW_HEAP_MB, or a smaller uncommitted-max-bytes |
memtables tight or starved: write stalls, many L0 files | Compaction is behind the write rate | More CPUs (background jobs follow them), or pin RocksDBConfig.maxBackgroundJobs |
native-residue tight or starved, growing | Native memory outside every pool: fragmentation, many stores or window segments | A larger limit; keep MALLOC_ARENA_MAX=2; check the start-up plan line's database count |
container starved, valve steps in the log | The container is too small for its heap and pools | A larger limit, or a smaller heap |
Every pool oversized or comfortable, slackMib large, the could run in a smaller container line | The container is larger than the load needs | The squeeze; Right-sizing memory |
Small pods
Knobs: the lean memory profile โ STOATFLOW_MEMORY_PROFILE=lean, or memoryProfile.set("lean") / stoatflow.docker.memoryProfile=lean in the build โ the container's memory limit, and the native image.
A small application at a low rate does not need a 1 GiB pod. The lean profile gives the heap a quarter of the first GiB instead of half, then the same shares as balanced, and the memory plan's rules for small pods do the rest: the JVM's share has a floor of its own, the headroom goes down to 32 MiB, the heap floor is 64 MiB (48 MiB in a native image), uncommitted-max-bytes follows the heap, and a pod whose cache cannot afford two background jobs gets one. Defaults โ Small pods shows the plan at each size. The smallest documented pods, with lean:
| Application | JVM | Native image |
|---|---|---|
| Stateless | 256 MiB | 128 MiB |
| Stateful | 512 MiB | 256 MiB |
Below these sizes the plan WARNs at start. The 256 MiB stateless JVM pod is a low-rate size: at about 1,000 msg/s it held up with the heap, the container and the native residue tight. At 512 MiB the heap and the container read comfortable, but the residue still reads tight: the JVM's native share is 160 MiB up to a 640 MiB pod, and a stateless app at that rate uses it. Both ran with no restart โ the residue verdict marks the share at its budget, not a pod in trouble โ and from 768 MiB, where the share grows past 160 MiB, the residue reads comfortable as well. The stateful sizes hold an application with a few stores. Each store's memtables may take 16 MiB ร 2 of the block cache, and the plan WARNs at start when their sum ฮฃ exceeds the cache โ the worst case, every store's memtables full at once, which the measured applications never approached. An application with many stores needs a larger pod: Defaults โ Small pods has a 14-store example, and GET /memory/what-if?limit=โฆ shows the plan and its WARNs at any size.
Measured. Resident memory at about 50 records/s, in local Docker:
| Application | JVM | Native image |
|---|---|---|
| Stateless | 160โ185 MiB | 16โ35 MiB |
| Stateful | 180โ215 MiB; 232 MiB during a full restore in a 512 MiB pod | 45โ55 MiB |
Most of the JVM figures is the JVM's own memory: G1, metaspace and the code cache measured 130โ150 MiB resident, which is why the plan sets aside at least 160 MiB for them, and why the native image, with no metaspace and no JIT, is the choice at 256 MiB and below (Native image). The heap's caps are bounds, not allocations: the producer's 256 MiB send buffer and uncommitted-max-bytes fill only as far as the rate drives them, so a small heap at a higher rate wants a smaller buffer.memory too โ see Memory-constrained environments.
G1 stays the collector. Serial GC saved only about 15 MiB resident on these pods, so the image keeps -XX:+UseG1GC. On a small JVM pod, these flags together trimmed another 15โ25 MiB. Their throughput cost is not measured yet, so they are optional, not defaults:
- GC threads. G1 sizes its parallel and concurrent GC threads from the CPUs the JVM sees, which follow the container's CPU limit: set a CPU limit, or set
-XX:ParallelGCThreadsand-XX:ConcGCThreads. -XX:ReservedCodeCacheSizeโ a smaller code cache for the JIT's compiled code.-XX:CICompilerCountโ fewer JIT compiler threads.-Xssโ a smaller stack per thread.- Heap uncommit.
-XX:G1PeriodicGCIntervalwith tighter-XX:MinHeapFreeRatioand-XX:MaxHeapFreeRatio, so G1 gives heap it no longer uses back to the operating system.
Pass them through the build's jvmFlags (Docker โ JVM flags) or JAVA_TOOL_OPTIONS at deploy time, and keep one only if resident memory, the memory report and the P99 agree under your load.
Timer cache
Every timer backend loads at most timer-backend.max-cached-timers timers per time domain into its timer cache, in timestamp order โ so a catch-up, a burst of timers at one instant, a restart or an HA failover never loads them all. HYBRID (the default) and PERSISTENT keep the rest in RocksDB; MEMORY keeps every timer in memory and bounds only the cache, so its total memory grows with the timer count.
Knob: stoatflow.timer-backend.max-cached-timers โ default 100000.
Memory. A heap entry holds a timer's key and, when they are 1 KiB or less, the timer's headers (larger ones stay in RocksDB and are read when the timer fires): budget about 2 ร max-cached-timers entries (event time and processing time each get the full bound) at the size of a timer key, plus its headers, plus some 100 bytes of overhead โ with ~200 B of tracing headers on every timer, about 70 MB at the default; at most about 230 MB if every timer carries a full 1 KiB. A timer registered for a time already loaded joins even a full cache, so registrations due within the load horizon (cache-horizon-ms, one second for PERSISTENT) can go past the bound โ stoatflow.timer.cache.overshoot.max shows by how much.
Throughput. When more event-time timers are due than fit, event time waits at the first one not yet loaded while the loaded ones fire (Timers and event time). A backlog of B due timers then drains in about B / max-cached-timers steps, each as long as onTimer takes for one cache-full; records that would move event time past the waiting timer wait in their partition buffers. The sizing rule: raise max-cached-timers when holds are frequent โ when rate(stoatflow_watermark_timer_held_time_total[5m]) stays high outside a catch-up โ and the memory above allows it. A slow onTimer stretches every hold; keep I/O out of it.
| Symptom | Likely cause | Reach for |
|---|---|---|
Event time advances in steps during a catch-up; stoatflow.watermark.timer.held toggles | A timer backlog larger than the cache drains chunk by chunk โ expected | Nothing, or raise max-cached-timers to take bigger steps |
stoatflow.watermark.timer.held stays at 1, stoatflow.timer.fired.total flat, a WARN Event time has been held at the timer frontier โฆ for โฆ ms | onTimer is stuck or very slow | Fix the slow onTimer; the WARN names the loaded count, the bound and the frontier |
| Windows emit late and window segments pile up during long holds | Every watermark-driven effect โ window closes, expiry, suppress โ waits with event time | Raise max-cached-timers; speed up onTimer |
Changing a store's retention
Symptom: you want to keep windowed or session state for longer (or shorter) than you originally configured, on a store that already has data in it.
Change retention and restart. On the segmented backend โ the default for every windowed aggregation
and every session store โ StoatFlow re-reads the existing state as-is: each segment records its own time
range on disk, so a changed retention (which also changes the segment interval) remaps rather than being
reinterpreted. Nothing is restored, nothing is re-read from the changelog, and no data becomes invisible.
Kafka Streams requires wiping local state for the same change.
That covers the stream-stream join buffers too: they are segmented window stores that retain duplicates,
so a changed grace remaps the same way. Changing before or after is different: the buffer's window
size is max(before, after), so that is a window-size change and takes the full restore below. Only hand-built
TransactionalRocksDBWindowStore and TransactionalRocksDBSessionStore instances โ the non-segmented
backend, which no Stores factory and no DSL operator builds any more โ keep the
interval as an 8-byte prefix on every stored key, where a retention change that moves it cannot remap and
is handled as a restore (below) instead.
Three consequences worth knowing before you do it:
- Retention is a minimum, not an exact bound. Whole segments are dropped, so the segment holding
watermark โ retentionis kept in full. Actual retention lands anywhere in[retention, retention + segmentInterval), and exactly 1ร on an in-memory store. Size disk against the upper bound. - Segments are sized by one rule, not configurable:
Backend Rule Worst-case retained Segmented window stores (every persistent RocksDB DSL or Stores-built window store, the default join buffers included)max(retention / 3, 60s, windowSize)up to 2ร when windowSizegoverns; otherwise up toretention + 60swhile the 60s floor governs, or 4/3ร onceretention / 3doesSegmented session stores (every persistent RocksDB DSL or Stores-built session store โ no window-size term)max(retention / 3, 60s)up to retention + 60swhile the floor governs, else up to 4/3รMaterialized.StoreType.IN_MEMORYwindow and session storesnot segmented exactly retentionNon-segmented (hand-built TransactionalRocksDBWindowStore/TransactionalRocksDBSessionStoreonly)max(retention / 3, 60s)up to retention + 60son the floor, else up to 4/3ร
ThewindowSizeterm binds wheneverwindowSize > retention / 3โ including the common default, sinceTimeWindows.ofSizeWithNoGrace(d)givesretention == windowSize. There the interval equals the retention and the store holds two live segments, so plan disk for twice the window's data. Kafka Streams has no such term (its rule ismax(retention / 2, 60s)), so StoatFlow retains less than KS on session stores (equal while both sit on the 60s floor, less once KS's/2term exceeds it), the same on a symmetric no-grace join buffer (window sizemax(before, after)against a retention ofbefore + after + gracelands exactly on KS'sretention / 2), and more on a default windowed aggregation. - Watch the segment count, not the disk.
stoatflow.store.segments{store_name}is the live number of RocksDB instances a segmented store holds โ about seven file descriptors each, with no upper bound. It plateaus atretention / segmentInterval + 1while event time advances and climbs for as long as the watermark is pinned by a lagging-but-live partition or, withwatermark.idleness-timeout-ms: 0, an idle one. Alert onstoatflow_watermark_lag_ms(sampled every second, so it climbs during the stall it reports) and read the segment gauge to see which stores are paying for it.
Below about three minutes of retention the 60-second floor governs providedwindowSize โค 60sโ a window larger than the floor still wins on a segmented store. It is the same floor Kafka Streams applies (though KS reaches its own floor below 120 seconds, since its rule isretention / 2), and it is deliberately not clamped down to the retention, so a 10-second store still gets a 60-second interval.
Being on the floor says nothing about how many segments are live. The number of live segments is set by where the watermark sits:retention / segmentIntervalwhole intervals plus the one holding the boundary when it lands on a segment edge, andceil(retention / segmentInterval) + 1in the worst phase โ the same number when the retention divides evenly, one higher when it does not, since segments are fixed-width and epoch-aligned. Size against the maximum. A single segment is never guaranteed โ 30 seconds of retention on a 60-second interval still spans two whenever the watermark is off a boundary. Atretention = 2min, windowSize = 90sthe interval is 90 seconds, the store holds two segments, and effective retention is 3min 30s. And because the floor is ours as much as KS's, short retentions are a large multiple rather than a small one โ a 30-second persistent session store keeps up to30s + 60s, i.e. 3ร, not 4/3ร; the in-memory one still keeps exactly 30 seconds. EmitStrategy.onWindowClose()adds a third term. Under the defaultonWindowUpdate(), expiry runs on the committed watermark. UnderonWindowClose()it is gated on the durable emit frontier instead, so a window is never expired before its final result has been emitted:Store family Emit strategy Expiry driven by Effective retention Any onWindowUpdate()(default)committed watermark โค retention + segmentIntervalAny onWindowClose()durable emit frontier โค retention + segmentInterval + (watermark โ emit frontier)
The extra term is normally small and is zero-slack by design โ the gate exists so expiry can never overtake an un-emitted close โ but it is not bounded by the retention contract. Size for it if you runonWindowClose()over a large keyspace. The gate is in the processor rather than the store, so it delays in-memory expiry too: the exactly-1ร property above is anonWindowUpdate()statement.- Narrowing retention frees disk gradually. A segment keeps the span it was written with, so after
cutting retention the old, wider segments expire only once their whole span has cleared the new
boundary. Until then effective retention is bounded by
retention + the widest existing span, not byretention + the new interval. Cutting 30 days to 1 hour therefore keeps answering reads from ~10-day segments for up to 10 days. The store logs oneINFOline at startup whenever that is the case. If retention is a deletion deadline for you, plan for the transition rather than the steady state.
Changes that do need a restore
These changes alter a layout that cannot be remapped, but the changelog still holds what the new layout reads:
the restore re-derives what moved. StoatFlow detects each at startup, logs a WARN naming the field and both
values, and rebuilds the store from its changelog:
| Change | Why it cannot remap |
|---|---|
| Retention, on the non-segmented backend only (hand-built stores) | The segment id it derives is part of every key there |
| Segmented โ non-segmented window or session backend (hand-built stores) | A different directory layout; the changelog is the same for both |
The restore is the ordinary changelog replay, so it costs restore time proportional to the store's changelog, and the application starts once it completes. Plan these alongside a deploy that can absorb it, not as a hot config edit.
Changes a changelog cannot rebuild
These changes alter what the changelog means as well, so a rebuild from it would read every record not
rewritten since under the new layout. On a store whose changelog is its recovery source StoatFlow refuses to
start instead โ whatever state.layout-mismatch says โ and leaves that store untouched, local state and
changelog alike:
| Change | Why the changelog cannot rebuild it |
|---|---|
| Plain โ timestamped, on a key-value or window store | A timestamped store's values, in the store and in its changelog, are an 8-byte timestamp followed by the value; a plain store's are the bare value |
| Store type โ key-value โ versioned, window โ session | Each type encodes its changelog keys its own way |
| Window size | Not stored per record: a window's changelog key carries its start only, and every read adds the size to it โ so the restored windows would be read with the new size |
retainDuplicates on a window store | Changes what a put means (coexist vs overwrite); the changelog keeps the records the old rule wrote |
A stream-stream join's buffers are window stores too, but a join reads them by record timestamp and never
through their window size, so changing its JoinWindows is no layout change: the join starts on its local
state, with no restore.
Only a Processor API store can meet the value-format flip or the retainDuplicates one: every DSL store is
timestamped whatever store supplier
Materialized gets, so swapping a plain supplier for a timestamped one โ or dropping an explicit supplier for
the default store โ changes nothing on disk. The refusal names the store, the field and both values; the
way out is to put the previous setting back, keep the new layout under a new store name (it starts empty,
with a changelog of its own), or reset the application (its local state and changelog topics). A table
restored from its source topic is rebuilt from it instead, and a store with no recovery source follows the
next section. A DSL windowed aggregation meets the window-size change: resize it under a new
Materialized.as name, or reset the application. Kafka Streams upgrades a plain key-value store to timestamped in
place โ its changelog carries the timestamp on the Kafka record, which cannot hold StoatFlow's negative event
times โ and checks nothing else: a resized windowed aggregation there reads its old windows with the new size.
When there is no changelog to restore from
A store built with withLoggingDisabled(), or any store under changelog.enabled = false, and not restored
from its source topic has no recovery source: its local state is the only copy. StoatFlow will not delete it for you. Startup fails
with a message naming every affected store, the field that moved and both values, and you choose:
- put the previous setting back and restart โ instant, no data movement;
- enable the store's changelog โ only if it still holds the store's data (logging was disabled recently): the store is rebuilt from it, and an empty changelog rebuilds it empty;
- accept the loss with
stoatflow.state.layout-mismatch: wipe-and-restore, which starts those stores empty. Remove the setting afterwards: it does not expire, and left in place it silently converts a later accidental change into a wipe.
The same check covers every RocksDB store a built-in store builder creates, key-value, versioned and timer
stores included (a custom StateStoreBuilder's store is not compared), and it also catches a rollback.
Each store records the local format and the layout-stamp schema it was written under. A store with no recovery
source whose local format or stamp schema another build wrote refuses too โ the message says to run the build
that wrote it, or to accept the loss โ or starts empty under wipe-and-restore. A store holding changelog records in a
format this build cannot read is never wiped, whatever the setting: its start is refused until a build that
reads them runs. See Upgrades and rollback.
Segmented-store checkpoint cadence
Time-windowed and session stores are segmented, and their RocksDB segments run with the write-ahead log off โ so they only become durable on a clean close(). A periodic checkpoint (flush dirty segments, then the offsets) makes them durable between commits and caps how much changelog a pod replays after an ungraceful restart, and how much a hot-standby standby drains on promotion โ to at most one checkpoint interval.
Knobs: stoatflow.state.segment-checkpoint-records (default 100000) and stoatflow.state.segment-checkpoint-ms (default 30000), whichever fires first.
The cadence applies under both processing guarantees, and the checkpoint runs off the commit path: under at-least-once a commit that finds a checkpoint still running waits for it before it writes state. An application that goes quiet is checkpointed too, once segment-checkpoint-ms has passed since the last checkpoint, so the bound holds whether or not records are still arriving. A checkpoint that fails keeps the last good one โ nothing is lost, but every later restart replays more until one succeeds โ and counts stoatflow.store.segment.checkpoint.failures.total.
The defaults are deliberately coarse: a checkpoint flushes SST files, so a tight cadence trades a smaller recovery window against more SST/compaction churn in steady state. Lower them only if your recovery-time objective needs a shorter ungraceful-restart catch-up than ~30 s / 100k records of windowed writes; raise them if you see checkpoint-driven write amplification and can absorb a longer catch-up.
RocksDB settings
Persistent state lives in RocksDB. Kafka Streams gives every store its own block cache and memtables, so its RocksDB memory grows with the number of stores. StoatFlow shares one block cache across all stores and accounts every store's memtables inside it, and the memory plan sizes that cache from the container (Sizing memory) โ there is no RocksDB memory setting to choose in the common case. To pin the pool instead, set stoatflow.rocks-db.memory-mb (Pinning a part of the plan).
RocksDB's write-ahead log is off: the changelog is the durability, as in Kafka Streams. A RocksDBConfigSetter can turn it on (options.write.disableWal = false) for a shorter replay after a crash, at a cost in write throughput; its files stay in the store's directory, as StoatFlow has no separate WAL-directory setting.
While the WAL is off, two settings must stay as they are. Keep options.db.atomicFlush on: a store writes its data and its changelog offsets in one batch across column families, and without atomic flush RocksDB may make the offsets durable ahead of the data, so a crash restores past records that were never on disk โ StoatFlow logs a WARN naming the store. And options.write.sync = true needs the WAL: RocksDB rejects every synced write without one, so StoatFlow refuses to open such a store instead of failing its first commit.
Per-store detail. The memory report covers the shared cache as a whole. To see which store reads past the cache, enable the RocksDB metrics (rocks-db.metrics.enabled + statistics-enabled) and compare the per-store stoatflow_rocksdb_block_cache_data_hit_ratio under load.
Backend selection
Knob: stoatflow.rocks-db.backend โ default AUTO.
AUTO picks each runtime's faster path: the FFM (Foreign Function & Memory API) backend on the JVM โ lower per-call overhead than JNI and no virtual-thread pinning during native RocksDB calls โ and JNI under a native image, where FFM's critical-downcall advantage doesn't apply. Leave it on AUTO unless you have a specific reason to pin a backend. If you force JNI on the JVM, keep the lanes on platform threads (the default) โ with lanes.thread-type: VIRTUAL, a JNI call pins its carrier thread.
Watching the effect
Tune against signals, not hunches. After each change, watch:
/metricsโ throughput, consumer lag, commit timing, and JVM/container memory, scraped by Prometheus. See Metrics and Observability./memoryโ the memory plan, a verdict per pool, and the limit that would fit. See Sizing memory./debug/barriersโ the live commit-pipeline state, which tells you whether barriers are firing on schedule and what's triggering them. See REST API./health/readyโ readiness flips DOWN if the engine can't keep up or a commit stalls. See Probes.
A clean tuning loop: change one knob โ run representative load โ read the metric that maps to the symptom โ keep or revert. Resist changing several knobs at once; you won't know which one moved the needle.
Next steps
- Defaults and the memory plan โ where every default comes from, and how the container's memory is split.
- Configuration reference โ every key, type, range, default, and environment override.
- Production checklist โ the pre-flight list before you take a topology to production.
- Observability โ wiring metrics and dashboards so the symptoms above show up before users notice.
Observability
Operating-time visibility for a single-instance app โ scrape /metrics into Prometheus and Grafana, the meters worth alerting on, correlating logs to lanes and barriers via opt-in MDC, and the /debug/threads and /debug/barriers endpoints for diagnosing a frozen or slow pipeline.
Production checklist
A go-live checklist for StoatFlow โ replica count, licence, probes, metrics, error policies, tuning, and thread safety โ each item linking to the canonical page that covers it in full.