Tuning under load

Practical tuning for StoatFlow under load โ€” measured goal recipes, lane count, commit-cadence bounds, the memory and uncommitted-state knobs, how to size the container with the memory report, and small pods, each tied to the symptom that tells you to reach for it.

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.

All values below are the defaults from the engine config. Every knob has a YAML key under 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:.

GoalRecipeMeasured trade-off
Low latency, stateless or exactly-oncecommit-barrier.interval-ms: 250, commit-barrier.min-interval-ms: 130, commit-barrier.interval-factor: 1.2P99 โˆ’8 to โˆ’17 % on the stateless apps under exactly-once, at the same CPU. More commits per second.
Low latency, stateful, eager emissionlanes.count at half the cores (4 on 8 cores)P99 โˆ’10 to โˆ’14 %, CPU +23 to +49 % (word-count).
High throughput, CPU-bound statefulRaise 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 aggregationsemit.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 fastThe 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 statelesskafka.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 outputkafka.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, statelesslanes.count: 1โˆ’3 to โˆ’34 % CPU. P99 doubles as load approaches one lane's capacity.
Blocking I/O in user codeMany 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, statelessprocessing.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-heavyA 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 appThe 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.count at 4ร—โ€“8ร— cores with lanes.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.
SymptomLikely causeReach for
Consumer lag grows while the CPU has headroom, no blocking callsToo few lanes for a CPU-bound stateful sub-topologyRaise lanes.count toward the core count
Cores underused, throughput plateaus, processing involves blocking callsToo few lanes for an I/O-bound topologyRaise lanes.count (4ร—โ€“8ร— cores) and set lanes.thread-type: VIRTUAL
High CPU, lots of context switching, no throughput gain from more lanesOver-provisioned lanesLower lanes.count toward the default
A few keys dominate; most lanes idleSkewed key distribution, not a lane-count problemRe-key upstream; lane count won't help
Lane count is fixed at startup and cannot be changed while running โ€” it's part of the engine's single-instance topology. Changing it requires a restart. The thread type is one setting for the whole engine; punctuation lanes always run on virtual threads. At startup the log line 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:

KnobYAML keyWhat it does
Seed intervalcommit-barrier.interval-msStarting interval before the cadence settles
Interval factorcommit-barrier.interval-factorTarget interval as a multiple of measured commit duration
Minimum intervalcommit-barrier.min-interval-msFloor โ€” barriers never fire closer together than this
Maximum intervalcommit-barrier.max-interval-msCeiling โ€” 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, lower interval-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.
SymptomLikely causeReach for
End-to-end latency too high; output lags inputCadence too loose; records wait for the next barrierLower max-interval-ms (and/or interval-factor)
Throughput capped; commit overhead dominates a profileCadence too tight for the volumeRaise max-interval-ms
Output is bursty in lockstep with commitsWorking as designed โ€” output is released at barriersTighten 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:

KnobYAML keyWhen to use
Hard cap on records per epochcommit-barrier.max-epoch-recordsUnset by default (no cap) โ€” set only if you need a deterministic upper bound on epoch size regardless of self-tuning
Initial cap before warmupcommit-barrier.initial-max-epoch-recordsLower 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 limitHeap (balanced)Default uncommitted-max-bytesStarting point
1 GiB512 MiB128 MiBThe default: on a small pod the cache needs the memory more
2 GiB819 MiBabout 205 MiBThe default
4 GiB1434 MiB256 MiBThe default: leaves the rest of the heap for the producer's send buffer, your objects and GC
8 GiB2048 MiB256 MiB256โ€“512 MiB: more room for GC and producer buffers
16 GiB3277 MiB256 MiB512 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.
SymptomLikely causeReach for
Container memory spikes near the limit; OOMKills under loadUncommitted state per epoch too large for the containerLower 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 topologyEarly barriers firing on memory pressure (MEMORY_PRESSURE trigger) or a per-store cache cap (CACHE_PRESSURE trigger) โ€” the barrier-trigger metric tells you whichRaise 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 lowOutput 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 doneRaise uncommitted-max-bytes (only if the container has the headroom)
Slow time-to-first-commit on a heavy-state topology at startupFirst epoch buffering too much before warmupLower 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: a comfortable or oversized cache serves its reads at its size, so it needs what it holds โ€” its capacity less ฮฃ, at most the working set โ€” however large the state; a tight, starved or unknown cache 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. null until the engine has measured.
  • slackMib โ€” how far the current limit is above fitsMib.

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.

VerdictHeap (after-GC peak, of the ceiling)Block cacheMemtablesNative residueContainer (anonymous memory, of the limit)
oversizedbelow 25 %the working set fits in less than 70 % of its data capacityโ€”โ€”โ€”
comfortable25โ€“60 %data hit ratio at least 0.95, or the working set fitsno write stalls, L0 below the slowdown triggerwithin its budget (below)below 85 %
tight60โ€“80 %data hit ratio 0.85โ€“0.95 with the cache fullwrite stalls, or 20 or more L0 filesup to 1.5 ร— the budget85โ€“95 %
starvedabove 80 %, or GC more than 5 % of the timebelow 0.85 with the cache full and a working set more than twice its capacitysustained stalls, or 36 or more L0 filesbeyond 1.5 ร— the budgetabove 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)
Formost applications: choose the container, let the plan split itapplications whose read latency depends on a cache size you want to choose and keep, whatever the container
Steps1. a generous limit; 2. a representative load, with a restart and a restore; 3. read the verdicts and fitsMib; 4. the squeeze1. 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 movesthe limit; the plan re-splits itthe 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:

  1. Run a representative load, with a restart and a restore, at a generous limit.
  2. Read fitsMib and the verdicts.
  3. Step the limit down by about 15 % at a time, as long as the container stays comfortable, no pool turns starved, the native residue stays no worse than tight, and the P99 holds.
  4. 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.

