Right-sizing memory

How to find the container memory limit an application needs — a starting size, what to observe and for how long, what each verdict of the memory report costs, when running a little under-provisioned is the right call, and the logs, alerts and dashboard that tell you whether a pod is too large or too small.

The container's memory limit is the one memory number you choose: the memory plan splits it between the JVM, the heap, a headroom and RocksDB, and the memory report (GET /memory) tells you how each part fares. This page is the procedure around them — where to start, what to watch, how long, and how to decide. The mechanics it builds on are on Tuning → Sizing memory.

The right size is not always the most comfortable one. A pod a little short on block cache costs read latency and CPU; a pod short on memory outside the cache costs restarts. Most of this page is about telling the two apart.

The procedure in short

  1. Start at a size from the table below, with the recommended probes.
  2. Observe for at least a day, through the daily peak, one restart with a full restore, and — where it can happen — a catch-up after downtime. Keep the peaks in your metrics system: the report itself looks back 15 minutes.
  3. Read the largest fits over that time against the limit, and the worst verdict of each pool.
  4. Decide: shrink with the squeeze when the pod is oversized, grow when the container or the native residue runs tight, or accept a tight cache on purpose.
  5. Alert on what ends in a restart, and on an oversized pod as a ticket, not a page (Alerts).

A starting size

ApplicationStart atProfileNotes
Stateless, up to about 1,000 msg/s256 MiB (JVM), 128 MiB (native image)leanHolds at about 1,000 msg/s with the heap, the container and the native residue tight. At 512 MiB the heap and the container read comfortable; the residue stays tight — healthy, see Alerts — and reads comfortable from 768 MiB, where the JVM's native share has grown past its 160 MiB floor (measured at 768 MiB and 1 GiB).
Stateless, higher rates1 GiBbalancedThe heap holds the Kafka clients' buffers and the epoch's held output; more rate wants more heap.
Stateful, a few stores, under ~1 GiB of state, low rate512 MiB – 1 GiB (JVM), 256 MiB (native image)leanA store count beyond a few needs more: GET /memory/what-if?limit=… shows the plan and its WARNs at any size.
Stateful, many stores or gigabytes of statethe limit that gives the cache its hot data: GET /memory/what-if?cache=<MiB>balanced, or state-heavy for large state read heavilyThe cache needs the part of the state your reads hit, not the whole state.
Not known yet4 GiBbalancedThen the squeeze.

The hot data. After a representative run, GET /memory reports the stores' working set (working-set.bytes): the uncompressed live data in their SST files. A cache that holds the working set serves every read from memory; one that holds the part reads actually hit — often much less — serves most of them. The simulated cache points measure that part directly. State on disk is compressed: the working set is usually two to four times what du reports.

Porting from Kafka Streams. A Kafka Streams fleet caches each instance's share of the state in that instance's RocksDB; StoatFlow is one instance with one cache for all of it. Add up the fleet's block-cache budgets (its RocksDBConfigSetter's cache times the instances) and ask GET /memory/what-if?cache=<that sum> for the limit, then squeeze. Do not add up the heaps: one process runs one set of Kafka clients and their buffers, not one per instance.

How long to observe, and what

The memory report judges a rolling 15-minute window and forgets older peaks; an in-place restart starts a fresh report. Size on the peaks your metrics system keeps — max_over_time over a day or a week — through four moments:

  • The daily peak. The highest rate the application sees, for as long as it lasts.
  • A restart with a full restore. The report samples from start-up on, so the restore's verdicts and residue are in the metrics. Run it once deliberately — in staging, a pod whose volume was deleted — and check the restore finishes inside the startup probe's budget. Two readings through a restore are not a short pool: the heap can read starved on a small pod while the JVM's first minute spends much of its time in GC (judge the heap by its after-GC peak there), and the memtables read starved right after it while compaction works through the L0 files the restore wrote. A restore also holds native memory outside the block cache — measured, up to twice RocksDB's reserve on a 1 GiB pod with 14 stores — which the residue's budget and the pod's headroom carry.
  • A catch-up after downtime. The application processes a backlog as fast as it can, and every buffer on its input path fills at once: the consumer's fetch responses (up to fetch.max.bytes per broker), each partition's buffer (up to processing.buffered-records-per-partition records), each lane's queue (up to lanes.queue-capacity records) and the epoch's uncommitted state (up to state.uncommitted-max-bytes). In the steady state they sit near empty, so none of this is in fits. Roughly, a catch-up needs heap for the epoch cap + partitions × buffered records × record size + lanes × queue capacity × record size + the fetch × brokers — for large records several times the steady heap. Measured on a 14-store join application with values of about 2 KB, after 10 minutes down at 100 records/s: the catch-up exhausted a 256 MiB heap and an 819 MiB one alike (OutOfMemoryError: Java heap space in the log, a restart loop); on dedicated CPUs at 300 records/s it exhausted a 4 GiB pod's 1,434 MiB heap too, and a 16 GiB pod's 3,278 MiB heap caught it up in four minutes with 2 GiB of it live — about ten times the steady state. Bounding the consumer's fetch, poll size and per-partition buffer cut the fetch path from about 100 MiB to 13, but the lane queues and the epoch filled the room, and the 256 MiB heap ran out the same way. Test a restart into a backlog the length of your longest expected outage before you settle on a size, and give an application that must survive one heap for that sum — a larger pod, the heap-heavy profile or STOATFLOW_HEAP_MB — or shrink its terms: a lower buffered-records-per-partition, lanes.queue-capacity or uncommitted-max-bytes, and the client settings in Memory-constrained environments. A later release sizes these buffers from the heap. A heap that reads oversized in the steady state is therefore not waste on a stateful application: it is what a catch-up uses. Shrink it — state-heavy, a smaller STOATFLOW_HEAP_MB — only after a catch-up test.
  • A stalled watermark, for segmented window and session stores: their segments accumulate while event time stands still, and the engine WARNs Memory plan re-check: segments opened since start … when they outgrow the plan.
# The largest fits over a day, as a share of the limit (above 1: the pod is too small)
max_over_time(stoatflow_memory_fits_bytes[24h]) / stoatflow_memory_limit_bytes

# The worst verdict of each pool over a day that held for five minutes: 0 oversized, 1 comfortable, 2 tight, 3 starved
# (a single sample right after a restart or restore can read starved while the report settles)
max by (pool) (max_over_time(min_over_time(stoatflow_memory_verdict[5m])[24h:1m]))

# Resident memory's peak over a day (cAdvisor), as a share of the limit
max_over_time(container_memory_rss{container="<your container>"}[24h]) / on(pod) stoatflow_memory_limit_bytes

stoatflow_memory_fits_bytes reads NaN until the engine has measured a heap peak; max_over_time skips those samples.

What each verdict costs

The verdicts mean different things in different pools. A tight block cache is a performance cost; a tight container is a restart risk.

Pooltight meansWhat you paystarved means
Block cacheData hit ratio 0.85–0.95 with the cache fullMore reads from disk: read latency and CPU go upMost lookups miss; throughput can fall below the input rate
Heap60–80 % occupied after GCMore frequent GC: CPU and pause timeGC more than 5 % of the time, close to OutOfMemoryError
MemtablesWrite stalls, or 20+ L0 filesCommit latency during burstsSustained stalls: compaction is behind the write rate
Native residueUp to 1.5 × its budgetMemory the plan does not hold back for it is in useBeyond 1.5 ×: the container's limit is at risk
Container85–95 % of the limit in useLittle left for a burst or a restoreAbove 95 %, a memory.high or oom event, or the pressure valve working

Measured. On a 14-store application at 300 msg/s (shared-CPU nodes, so the numbers are indicative; the pool pinned, with a large heap, 64 allocator arenas and two background jobs around it): with the block cache at 4 GiB, 2 GiB, 1 GiB and 512 MiB the end-to-end P99 was 421, 438, 508 and 557 ms — a smaller cache costs latency gradually, then steeply below 512 MiB — and at 256 MiB, starved, it was 6.3 s. Under the plan's own settings a 1.4 GiB cache gave 417–429 ms. On the same application, glibc's default arena count — eight per core, 64 on that node, where the image sets MALLOC_ARENA_MAX=2 — raised the native residue from 415 to 1,774 MiB and the P99 from 417 to 699 ms.

The verdict thresholds are a first calibration, measured on a few applications; they may move as more are measured. What they read: the cache counts as full at 95 % of its capacity, the hit ratio needs 1,000 lookups in the window (a low-read application is judged on its working set alone), and a stall time above 1 % of the window is sustained.

Under-provisioning on purpose

Trade the cache, never the container. A block cache smaller than the working set is a legitimate choice when the latency it costs is acceptable: the application stays correct and up, reads take longer, CPU rises. Memory outside the cache — the heap, the JVM's own memory, RocksDB's native memory — has no such give: when it runs out, the kernel kills the pod, and a single instance then restarts and, if its volume is gone, restores.

You may acceptAs long asNever accept
A tight block cache, or a starved one for a latency-insensitive applicationConsumer lag stays flat through the daily peak and the P99 is inside its objectiveA tight or starved container verdict for longer than a burst
A tight heapGC stays a small share of CPU, and a catch-up does not run it out (watch the heap through one)A starved heap — a catch-up turns it into OutOfMemoryError and a restart loop
tight memtables during bursts or a restoreStalls stop once the burst endsA starved native residue, or one that keeps growing
A restore that takes longer on a small podIt finishes inside the startup probe's budgetValve steps in steady state: they mean the container is too small for what runs in it

To run a smaller cache deliberately, lower the limit, or keep the limit and pin the RocksDB pool (stoatflow.rocks-db.memory-mb) — the rest of the limit then stays with the heap and the headroom. The report keeps calling the cache tight; alert on the container and the residue, not on the cache (Alerts).

Over-provisioning

A pod is larger than it needs when, over a window with the peaks in it, every pool reads oversized or comfortable and fits sits well below the limit. The engine says so itself: once a whole window shows the container comfortable, no pool tight or starved and fits at least 25 % below the limit, it logs at INFO, at most every six hours:

Memory report: this application could run in a smaller container — it fits 1480 MiB of the 4096 MiB limit over the last 15 min (slack 2616 MiB), no pool tight or starved. Before shrinking, look at a window with a restart, a restore and the day's peak (max_over_time of stoatflow_memory_fits_bytes); GET /memory/what-if?limit=1480 shows the plan at that size.

Until the stores report a working set or the cache's hit ratio shows it serves its reads, fits counts the whole planned block cache, so a stateful application reads oversized only once it has run long enough to measure one. A cache that serves its reads (comfortable or oversized) counts what it holds, at most the working set, so a large state behind a high hit ratio does not raise fits. Shrink in steps with the squeeze, checking each against the peaks.

What the logs say

LineWhenLevelMeans
StoatFlow heap sizing: … (stderr)Container start—The entrypoint's heap from the limit and the profile, and the limit's source
Memory plan: …Engine startINFOThe split the engine runs on: heap, RocksDB pool, block cache, Σ, background jobs
A memory-plan WARNEngine startWARNA pool over what is left, the cache at its floor, Σ against the cache, a heap below its demand, a second engine, a tmpfs state directory, open files over the descriptor limit — what each means
Memory report: heap …, block-cache …; fits … MiB …Every 15 minutes while a pool is tight or starvedINFO (WARN while the valve is active)Which pool is short, and the limit that would fit
Memory report: this application could run in a smaller container …At most every 6 hours while oversizedINFOOver-provisioning
Memory pressure valve: … block cache lowered … / … raised …Each valve stepWARNThe container passed 90 % of its limit; the cache gave memory back
Memory pressure valve: … the block cache can give no more …Once per pressure episodeWARNThe memory is outside the block cache — the heap, the JVM's own memory or native allocations; the pod may be OOM-killed
Memory plan re-check: segments opened since start …Once, when segments outgrow the planWARNA segmented store's segments grew (a stalled watermark); a larger pod or a shorter retention

A restart with no OutOfMemoryError in the log was ended from outside the JVM — by the kernel's OOM killer or by the kubelet for a failed probe, and the application's log cannot tell which. kubectl describe pod shows the container's last state (OOMKilled, or Error with exit code 137) and the events (Liveness probe failed before a restart is the kubelet). On one or two CPUs during a restore it is usually the probe: use a startup probe and a 3-second timeout (Health probes). A pod short of CPU rather than memory looks the same: given half the cores its rate needed, a measured pod fell behind and failed even a 3-second liveness probe, restarting five times in ten minutes with its memory well inside the limit. Before you raise the memory limit for a restart loop, check CPU throttling — rate(container_cpu_cfs_throttled_periods_total[5m]) / rate(container_cpu_cfs_periods_total[5m]) near 1 — and consumer lag.

Alerts

AlertExpressionSeverityMeaning
Memory pool starvedmax(stoatflow_memory_verdict{pool!="block-cache"}) == 3 for 30mWarningThe heap, the memtables, the native residue or the container is short; GET /memory names it and the limit that would fit. The block cache is left out on purpose: a starved cache costs latency, which your latency alert sees
Container tight for hoursmin_over_time(stoatflow_memory_verdict{pool="container"}[6h]) >= 2TicketThe pod has run near its limit for six hours; grow it before a restore or a catch-up finds the rest
Memory pressure valveincrease(stoatflow_memory_valve_steps_total[15m]) > 0WarningThe container passed 90 % of its limit and the engine shed block cache to keep the pod alive
OOM-killedincrease(kube_pod_container_status_restarts_total[15m]) > 0 and on(pod, container) kube_pod_container_status_last_terminated_reason{reason="OOMKilled"} == 1CriticalThe kernel killed the container (kube-state-metrics)
Oversized for a weekmax_over_time(stoatflow_memory_fits_bytes[7d]) < 0.6 * stoatflow_memory_limit_bytesTicketThe pod could run in a container 40 % smaller; check with the squeeze

On stateless pods up to 640 MiB the native residue runs at its budget from about 1,000 msg/s and reads tight while the pod is healthy — measured at 256 and 512 MiB: alert on the residue at starved (== 3), not at tight.

A recording rule keeps the share a pod could shrink by cheap to chart:

groups:
  - name: stoatflow-memory
    rules:
      - record: stoatflow:memory_fits_ratio
        expr: stoatflow_memory_fits_bytes / stoatflow_memory_limit_bytes

A Grafana dashboard

Download the memory dashboard (JSON, Grafana 10+) and import it with a Prometheus data source. One row per question, filtered by application_id and pod:

  • Does it fit? fits against the limit, and the plan's split per pool.
  • How does each pool fare? The verdict of each pool over time.
  • What is resident? The container's resident memory (cAdvisor) against the limit, and the native residue against the plan's native reserve.
  • Under pressure? The valve's steps.

Native images

A native image publishes no heap occupancy after GC, so its heap verdict reads unknown and fits stays empty. Size a native image on the container verdict, the native residue and the resident memory's peak instead — the same procedure, with the native rows of the plan as the starting point.