QueryAnswers
?limit=4096the 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=2048the smallest limit whose plan gives at least this block cache, and the split there โ€” "I want a 2 GiB cache: which limit?"
?heap=1536the smallest limit whose brackets give at least this heap
&profile=state-heavyany 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.

SymptomLikely causeReach for
block-cache starved: data hit ratio below 0.85 with the cache full and a working set more than twice its capacityThe working set is much larger than the cacheA larger limit, or state-heavy; ask ?limit= or ?cache= first
heap oversized and block-cache tight or starvedThe split, not the sizestate-heavy โ€” the report's hint says so
heap starvedIn-memory stores, suppress buffers or a large uncommitted-max-bytes on a small heapheap-heavy, STOATFLOW_HEAP_MB, or a smaller uncommitted-max-bytes
memtables tight or starved: write stalls, many L0 filesCompaction is behind the write rateMore CPUs (background jobs follow them), or pin RocksDBConfig.maxBackgroundJobs
native-residue tight or starved, growingNative memory outside every pool: fragmentation, many stores or window segmentsA larger limit; keep MALLOC_ARENA_MAX=2; check the start-up plan line's database count
container starved, valve steps in the logThe container is too small for its heap and poolsA larger limit, or a smaller heap
Every pool oversized or comfortable, slackMib large, the could run in a smaller container lineThe container is larger than the load needsThe 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:

ApplicationJVMNative image
Stateless256 MiB128 MiB
Stateful512 MiB256 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:

ApplicationJVMNative image
Stateless160โ€“185 MiB16โ€“35 MiB
Stateful180โ€“215 MiB; 232 MiB during a full restore in a 512 MiB pod45โ€“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:ParallelGCThreads and -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:G1PeriodicGCInterval with tighter -XX:MinHeapFreeRatio and -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.

SymptomLikely causeReach for
Event time advances in steps during a catch-up; stoatflow.watermark.timer.held togglesA timer backlog larger than the cache drains chunk by chunk โ€” expectedNothing, 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 โ€ฆ msonTimer is stuck or very slowFix the slow onTimer; the WARN names the loaded count, the bound and the frontier
Windows emit late and window segments pile up during long holdsEvery watermark-driven effect โ€” window closes, expiry, suppress โ€” waits with event timeRaise 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 โˆ’ retention is 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:
    BackendRuleWorst-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 windowSize governs; otherwise up to retention + 60s while the 60s floor governs, or 4/3ร— once retention / 3 does
    Segmented session stores (every persistent RocksDB DSL or Stores-built session store โ€” no window-size term)max(retention / 3, 60s)up to retention + 60s while the floor governs, else up to 4/3ร—
    Materialized.StoreType.IN_MEMORY window and session storesnot segmentedexactly retention
    Non-segmented (hand-built TransactionalRocksDBWindowStore / TransactionalRocksDBSessionStore only)max(retention / 3, 60s)up to retention + 60s on the floor, else up to 4/3ร—

    The windowSize term binds whenever windowSize > retention / 3 โ€” including the common default, since TimeWindows.ofSizeWithNoGrace(d) gives retention == 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 is max(retention / 2, 60s)), so StoatFlow retains less than KS on session stores (equal while both sit on the 60s floor, less once KS's /2 term exceeds it), the same on a symmetric no-grace join buffer (window size max(before, after) against a retention of before + after + grace lands exactly on KS's retention / 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 at retention / segmentInterval + 1 while event time advances and climbs for as long as the watermark is pinned by a lagging-but-live partition or, with watermark.idleness-timeout-ms: 0, an idle one. Alert on stoatflow_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 provided windowSize โ‰ค 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 is retention / 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 / segmentInterval whole intervals plus the one holding the boundary when it lands on a segment edge, and ceil(retention / segmentInterval) + 1 in 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. At retention = 2min, windowSize = 90s the 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 to 30s + 60s, i.e. 3ร—, not 4/3ร—; the in-memory one still keeps exactly 30 seconds.
  • EmitStrategy.onWindowClose() adds a third term. Under the default onWindowUpdate(), expiry runs on the committed watermark. Under onWindowClose() it is gated on the durable emit frontier instead, so a window is never expired before its final result has been emitted:
    Store familyEmit strategyExpiry driven byEffective retention
    AnyonWindowUpdate() (default)committed watermarkโ‰ค retention + segmentInterval
    AnyonWindowClose()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 run onWindowClose() 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 an onWindowUpdate() 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 by retention + 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 one INFO line 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:

ChangeWhy 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:

ChangeWhy the changelog cannot rebuild it
Plain โ†” timestamped, on a key-value or window storeA 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 โ†” sessionEach type encodes its changelog keys its own way
Window sizeNot 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 storeChanges 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.

State written by a StoatFlow build from before the segment-layout change cannot be read: the old directory names recorded no time ranges, so they cannot be interpreted safely. The application refuses to start and names the remedy โ€” delete the store's local state directory and let the changelog restore it. This is a one-time pre-1.0 break; there is no migration path and none is planned.

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