State stores

Use the Stores factory and Materialized to configure persistent and in-memory key-value, window, session, and versioned stores — and read them back via interactive queries.

State stores hold the data your stateful operators accumulate — running counts, window aggregates, join buffers, custom per-key state. This page covers the two factories you use to configure them (Stores and Materialized), how to choose between RocksDB-backed and in-memory variants, how to attach a store to a custom Processor, and how to read a store back from a running application.

For the conceptual model — global state, thread-safety under concurrent lanes, and changelog-backed durability — see State and thread safety.

RocksDB vs. in-memory

Every store type comes in two variants, and the choice is the same each time:

Persistent (RocksDB)In-memory
Survives restartYes — restored from local disk + changelogNo — rebuilt from changelog on every start
Memory footprintBounded; data spills to diskWhole store lives on the heap
Exactly-onceYesYes (changelog still committed on the barrier)
Best forProduction, large state, fast restartTests, small bounded state, prototyping
RocksDB is the default and the recommended production type. In-memory stores keep their data on the JVM heap, so they're bounded by the heap — an application built on them takes the heap-heavymemory profile — and have to read the entire changelog at startup — fine for tests and small state, but RocksDB recovers faster and scales past heap size in production. Note that "in-memory store" is not "no durability": both variants write a changelog and commit it atomically on the commit barrier. The difference is local persistence and cold-start cost.

A store is never rebuilt from metadata StoatFlow could not read. Before a restore, StoatFlow reads the partition count and the end and begin offsets of each store's changelog or source topic. A count of 0 means one of three things: a missing topic, a topic created moments ago that a broker has not seen yet, or a failed describe. That count, and a failed offset read, are retried for up to state.restoration-metadata-timeout-ms (30 s by default). If the read still fails, the start fails with an error naming the store, and the store's local state is left as it is; an authorization or authentication error is not retried. A store is deleted for a full restore only when the metadata was readable.

The local check reads metadata, not data. Each store's local state is checked once, read-only: RocksDB's manifest, whether every data file is there at its recorded size, and the stored offsets. No data file is opened, so the check costs the same for a small store as for a large one. A store whose directory fails it — a missing or truncated file, an unreadable manifest — is restored in full. A read that fails for another reason — "Too many open files", an I/O error, a file the process may not read — fails the start instead, naming the store: it may succeed on the next start, and a store deleted for a full restore cannot come back. Damage inside a data file is not looked for at startup; it fails the first read of that file. Each store's check is bounded by state.restoration-validation-timeout-ms (30 s) from its own start, and at most state.restoration-pool-size checks run at once, so many stores take longer without failing: a check still running at its bound — a RocksDB open stuck on a stalled disk — fails the start, naming the store, instead of holding it. Every other look StoatFlow takes into a store directory at startup — the layout and format checks, the table source-switch check below, the lock check before a store is deleted (each RocksDB database of the store on its own), and the directory checks around them — gets the same bound, each on its own. Neither window waits long on purpose: a failed start stops the application, and the restart is what recovers.

One open per store directory. A store's RocksDB directory can be open only once. If another open still holds it — a second instance on the same state directory, or a store a previous engine left open across an in-place restart — the start fails, naming the store, its directory and the likely holder, and the directory is left alone. Run one instance per state directory; a process restart releases a lock the process itself held.

Reusing a compacted source topic needs DescribeConfigs. With ktable.auto-reuse-source-topics on (the default), a table() whose source topic is compacted restores from that topic instead of from a changelog. To decide that, StoatFlow reads the topic's cleanup.policy at startup. If that read fails, the start fails rather than guess "not compacted". That guess would send a store that restores from its source topic to a changelog that was never written. A timeout, or a topic a broker does not know yet (created moments ago), is retried within the metadata window above; an authorization error fails the start at once. To fix it, either grant DescribeConfigs on the source topics, or pin the table to the source it already restores from — the error names it: Consumed.with(...).withMaterializeFromSourceTopic(true) for a table that restores from its source topic, (false) (or ktable.auto-reuse-source-topics: false) for one that restores from its changelog.

A table restored from its source topic is restored up to the committed offset. That topic is the table's changelog, and the consumer group's committed offset (application.id) is its checkpoint. At startup StoatFlow restores the table up to that offset and no further, and processing resumes from it, as in Kafka Streams. Each update after the last commit is therefore processed against the table as it stood when the update was first read, and an aggregation over the table (groupBy(...).count()) or a foreign-key join sees each update's real old value.

  • No committed offset (a first start, or a deleted or reset group): nothing is restored, and processing rebuilds the table from the offset reset position. A table() follows auto.offset.reset or its Consumed policy, so under latest it starts empty. A globalTable() always starts from the earliest offset. The same holds when the committed offset is no longer in the topic: the source's policy, else auto.offset.reset, decides where processing resumes.
  • Local state ahead of the committed offset (an at-least-once crash after the store saved its position but before the offsets were committed): it is kept, and the records in between are processed again (at-least-once replay).
  • A partition with nothing to restore is kept, even when retention has since moved the topic's start past it.
  • A restore that loses its place — the topic's start moves past its position while it runs — stops the start and marks the store; the next start restores it in full. A restore cut short by a crash resumes where its data stops, or, for a window or session store restoring a partition from nothing, restores the store in full.
  • Permissions: reading the committed offsets needs Describe on the consumer group, which Read implies.
  • High availability: with ha.mode: active-standby the table is still restored to the topic's end, as before; the bound for HA comes with a later release.

A table never switches its restoration source under its state. A table that restores from its source topic keeps no changelog, and its input is consumed past the data the topic holds. Moving it to a changelog in place — turning ktable.auto-reuse-source-topics off, pinning withMaterializeFromSourceTopic(false), or the topic losing its cleanup.policy=compact — would start it from an empty changelog and lose it, so such a start fails before anything is created or deleted. The error says how to keep the source, and how to switch on purpose:

  1. stop the application;
  2. reset its consumer group (application.id) on the source topic to the earliest offset — the table's input is then reprocessed;
  3. delete the store's local state (StoatFlow.cleanUp() deletes every store's);
  4. start it with the new setting.

The refusal goes by the table's local state, which records the source it restored from. A table without such state — an in-memory table, one on a fresh disk, one after StoatFlow.cleanUp() — gets a WARN instead, when its changelog topic does not exist yet while the consumer group (application.id) has committed offsets past the start of the source topic: switched now, it would start from an empty changelog and miss everything before those offsets. A stream turned into a table, or a renamed table store, looks the same, so the start goes on; the WARN names the table and the steps above (for an in-memory table, step 3 has nothing to delete). The committed offsets are read once, with Describe on the group (which Read implies); if that read fails there is no warning, and the start goes on. A new application has no committed offsets and gets no warning. A table with logging disabled never gets a changelog and is left as it is. Kafka Streams switches a table's source without a warning.

A versioned table always restores from its changelog. A compacted topic keeps one version per key, so restoring a VersionedKeyValueStore from its source topic would lose its history. A versioned table() therefore restores from its own changelog even with reuse on, and pinning one to its source topic (withMaterializeFromSourceTopic(true)), or passing a versioned store to addReadOnlyStateStore, fails when the topology is built.

Which timestamp a restored table holds. A store rebuilt from its changelog gets back exactly the timestamps it stored. A table() store rebuilt from its source topic instead — a reused compacted source, Consumed.with(...).withMaterializeFromSourceTopic(true), or a read-only store (addReadOnlyStateStore, including the overload without an update processor, which writes the extracted timestamp live) — takes each record's Kafka record timestamp, as Kafka Streams does — including a record the live path skipped because its timestamp was Kafka's -1 "no timestamp" (no event time), which is present after such a restore. A global store (globalTable, addGlobalStore) is rebuilt from its changelog and keeps the timestamps it stored. If the table uses a custom TimestampExtractor or timestamp assigner, the restored entries therefore carry the record timestamp rather than the extracted one, and output timestamps derived from them (joins against the table, aggregations over it) can differ after a restart or an HA failover until each key is updated again.

The Stores factory

Stores is a static factory (io.stoatflow.core.state.Stores) that returns a supplier — a deferred description of a store. Suppliers are handed to Materialized (for DSL operators) or to StreamsBuilder.addStateStore(...) (for custom Processors). The factory methods, grounded in Stores.kt:

Store typePersistent (RocksDB)In-memory
Key-valuepersistentKeyValueStore(name)inMemoryKeyValueStore(name)
LRU cache—lruMap(name, maxCacheSize), or 🆕 lruMap(name, maxCacheSize, tombstoneOnEviction) — bounded, evicts least-recently-used; see LRU stores for its trade-offs
WindowpersistentWindowStore(name, retention, windowSize)inMemoryWindowStore(name, retention, windowSize)
SessionpersistentSessionStore(name, retention)inMemorySessionStore(name, retention[, expiryIndex]) — see expiring sessions from an in-memory store
Timestamped KV (KIP-258)persistentTimestampedKeyValueStore(name)inMemoryTimestampedKeyValueStore(name)
Timestamped window (KIP-258)persistentTimestampedWindowStore(name, retention, windowSize)inMemoryTimestampedWindowStore(name, retention, windowSize)
Versioned KV (KIP-889)persistentVersionedKeyValueStore(name, historyRetention)inMemoryVersionedKeyValueStore(name, historyRetention)

All duration arguments are java.time.Duration. Window and session retention must be at least the window size (the factory enforces this and throws IllegalArgumentException otherwise). Store names must be non-empty and contain only [a-zA-Z0-9._-].

Window and session retention

Retention is a minimum, not an exact bound. A store keeps at least the configured retention. The RocksDB window and session stores expire whole segments, so they keep up to retention + segmentInterval — the segment holding the retention boundary is retained in full — where segmentInterval = max(retention / 3, 60s, windowSize) — one rule for every built-in segmented RocksDB window and session store, the stream-stream join buffers included (a session store has no window size, so its third term is 0; a hand-built non-segmented store omits the term entirely). The in-memory stores expire per record and keep exactly retention. Kafka Streams makes the same minimum-bound promise with the same segmented/in-memory split, sized max(retention / 2, 60s).

Two things scope that bound, both covered in Tuning: under EmitStrategy.onWindowClose() expiry is gated on the durable emit frontier rather than the watermark, which adds an unbounded (watermark − emit frontier) term — and because that gate lives in the processor, it delays in-memory expiry too, so the exactly-retention property above is an onWindowUpdate() statement. And after a retention narrowing, existing segments keep the wider span they were written with, so the ceiling is retention + widest existing span until they age out.

Which term sets the interval — and therefore how much slack you get — depends on the configuration:

RegimeBinds whenIntervalEffective retention ≤
Quotientretention ≥ 3 × windowSize and retention ≥ 180sretention / 34/3 × retention
60s floorretention < 180s and windowSize ≤ 60s60sretention + 60s — at 30s retention, 3×
Window size (segmented window stores only)windowSize > max(retention / 3, 60s)windowSizeretention + windowSize — at retention == windowSize, 2×

A multiplier only means something with the condition that makes it bind. Two consequences catch people out: below three minutes of retention the 60-second floor does not always govern (a 90-second window inside a 2-minute retention makes the window-size term the largest, so the store holds two segments), and the retention + 60s regime is not Kafka-Streams-only — StoatFlow has had the same floor since ADR-141, so a 30-second session store keeps 3× what you configured.

The mechanism: a segment is dropped only once its entire time range has fallen at or before watermark − retention. The segment containing the boundary is retained in full — that is the slack. Worked examples for every regime are on the windowing page, and sizing guidance is in Tuning.

Versioned stores (persistentVersionedKeyValueStore / inMemoryVersionedKeyValueStore) keep multiple versions of each value over time for point-in-time lookups and temporal joins. The single historyRetention argument is dual-purpose: it's both how long old versions are kept and the grace period — out-of-order records older than that window are rejected. Unlike Kafka Streams, which only ships a RocksDB-backed versioned store, StoatFlow offers an in-memory variant too.Pass a versioned supplier to Materialized.as(...) and any non-windowed key-value materialisation becomes versioned under the supplier's name: table(), toTable(), KTablefilter/mapValues/transformValues, table–table and foreign-key join results, a non-windowed cogroup and count/reduce/aggregate. A write older than the history retention is rejected and nothing is forwarded; an accepted out-of-order write lands in history and downstream aggregations ignore it, as in Kafka Streams. A windowed or session aggregation refuses a versioned supplier at build time. globalTable() accepts one, where Kafka Streams refuses it. A versioned table can be suppressed only by Suppressed.untilBarrier() — explicitly, or through stoatflow.emit.mode: on-barrier: it consolidates each key's latest changes per commit, and a write that lands in history passes through in order, flagged as history — the key's buffered latest change goes out first — so the sequence is the one the topology emits without the suppress (that key just loses its consolidation for the commit). The other suppress kinds are refused, as in Kafka Streams (KIP-914) — also through a filter, mapValues or transformValues of the versioned table without its own Materialized. Under exactly_once every lane reads a RocksDB versioned store as of its own commit, so any join can read a versioned table backed by one — and it judges a write's grace window as of that commit too, so another lane's newer, still-uncommitted record cannot get a write rejected. The stream time behind the window is shared by every lane that writes the store, where Kafka Streams keeps one per task: a lane running more than the history retention behind its siblings can see a write rejected that Kafka Streams would accept.The in-memory versioned store writes each version directly, with no per-commit write buffer. It is still exactly-once: a commit is abandoned only when StoatFlow tears the engine down and rebuilds the store from its changelog, so an aborted commit's writes never survive. With withLoggingDisabled() there is no changelog to rebuild from: the store comes back empty after every such teardown — including the in-place restart that replays a poison record — not just without the aborted commit. But its reads are always live, so it cannot be read as of a commit: under exactly_once a join that reads it from another lane is refused at build time (see joins under exactly-once), and a Processor API node that may read it from another lane gets the presumed-cross-lane-read warning. For the same reason an interactive query cannot read it at READ_COMMITTED: it is read live, with a warning (isolation level, KSC-106). The TopologyTestDriver runs every versioned store on this in-memory backend, but those checks judge the store you declared: a RocksDB versioned table passes in the driver as it does in production, and an in-memory one is refused in both.A point-in-time read below the retention floor (observedStreamTime − historyRetention, inclusive) is outside the window. It still returns the latest version when that version is old enough to satisfy the bound — the latest version never expires, matching Kafka Streams — and null otherwise. So a key written once and never updated keeps answering forever, while superseded history genuinely ages out.Retention is a minimum bound. The read behaviour above is exact from the moment stream time advances, but the disk space is reclaimed by a background sweep that runs a slice per commit, so a version can remain on disk (invisible to reads) for up to one sweep period after it expires. Tune that with stoatflow.state.versioned.sweep-period-ms, and watch it with the stoatflow.store.versioned.sweep.lag.ms gauge.That bound holds whether or not your application is busy, and under both processing guarantees. An application that goes quiet still commits on a slow idle cadence, so the sweep keeps running until it has nothing left to reclaim and then stops — which matters precisely because the worst case for disk is an application that falls silent holding a backlog of just-expired versions, overnight or over a weekend.The changelog for a versioned store is compact with unlimited retention — the same policy a plain key-value store's changelog gets, and the same one Kafka Streams uses. That follows from the latest version never expiring: the changelog records one row per version, so compaction cannot collapse them, and a time-based deletion policy would eventually remove the single row belonging to a key that was written once and never updated.The topic is bounded instead by explicit reclamation: when the sweep removes a version locally it writes a tombstone for exactly that version, which is what lets compaction drop the original record. So there are three clocks between a version expiring and the disk coming back, and only the first is immediate — a version leaves the read window the moment stream time passes it; the sweep reclaims it within one stoatflow.state.versioned.sweep-period-ms; and the broker frees the space on its own compaction cadence.That third clock is the broker's, not StoatFlow's, and it is the one worth understanding: the log cleaner never touches the active segment, so a tombstone cannot drop the record it targets until that record's segment rolls. StoatFlow therefore sets segment.ms and max.compaction.lag.ms to your sweep period — floored at five minutes, so a short period cannot produce a segment per second — and min.cleanable.dirty.ratio to 0.1when it creates the changelog, so the broker-side clock tracks the sweep's. Below five minutes the two stop tracking, and the broker bound stays at five. Left at Kafka's defaults it would not: segment.ms alone is 7 days. Two consequences worth planning for — a changelog created before this shipped keeps the old defaults (config reconciliation only ever adjusts cleanup.policy and retention.ms, so set the three knobs by hand or re-create the topic), and any value you set yourself through withLoggingEnabled(...) wins.Expect the topic to grow before it shrinks: a version costs a second, key-sized record on its way out. Watch stoatflow.store.versioned.sweep.tombstones.total against stoatflow.store.versioned.sweep.reclaimed.total — the two track each other in a healthy steady state, and a persistent gap means the local store is shedding while the topic is not.

LRU stores

Stores.lruMap(name, maxCacheSize) keeps at most maxCacheSize keys and evicts the least recently used one — a get() counts as a use. That makes it a different kind of store from every other key-value store, and it has trade-offs worth knowing before you materialise a table with it:

  • No commit buffer. Other stores buffer each commit's writes and apply them when the commit succeeds; an LRU store writes directly (a buffer cannot sit above a store that decides its own evictions). It remains exactly-once — an aborted commit ends in an engine rebuild from the changelog, so its writes never survive (with logging disabled the rebuild is empty, so the store loses all its state on every such restart) — but it cannot be read as of the last commit, so under exactly_once it cannot be a table that a join reads from another lane (joins under exactly-once), and a Processor API node that may read it from another lane gets the presumed-cross-lane-read warning. Its reads are always live, so an interactive query cannot read it at READ_COMMITTED: it is read live, with a warning (isolation level, KSC-116). Its changelog follows it under both guarantees: each key's changelog records are held until the commit, in the order the store applied the writes, so a restart restores the value it held even when two lanes wrote the key on either side of a commit barrier (the in-memory versioned store does the same).
  • Reads change it. A get() — including an interactive query — promotes the key, so it changes which key is evicted next.
  • A restart does not bring back the same keys. It is rebuilt from its changelog, and when the changelog holds more than maxCacheSize keys, which of them survive depends on the restore order — the changelog's partitions are restored in parallel — not on which keys were most recently used. The surviving set can even differ between two restarts over the same data, so a table backed by it can answer differently after a restart or an HA failover.
  • Evictions are not in the changelog by default. An evicted key is dropped locally only, so the changelog keeps its last value. Opt in with Stores.lruMap(name, maxCacheSize, tombstoneOnEviction = true) (Java: Stores.lruMap(name, maxCacheSize, true)): each eviction then also writes a delete to the changelog, so a restart or failover does not bring an evicted key back. It needs changelog logging — combined with withLoggingDisabled() the store is refused at startup.

Materialized — stores behind DSL operators

Stateful DSL operators (count, reduce, aggregate, windowed counts, joins) take a Materialized to describe their store. The most common forms (grounded in Materialized.kt):

import io.stoatflow.core.state.StateStore
import io.stoatflow.core.topology.Materialized
import org.apache.kafka.common.serialization.Serdes

// Named store, default (RocksDB) type, with serdes
val counts =
    Materialized.`as`<String, Long, StateStore>("word-counts")
        .withKeySerde(Serdes.String())
        .withValueSerde(Serdes.Long())

// Pick the store type explicitly (an explicit supplier, if set, still wins)
val inMem =
    Materialized.`as`<String, Long, StateStore>("counts")
        .withStoreType(Materialized.StoreType.IN_MEMORY)

// Auto-generated store name, store type only
val autoNamed = Materialized.`as`<String, Long, StateStore>(Materialized.StoreType.ROCKS_DB)

You can also hand Materialized.as(...) a supplier directly when you need parameters the DSL doesn't expose (window retention overrides, an explicit window/session/versioned supplier). Any supplier from Stores works, the timestamped and headers-aware ones included, so the Kafka Streams idiom Materialized.as(Stores.persistentTimestampedKeyValueStore(...)) ports unchanged. A DSL store is timestamped whichever supplier you pick.

As in Kafka Streams, the supplier overloads take two type arguments (Materialized.<String, Long>as(supplier)) and type the store after the supplier — KeyValueStore<Bytes, byte[]>, WindowStore<Bytes, byte[]> or SessionStore<Bytes, byte[]>. The name and store-type overloads take three. An operator refuses a supplier of another store kind when the topology is built (a key-value supplier in a windowed aggregation, say — Kafka Streams rejects that at compile time), and a windowed aggregation refuses a duplicate-retaining window supplier (retainDuplicates = true, which Kafka Streams accepts and then emits once per update).

A windowed aggregation also refuses a window or session supplier it cannot use (KSC-153). The supplier's retention must cover what withRetention must: the window size plus the grace period (twice the time difference plus grace for sliding windows, the inactivity gap plus grace for sessions), or the store drops a window before it closes. Its window size must be the aggregation's: the window size of a time window, or for a sliding window its time difference, Kafka Streams' size. Kafka Streams checks only withRetention and builds such a supplier as it is. The hourly supplier below suits one-hour tumbling windows with up to an hour of grace:

import io.stoatflow.core.state.Stores
import io.stoatflow.core.topology.Materialized
import java.time.Duration

// Explicit persistent window store supplier
val windowed =
    Materialized.`as`<String, Long>(
        Stores.persistentWindowStore("hourly", Duration.ofHours(2), Duration.ofHours(1)),
    )

// Explicit in-memory key-value supplier
val cache =
    Materialized.`as`<String, Long>(Stores.inMemoryKeyValueStore("cache"))

// A timestamped supplier, as Kafka Streams code writes it
val timestamped =
    Materialized.`as`<String, Long>(Stores.persistentTimestampedKeyValueStore("counts"))

Store names

A store's name is its changelog topic (<application.id>-<store>-changelog) and its state directory, so two stores never share one. Without Materialized.as("name") an operator's store takes a derived name:

OperatorStore name without Materialized.as
builder.table("orders"), globalTable(...)orders-store (the topic)
count, reduce, aggregate, windowed and session aggregations, toTable, filter / mapValues / transformValues<operator name>-store (the Named.as name, else a generated one)
suppress(Suppressed...withName("final"))final-store, the suppress's buffer — Kafka Streams' name, so its changelog topic and schema-registry subjects are the same
stream-stream joins<name>-left-store, -right-store, -outer-store (StreamJoined.withStoreName)

A derived name is StoatFlow's, not Kafka Streams' generated …-STATE-STORE-000000000N, so two operations can derive the same one — builder.table("x") and a suppress or count named x both want x-store. StoatFlow refuses such a topology when it is built, naming both operations and the setting that renames each:

State store 'x-store' of suppress() 'x' is already registered by table('x'): a store name is one changelog topic and
one state directory. Rename one — Materialized.as("name") for table('x'), or Suppressed.withName("name") for
suppress() 'x'.

Reserved names. timer-store, stoatflow-watermark and every name ending in -emitfrontier — in any letter case, since on macOS and Windows Timer-Store is the same directory — belong to StoatFlow's own stores (the timer store, the committed-watermark store, the onWindowClose() emit frontiers). A user store under one of them is refused on every path — Materialized.as, addStateStore, ProcessorSupplier.stores() — and so is one that derives it, such as an aggregation named timer or a table on topic timer, whether or not the application uses that store. Kafka Streams accepts these names.

Store type precedence

When more than one store source is set on a Materialized, resolution follows Kafka Streams' order:

  1. An explicit supplier passed to Materialized.as(supplier) — wins.
  2. withStoreType(...) / Materialized.as(storeType) (a DslStoreSuppliers, such as Materialized.StoreType) — applies only when no explicit supplier is set.
  3. The store type of a StreamsBuilder(TopologyConfig) whose configuration sets dsl.store.suppliers.class (or the deprecated default.dsl.store) — every store of that builder whose operator sets none.
  4. The application's store type: dsl.store.suppliers.class, else default.dsl.store (below).
  5. Default — RocksDB, segmented for window and session stores (matching Kafka Streams).

Neither setter clears the other. If both are set, the supplier is used and StoatFlow logs one warning per store naming the ignored store type. The same order applies per side on StreamJoined (withThisStoreSupplier / withOtherStoreSupplier beat withDslStoreSuppliers), and a foreign-key join's subscription store follows the backend of the result store's supplier. Before 2026-09-09 this was inverted — the store type outranked and erased an explicit supplier — so a ported topology that set both silently changed backend (KSC-100 in the compatibility matrix).

A store type for the whole application

dsl.store.suppliers.class (YAML stoatflow.dsl.store-suppliers-class) names the store type of every DSL store whose operator sets none: tables, aggregations (windowed and session ones too, with or without a Materialized), the stream-stream join buffers, and the backend of a join's internal stores (a left or outer join's outer store, a foreign-key join's subscription store). io.stoatflow.core.state.BuiltInDslStoreSuppliers$InMemoryDslStoreSuppliers keeps them all in memory; Kafka Streams' class names of its built-in suppliers are accepted, so a ported configuration works as it is. The class is instantiated once when the application is constructed and handed the configuration through configure(Map) — set in YAML, the application's settings in Kafka Streams' keys, the client settings as you set them under their consumer. / producer. / admin. prefixes, as Kafka Streams hands them; a store type set in a code override wins, and the class is then never instantiated. Every store shares that instance, where Kafka Streams makes one per store (KSC-162 — it matters only for a class that keeps per-store state). The deprecated default.dsl.store (rocksDB / in_memory) does the same when the class is not set; StoatFlow applies it from the application's configuration too, where Kafka Streams applies it only through StreamsBuilder(TopologyConfig) (KSC-162).

stoatflow:
  dsl:
    store-suppliers-class: io.stoatflow.core.state.BuiltInDslStoreSuppliers$InMemoryDslStoreSuppliers

An in-memory store keeps nothing on disk: every restart rebuilds it from its changelog, so it suits small state. Versioned stores, suppress buffers and the engine's own stores never take a store type. The TopologyTestDriver applies the configured store type too.

A custom DslStoreSuppliers

DslStoreSuppliers is Kafka Streams' interface: keyValueStore(DslKeyValueParams), windowStore(DslWindowParams) and sessionStore(DslSessionParams), each returning the supplier of one store, and an optional configure(Map). The params carry what the operator asks for — name(), the format (dslStoreFormat() / storeFormat(): plain, timestamped or headers-aware), and for windows retentionPeriod(), windowSize(), retainDuplicates() (a stream-stream join's buffers), emitStrategy() and isSlidingWindow(). Return one of Stores' suppliers, or delegate to Materialized.StoreType / BuiltInDslStoreSuppliers, under the params' name. StoatFlow builds its stores itself, so a supplier that is none of Stores' is refused when the topology is built, as an explicit one is; so is a supplier under another name, and one that breaks what the operator needs (a duplicate-retaining store for an aggregation, one that retains no duplicates for a join, a retention shorter than the windows need). A versioned supplier is refused as well: a store type picks a store's backend, not whether a table is versioned — materialize a versioned table with Materialized.as(Stores.persistentVersionedKeyValueStore(...)) (KSC-162).

class HotInMemory : DslStoreSuppliers {
    private fun pick(name: String): DslStoreSuppliers =
        if (name.startsWith("hot-")) Materialized.StoreType.IN_MEMORY else Materialized.StoreType.ROCKS_DB

    override fun keyValueStore(params: DslKeyValueParams) = pick(params.name()).keyValueStore(params)

    override fun windowStore(params: DslWindowParams) = pick(params.name()).windowStore(params)

    override fun sessionStore(params: DslSessionParams) = pick(params.name()).sessionStore(params)
}

Pass it to one operator with withStoreType(new HotInMemory()), or to the whole application with dsl.store.suppliers.class. A join's internal stores take only the backend of what it returns, never the store itself (an LRU map could not range-scan them).

Materialized options

MethodEffect
withKeySerde(serde) / withValueSerde(serde)Serdes for the store (and its changelog). Falls back to the configured defaults if unset.
withStoreType(Materialized.StoreType.IN_MEMORY | ROCKS_DB)Selects the store type when no explicit supplier is set; an explicit Materialized.as(supplier) wins over it (Kafka Streams' order, KSC-100). Takes any DslStoreSuppliers, a custom one included.
withRetention(duration)Overrides retention for windowed stores. Must be at least window size + grace. It is a minimum — a persistent store keeps up to retention + segmentInterval; see window and session retention.
withCachingEnabled() / withCachingEnabled(config)Sets the store's cache caps — the default ones, or your own EmissionSuppression.maxEntries(...) / maxEstimatedBytes(...). A store over its caps triggers an early commit. Caching itself is always on (see below).
withCachingDisabled()Accepted for Kafka Streams compatibility; changes nothing. Caching cannot be turned off, and the store keeps the default cache caps.
withLoggingEnabled() / withLoggingEnabled(topicConfig)Forces the changelog topic on, optionally with custom topic config (e.g. retention.ms).
withLoggingDisabled()Disables the changelog for this store — state is then only locally persisted (RocksDB) and cannot be recovered from Kafka after a crash. Use only for state you can recompute.
withRecordHeaders() / withoutRecordHeaders()Persists the processing record's Headers alongside the value (KIP-1271/KIP-1285). See record headers in state stores. Explicit opt-in or opt-out always beats the global stoatflow.dsl.store-format. An explicit headers-aware supplier (Stores.*WithHeaders) keeps its headers under withoutRecordHeaders() — the supplier wins, with one warning at startup.
withChangelogNumPartitions(n)Sets this store's changelog partition count, overriding the global stoatflow.changelog.num-partitions. See changelog partition count — it is fixed when the topic is created.

Changelog partition count

Each store's changelog topic has a partition count. By default every store uses stoatflow.changelog.num-partitions (3), and withChangelogNumPartitions(n) overrides it for one store:

// A large, write-hot aggregation store: more partitions, more write throughput and leader spread.
Materialized.`as`<String, Stats, StateStore>("order-stats")
    .withChangelogNumPartitions(6)

// A small lookup table: pin it back down so it stops widening every commit.
Materialized.`as`<String, Config, StateStore>("feature-flags")
    .withChangelogNumPartitions(1)

The same method is on StreamJoined (for a join's buffer stores), on the Processor-API StoreBuilder, and on Suppressed.BufferConfig. The timer store has no Materialized, so it uses the stoatflow.changelog.timer-num-partitions config key instead (-1 inherits the global count).

Two stores you cannot name inherit the setting from one you can: a stream-stream LEFT/OUTER join's -outer-store inherits from StreamJoined, and a foreign-key join's -subscription-store inherits from the result store's Materialized. Both hold roughly one entry per row of the store they shadow, so sizing the visible store sizes its hidden half too.

What the number buys. A changelog topic's partition count sets its write-throughput ceiling and decides how the store's data and write load shard across brokers — one partition funnels every write for that store through a single broker leader. Cold-start restore also gets faster, because the restoration pool creates one task per changelog partition — but that gain is sub-linear: a single store restores into one RocksDB instance whose writes serialise internally, and all stores share one pool of stoatflow.state.restoration-pool-size workers.

What it costs. Changelog records ride the same Kafka transaction as your output records. A store whose epoch touches keys spanning all N partitions therefore adds up to N−1 partitions to every commit that touches it — more produce requests, more commit markers, a wider flush wait — plus extra standby consumer assignments and one more local offset write per partition per commit. That cost is paid continuously; the restore benefit is paid at a cold start you hope is rare.

Prefer small counts, and raise a store only on a measurement. Read stoatflow.state.restoration-pool-size as a ceiling beyond which restore parallelism cannot improve — never as a quota to fill. The override is bidirectional, and with the default at 3 the everyday use is the downward one: pinning a small store — a lookup table, a config table — back to 1.
The partition count is fixed when the changelog topic is created. Changing withChangelogNumPartitions(n) later is a no-op plus a startup warning — StoatFlow never re-partitions a live changelog. To actually change it you must reset that state: wipe the local state directory and delete and recreate the changelog topic.Do not increase the partition count on an existing compacted changelog by hand. Compaction keeps the latest value per key per partition, so adding partitions re-maps keys while stale values survive in the old ones — the restore then reconstructs corrupted state. It is a corruption hazard, not a migration.Running kafka-topics --alter --partitions does not wait for a restart. StoatFlow lets Kafka's default partitioner place changelog records, and that partitioner divides the key hash by the producer's live partition count — so keys re-map on the next metadata refresh, while the app is running. The startup warning above cannot catch it, because nothing started. Stop the app first.
Unrelated to Repartitioned.numberOfPartitions. That sizes an in-memory repartition (lane) fan-out; this sizes a changelog topic. The two have nothing to do with each other.
A custom Kafka partitioner.class is refused at startup. StoatFlow shares one producer between your sinks and its changelogs, and changelog restore requires that each changelog key always hash to the same partition. To customise sink partitioning use Produced.withStreamPartitioner(...) or Repartitioned.streamPartitioner(...).
Caching does not change what flows downstream. Every update is forwarded — counts climb 1, 2, 3 — in production and in the test driver alike. Caching is always on — every store except an LRU one batches its writes per commit, which is where exactly-once epoch buffering and changelog compaction live — so there is nothing to turn off; the cache caps only bound how much a store may hold before it triggers an early commit. This differs from Kafka Streams, whose record cache consolidates downstream emissions and which withCachingDisabled() turns off. To emit only one final value per key per commit, use suppress(Suppressed.untilBarrier()) on the operator, or stoatflow.emit.mode: on-barrier for the whole topology.

Worked example: a counting KTable

import io.stoatflow.core.state.StateStore
import io.stoatflow.core.topology.Grouped
import io.stoatflow.core.topology.Materialized
import io.stoatflow.core.topology.Named
import io.stoatflow.core.topology.StreamsBuilder
import org.apache.kafka.common.serialization.Serdes

fun buildTopology(builder: StreamsBuilder) {
    builder
        .stream<String, String>("words")
        .groupBy({ _, word -> word }, Grouped.`as`("group-by-word"))
        .count(
            Named.`as`("count"),
            Materialized.`as`<String, Long, StateStore>("word-counts")
                .withKeySerde(Serdes.String())
                .withValueSerde(Serdes.Long()),
        )
}

Attaching a store to a custom Processor

For the Processor API you create a store builder yourself, register it on the StreamsBuilder with addStateStore(...), and connect it to the processor by naming it in the process(...) call — registering alone is not enough. Inside the processor you then look it up with context.getStateStore(name). The builder comes from Stores.keyValueStoreBuilder(supplier, keySerde, valueSerde) (and the windowStoreBuilder / sessionStoreBuilder / versionedKeyValueStoreBuilder equivalents).

If you write your own StateStoreBuilder instead, its isTimestamped must be true exactly when the store its build() returns is timestamped — implements TimestampedKeyValueStore or TimestampedWindowStore (or a headers-aware twin). Interactive queries and TopologyTestDriver recognise a timestamped store by that interface, so startup refuses a builder that disagrees with a TopologyValidationException, before any store is opened. The same holds for a supplier behind Materialized.as(...) on a timestamped aggregation such as count(): it must build a timestamped store. Builders from Stores always comply.Your build() must also not return a persistent supplier's get() — for example Stores.persistentKeyValueStore("counts").get(), or the timestamped, window or session equivalent. get() returns the byte-level RocksDB store without the commit machinery StoatFlow drives each store's epochs through, so it would never commit or write its changelog, and its state would be lost on restart. Startup refuses it with a TopologyValidationException, before any store is opened. Hand the supplier to Stores.keyValueStoreBuilder(supplier, keySerde, valueSerde) (or the windowStoreBuilder / sessionStoreBuilder equivalent) or to Materialized.as(supplier) instead. In-memory and LRU suppliers' get() stores are not affected.Keep a store's value format, type and window layout once it holds data. Switching an existing Processor API store between Stores.keyValueStoreBuilder and Stores.timestampedKeyValueStoreBuilder (or the window pair), to another store type, or to another window size or retainDuplicates setting, under the same name makes a store with a changelog refuse to start with a StoreLayoutMismatchException naming the store and both values, and the store is left untouched: its changelog holds records in the old layout — a window store's changelog keys carry each window's start, not its size — which a rebuild would misread. Give the new layout a new store name instead; that goes for a DSL windowed aggregation whose window size changes, too. Kafka Streams upgrades a plain key-value store to timestamped in place; StoatFlow's changelog keeps the timestamp in the value, so it cannot (see Changes a changelog cannot rebuild). DSL stores are timestamped whatever supplier Materialized gets, so swapping one there changes nothing, and changing a stream-stream join's JoinWindows is no layout change at all: a join reads its buffers by record timestamp.A custom versioned builder that builds a persistent store should override toInMemoryBuilder() to return its in-memory twin. With the default, which returns the builder itself, StoatFlow takes the store for an in-memory one, which cannot be read as of a commit — so under exactly_once it is refused as a table a join reads from another lane (joins under exactly-once).

The alternative is to declare the store from ProcessorSupplier.stores(), which connects it automatically — see Processor API.

import io.stoatflow.core.processor.Processor
import io.stoatflow.core.processor.ProcessorContext
import io.stoatflow.core.processor.Record
import io.stoatflow.core.state.KeyValueStore
import io.stoatflow.core.state.Stores
import io.stoatflow.core.topology.StreamsBuilder
import org.apache.kafka.common.serialization.Serdes

fun buildTopology(builder: StreamsBuilder) {
    builder.addStateStore(
        Stores.keyValueStoreBuilder(
            Stores.persistentKeyValueStore("seen-counts"),
            Serdes.String(),
            Serdes.Long(),
        ),
    )

    builder
        .stream<String, String>("events")
        .process({ CountingProcessor("seen-counts") }, "seen-counts")
}

class CountingProcessor(
    private val storeName: String,
) : Processor<String, String, String, Long> {
    private lateinit var store: KeyValueStore<String, Long>

    override fun init(context: ProcessorContext<String, Long>) {
        store = context.getStateStore(storeName)
    }

    override fun process(record: Record<String, String>) {
        val next = (store.get(record.key) ?: 0L) + 1
        store.put(record.key, next)
    }
}
A processor may only reach a store it declared.getStateStore(name) throws StoreNotConnectedException if name is not connected to that node — the Kafka Streams rule, and a fatal error rather than something processing.exception.handler can skip. Two exemptions need no declaration: global stores (addGlobalStore(...) and globalTable(...)) and read-only stores (addReadOnlyStateStore(...)).

A global store reached without declaring it is handed to the processor read-only — put/delete throw UnsupportedOperationException, as in Kafka Streams. Its own state-update processor writes to it normally. This covers every store family: plain key-value, window and session stores, and equally the timestamped, versioned and headers-aware ones. The store keeps its declared type, so getStateStore<TimestampedKeyValueStore<K, V>>(name) still returns a TimestampedKeyValueStore; only its writes throw.

To write to a global store from your own processor, declare it — process(supplier, "my-global") or ProcessorSupplier.stores() — which opts into write access. That is a StoatFlow extension (Kafka Streams rejects the declaration itself): on a single instance all state is already global, so a "global" store is an ordinary store, and the read-only default exists for Kafka Streams portability rather than safety.

Within a processor, state access is safe without any locking of your own: records with the same key always run on the same processing context in arrival order, so per-key read-modify-write is serial. The store also exposes atomic compute(key, fn) and merge(key, value, fn) for read-modify-write in a single call, and putIfAbsent(key, value) is atomic too — of two writers for an absent key, exactly one inserts and the other gets its value back. All three are atomic per key on every key-value store, headers-aware and lruMap ones included, and within a commit epoch. The function you pass to compute or merge runs while the store holds the key — on an lruMap store, the whole store — so keep it to computing the new value: never write a store from inside it (a nested write to the same store can fail, and two calls writing each other's keys can deadlock), and on an lruMap store never read another lruMap store either — two lanes doing that in opposite order wait for each other forever. See State and thread safety for the full model, including the cross-key key-lock utility and the two shapes where key affinity does not hold: a many-to-one re-key into a Processor API node, which StoatFlow refuses to compile rather than let you lock your way around, and storing under a key that is not the record key, which is computed at runtime and so cannot be caught at build time.

Deleting a key

Two calls delete a key from a KeyValueStore, and they do not cost the same:

  • store.put(key, null) writes the tombstone and nothing else.
  • store.delete(key) returns the previous value, so it has to read — and deserialise — that value before it writes the same tombstone. That is the Kafka Streams contract, and StoatFlow keeps it.

Use put(key, null) whenever you do not need the value you are deleting. The read that delete() adds is nearly free for a key written in the current commit epoch (it is still in the write-back cache), but for anything older it is a full store read — and expiry, session close-out and cleanup work, where most deletes happen, almost always delete keys written many epochs ago. StoatFlow's own DSL tombstones through put(key, null) for exactly this reason, and so does Kafka Streams.

override fun onTimer(timestamp: Long, key: String, context: TimerContext<String, Session>) {
    val sessions = context.getStateStore<KeyValueStore<String, Session>>("sessions")
    val session = sessions.get(key) ?: return
    if (session.lastActivity + SESSION_TIMEOUT_MS <= timestamp) {
        context.forward(key, session.complete())
        sessions.put(key, null) // tombstone; we already read the value above
    }
}
Two places the distinction shows up. The stoatflow.store.delete.* meters count delete() calls only — StoatFlow's DSL never makes one, so on a topology that tombstones purely through the DSL they read zero and its tombstones are counted under put. And when you do need the previous value to decide what to write, compute(key, fn) and merge(key, value, fn) do the read-modify-write atomically — there the read is the point, not overhead.

On a timestamped store a null value is an absent entry, as in Kafka Streams. Writing a ValueAndTimestamp whose value is null — or one whose value serializer returns null — deletes the key (on a window store, the window); to delete, write put(key, null) (from Java, put(key, ValueAndTimestamp.makeAllowNullable(null, ts)) does the same). merge rejects such a value with IllegalArgumentException, as Map.merge rejects a null — use put(key, null) to delete — while a null returned by the remapping function deletes the key. putIfAbsent(key, null) writes nothing. put and putIfAbsent accept null from Kotlin and Java alike, as Kafka Streams' do (merge does not — like java.util.Map.merge, it needs a value), and a window store's put(key, null, windowStart) deletes the window (a no-op on a store that retains duplicates). On a session store, put(session, null) removes the session. Reads mirror it: a stored value that your deserializer maps to null reads back as null, and an iterator yields it as a KeyValue whose value is null. The factories follow Kafka Streams too: ValueAndTimestamp.make(null, ts) returns null, and makeAllowNullable(null, ts) returns an instance holding the null.

Expiring sessions from an in-memory store

The in-memory session store keeps its sessions in one key-first map, which is what makes the per-record session merge scan a tight seek. Expiry is the one operation with no key, so by default it walks every live session on every watermark advance — about 50 ns per session in StoatFlow's reference measurement: 25 ms per barrier at 500 000 live sessions, and past roughly 3 million sessions per store the pass alone costs more than the 150 ms barrier floor. (The per-session cost depends on heap layout — the same pass measures 4–23 ns when the store's nodes sit densely packed — so 50 ns is the conservative planning figure and the thresholds below follow it.) It runs on the punctuation lane, which the commit barrier waits for, so at that size it stretches every commit of the whole application. The RocksDB session store does not have this cost (it drops whole segments).

Two things make the cliff visible before it hurts: the stoatflow.store.num.keys gauge shows the live count per in-memory store, and the store logs one warning per store the first time an expiry pass takes longer than 15 ms (a tenth of the barrier floor — about 300 000 sessions on the default scan) on a store holding at least 100 000 live sessions (so a GC pause under a small store cannot trip it). Both expiry modes are timed: without the index the warning names the opt-in below; with it, the removal volume and the RocksDB store.

The opt-in is a third argument on both in-memory session factories. It adds an end-time index beside the map, consulted only by expiry, so an expiry pass costs a logarithmic lookup plus whatever actually expires, whatever the live count:

// DSL: the explicit supplier carries the switch (it wins over withStoreType, as in Kafka Streams)
stream.groupByKey()
    .windowedBy(SessionWindows.ofInactivityGapWithNoGrace(Duration.ofMinutes(30)))
    .count(Materialized.`as`(Stores.inMemorySessionStore("sessions", Duration.ofHours(2), expiryIndex = true)))

// Processor API
builder.addStateStore(
    Stores.sessionStoreBuilder(
        Stores.inMemorySessionStore("sessions", Duration.ofHours(2), expiryIndex = true),
        Serdes.String(), Serdes.Long(),
    ),
)
// The headers-aware twin takes the same argument: Stores.inMemorySessionStoreWithHeaders(name, retention, true)

What it trades. The index moves the cost of expiry from how many sessions are alive to how many expire. The per-pass walk over the whole store goes away — about a microsecond at 500 000 sessions instead of milliseconds, and flat as the store grows. In exchange, every write pays one extra index insert (about 0.3 µs), every live session costs about 60 B more heap, and each session that does expire costs more to remove (roughly four times as much, because the index removes sessions in end-time order rather than key order). In a steady state where sessions live longer than a minute or two, the walk it removes dwarfs what it adds. Where it loses is a pass that expires a large fraction of the store at once — a watermark jump after a restore or catch-up, or sessions that end in bursts — which costs more with the index than without.

Decide on your workload, not on these numbers. They come from one host and one synthetic shape. Before opting in, run your topology under realistic traffic with the index off and on, and compare what matters to you: commit latency (stoatflow.barrier.commit.latency, since the expiry pass runs on the lane the barrier waits for), the live count (stoatflow.store.num.keys), heap, and whether the once-per-store expiry warning fires. The repository's InMemorySessionStoreExpiryCostMeasurementTest is the same comparison at store level if you want a number without a broker. As a starting point:

  • Below ~100 000 live sessions the default scan costs a few milliseconds per watermark advance at most — leave the index off.
  • From ~100 000 live sessions per store (the warning fires at ~300 000) the index is usually the right choice — confirm it against your session churn.
  • Past a few million live sessions, or when most of the store expiring in one pass is your steady state rather than an exception, use persistentSessionStore: heap is the limit in the first case, and dropping whole segments beats removing sessions one by one in the second.

Nothing about the index is persisted, so enabling it on an existing application is an ordinary restart: the changelog restore that fills the store fills the index. Under the TopologyTestDriver, a RocksDB session store coerced to its in-memory twin runs without the index (a persistent supplier has no such switch) — that affects tests only. This is a StoatFlow extension; Kafka Streams' in-memory session store is laid out end-time-first instead and pays for cheap expiry on every single-key read.

Record headers in state stores

A store can persist the processing record's Headers alongside the value — a schema id, a traceparent, tenant or routing metadata, lineage — so it survives aggregation and comes back through interactive queries and on the changelog. This is Kafka's KIP-1271 (storage) and KIP-1285 (DSL opt-in), and StoatFlow implements both.

Opt in per store, or globally:

builder
    .stream<String, String>("orders")
    .groupByKey()
    .count(
        Materialized.`as`<String, Long, StateStore>("order-counts")
            .withKeySerde(Serdes.String())
            .withValueSerde(Serdes.Long())
            .withRecordHeaders(),
    )
stoatflow:
  dsl:
    store-format: HEADERS   # table, KTable-operator, join-result and aggregation stores persist headers by default

Headers-aware stores are timestamped-only (as in Kafka Streams), covering timestamped key-value, versioned, timestamped window and session stores. Join buffers are out of scope in both engines. Query them with the QueryableStoreTypes.*WithHeaders() views, or through query() with the headers-aware query types (Querying stored headers). A headers-aware store builder needs a headers-aware supplier: Stores.timestampedKeyValueStoreWithHeadersBuilder(...), its window and session twins and StoatFlow's Stores.versionedKeyValueStoreWithHeadersBuilder(...) refuse a plain or timestamped supplier when the topology is built (Kafka Streams accepts one and keeps no headers), so pass a Stores.*WithHeaders(...) supplier. The other way round, timestampedKeyValueStoreBuilder, timestampedWindowStoreBuilder, sessionStoreBuilder and versionedKeyValueStoreBuilder build a Stores.*WithHeaders(...) supplier's store without record headers, as Kafka Streams does.

Which headers a store's serdes see. A store without record headers calls its key and value serdes with empty headers, on every write and read, so it decodes the same wherever it is read. A serde that keeps its schema id in the headers — Confluent's header mode — therefore needs a headers-aware store; StoatFlow warns once per store when a plain store's serializer writes headers it will drop. A headers-aware store serializes a write's key and value with the headers it stores (and keeps what the serializers add), a lookup's key with the current record's headers, and decodes each iterator entry with its own stored headers — on a copy, never the record's headers. See serdes in state stores.

A suppress buffer always keeps each record's headers, whatever the store format — it emits under them, as Kafka Streams does — but it is not one of these store families and has no headers view. A join or other operator that reads a suppressed table looks a key up with the headers of the record doing the reading, as Kafka Streams does: with a key serde whose bytes depend on the headers, a reader whose headers differ from the buffered record's misses the buffered entry and reads the not-yet-suppressed value.

Headers a store does not keep

A headers-aware store keeps every header of the record it stores, except a few names StoatFlow uses itself. This applies to Materialized.withRecordHeaders(), dsl.store.format=HEADERS (stoatflow.dsl.store-format: HEADERS) and the Stores.*WithHeaders* builders:

  • __stoatflow.v and every name starting with __stoatflow.v. are reserved for StoatFlow's changelog format: a changelog record can carry its format version under that name (see Upgrades and rollback). A store drops a header with a reserved name from what it stores, whether it came with the record or from a serializer, and logs one WARN per store naming the header.
  • stoatflow.epoch, the engine's stamp on records emitted under emit.mode = on-barrier, is dropped silently.

Every other header stays, including __stoatflow.vendor and the dead-letter headers __stoatflow.errors.*. A live store and a restored one hold the same headers, including a table restored from its source topic, because the restore drops the same names. Interactive queries and forwards see the stored headers.

Kafka Streams keeps every header, so this is a divergence (KSC-149). To keep such a header, rename it before the stateful step.

Turning record headers on

Flipping the flag on is a lazy in-place upgrade — no migration pause, no I/O spike. The store opens with a second RocksDB keyspace: reads check the new one and fall back to the old, converting an old-format hit on the way out (old entries read back with empty headers, which is correct — they predate the feature); writes land in the new keyspace and clear the old copy, so each key upgrades itself the first time it is touched. Windowed and session stores do this per time segment.

Turning record headers off again

Turning them off is not the mirror image, and it is worth knowing before you flip the flag.

The new keyspace is created eagerly the first time the store opens in headers mode, so it exists on disk even if nothing was ever written to it — and RocksDB refuses to open a database without naming every keyspace present. StoatFlow therefore classifies the mismatch at startup, before the store opens, and treats it as a declared format change, not corruption:

SituationWhat happens
Nothing was written in headers modeThe empty keyspace is dropped in place. Free: no acknowledgment, no restore, not a byte of data touched.
Data has migratedStartup refuses with an actionable message. Nothing on disk is touched, so an accidental flag removal costs a restart, never data.
Data has migrated, and you acknowledgeSet stoatflow.state.format-downgrade: wipe-and-restore. That store's local state is deleted and rebuilt from its changelog — one full restore, bounded by changelog size.
Data has migrated, and the store has no recovery sourceRefused unconditionally. The acknowledgment does not apply: with the changelog disabled (per store via withLoggingDisabled(), or globally) there is nothing to rebuild from, so wiping would be unrecoverable data loss.
A downgrade sheds persisted headers, and turning the flag back on does not bring them back. The old format cannot hold headers, so they are dropped from the local store; and re-enabling headers upgrades lazily, converting legacy values with empty headers. Only a forced full restore repacks them. Kafka Streams behaves the same way — it refuses the downgrade outright and leaves you to delete local state by hand; the acknowledgment key is StoatFlow's addition, so the operation is one config line rather than a manual reset.

The outcome is metered as stoatflow.store.format.downgrade.total{outcome=dropped-empty|wiped|refused}. If you take the rebuild, the restoration tuning guide covers making it fast.

Reading a store back

A store registered in your topology is queryable by name. The read-only views are typed via QueryableStoreTypes and selected with StoreQueryParameters.fromNameAndType(...):

Store kindQueryableStoreTypes factoryRead-only view
Key-valuekeyValueStore()ReadOnlyKeyValueStore<K, V>
WindowwindowStore()ReadOnlyWindowStore<K, V>
SessionsessionStore()ReadOnlySessionStore<K, AGG>
Timestamped KVtimestampedKeyValueStore()ReadOnlyKeyValueStore<K, ValueAndTimestamp<V>>
Timestamped windowtimestampedWindowStore()ReadOnlyWindowStore<K, ValueAndTimestamp<V>>
Versioned KVversionedKeyValueStore()ReadOnlyVersionedKeyValueStore<K, V>
Timestamped KV with headerstimestampedKeyValueStoreWithHeaders()ReadOnlyKeyValueStore<K, ValueTimestampHeaders<V>>
Timestamped window with headerstimestampedWindowStoreWithHeaders()ReadOnlyWindowStore<K, ValueTimestampHeaders<V>>
Session with headerssessionStoreWithHeaders()SessionStoreWithHeaders<K, AGG> (read-only at runtime)
Versioned KV with headersversionedKeyValueStoreWithHeaders()VersionedKeyValueStoreWithHeaders<K, V> (read-only at runtime)

Pick the factory by the value shape you want back. Every DSL materialisation — table(), toTable(), globalTable(), a KTable operator (filter, mapValues, transformValues, joins), a grouped or cogroup aggregation and every windowed aggregation — builds a timestamped store, and withRecordHeaders() a headers-aware one, as in Kafka Streams. The factories convert between them:

  • keyValueStore() and windowStore() accept a timestamped store or its headers-aware twin and answer with the plain value, so count() reads back as Long.
  • timestampedKeyValueStore() and timestampedWindowStore() accept the headers-aware twin too, and answer with ValueAndTimestamp: the timestamp without the headers.
  • sessionStore() accepts a headers-aware session store and answers with the plain aggregate.

Use a *WithHeaders() factory to read the headers themselves.

Every view is read-only, as in Kafka Streams, in one of two ways. When the store holds the value shape the factory promises, the view keeps the store's own interface and a write through it (put, delete, remove, expireSessions) throws UnsupportedOperationException. That holds for the two headers-aware session and versioned types too, whose factories return the full interface with its write methods. For a headers-aware session store you can hold the result as ReadOnlySessionStore<K, AggregationWithHeaders<AGG>> instead, which SessionStoreWithHeaders extends; the versioned headers-aware type has no read-only interface. When the factory converts (keyValueStore() over a timestamped store, and the other pairs above), you get a converting view that implements only the ReadOnly* interface: it has no write methods at all, and casting it to a writable store type fails with ClassCastException. Program against the ReadOnly* type you asked for. State is written by the processors connected to the store, inside the topology, where each write is part of a commit and reaches the changelog.

ReadOnlyKeyValueStore gives you get(key), containsKey(key), all(), reverseAll(), range(from, to), reverseRange(from, to), prefixScan(prefix, prefixKeySerializer), and approximateNumEntries(). Iterators must be closed after use.

Range bounds follow Kafka Streams semantics (KIP-763): a null bound is open-ended (both null ≡ all()), reverseRange takes its bounds in the same ascending (low, high) order as range, and an inverted range (from > to on the serialized key bytes) returns an empty iterator with a WARN. The same null-bound rules apply to ReadOnlyWindowStore.fetch(keyFrom, keyTo, …) and the ReadOnlySessionStore key-range queries.

StoatFlow's single-instance model means all state is globally accessible — there is no partition routing and no cross-instance RPC. Consequently StoreQueryParameters has no withPartition(...); a query against any key resolves locally. Use enableStaleStores() to allow reads while the application is still restoring.

Interactive queries against the running engine

The query entry point is store(...) on the core StoatFlow engine, which returns the requested read-only view:

import io.stoatflow.core.state.QueryableStoreTypes
import io.stoatflow.core.state.ReadOnlyKeyValueStore
import io.stoatflow.core.state.StoreQueryParameters

val store: ReadOnlyKeyValueStore<String, Long> =
    stoatflow.store(
        StoreQueryParameters.fromNameAndType(
            "word-counts",
            QueryableStoreTypes.keyValueStore(),
        ),
    )

val count: Long? = store.get("hello")

By default a query reads the store's latest state, including writes that are not committed yet, as in Kafka Streams. Isolation level for interactive queries below shows how to read only committed state instead.

store(...) throws IllegalStateException unless the application is RUNNING (or RESTORING / VALIDATING_STATE when enableStaleStores() was set), UnknownStateStoreException if the named store does not exist, and InvalidStateStoreException (as in Kafka Streams) if the store's type does not match the requested QueryableStoreType — a built-in type checks at the call, a custom type on its first read. storeNames() lists every registered store name for discovery.

A store handle looks the store up again on every read, so you can keep one for the life of the application. An in-place engine restart (for example a REPLACE_THREAD recovery) closes every store and opens it again; while that is under way a read through the handle throws InvalidStateStoreException, and once the application is RUNNING again the same handle reads the reopened store. After an HA demote the instance becomes a standby: it reports RUNNING, but a read through the handle keeps throwing InvalidStateStoreException until this instance is promoted again, so send queries to the new active instance. Retry on InvalidStateStoreException, as you would around a rebalance in Kafka Streams. An iterator opened before a restart is closed with its store. A handle also keeps serving while the application is paused (pause() stops processing, not the stores), although a new store(...) call needs RUNNING. With enableStaleStores(), a store(...) call made while the stores are still being restored throws InvalidStateStoreException; retry it.

A custom QueryableStoreType implements Kafka Streams' create(StateStoreProvider storeProvider, String storeName). Call storeProvider.stores(storeName, this) on every read rather than keeping the store it returns, so your view survives a restart too. To honour the configured isolation level, apply storeProvider.defaultIsolationLevel() with readOnly(level) to the store on each read, as the built-in types do (Kafka Streams 4.4). For a read-only view of a built-in store family, delegate to the matching built-in type: QueryableStoreTypes.keyValueStore().create(storeProvider, storeName) — it also converts a timestamped store's values to the plain value, as the built-in type does. To hand out the store exactly as it is instead, wrap the store stores(...) returned in a public ReadOnlyKeyValueStoreWrapper(store, message) (or the window / session one): it converts nothing, and it stays bound to that instance, so it does not survive a restart.

Key metadata

queryMetadataForKey answers "where does this key live?" with Kafka Streams' KeyQueryMetadata. StoatFlow is a single instance, so activeHost() is always this instance (its application.server) and standbyHosts() is empty; partition() is the key's partition in the store's changelog topic (or its source topic, for a store restored from one), and -1 for a store no topic backs — logging disabled and no source topic — since its data lives only in the local store. It is informational: every store is global, so StoatFlow never routes by it. There are four overloads, as in Kafka Streams 4.4:

OverloadPartition from
queryMetadataForKey(store, key, keySerializer)Kafka's default partitioner over keySerializer.serialize(topic, key)
queryMetadataForKey(store, key, headers, keySerializer)the same over serialize(topic, headers, key) — for a key serializer that reads headers (KIP-1321)
queryMetadataForKey(store, key, partitioner)your StreamPartitioner, called with empty headers and a null value
queryMetadataForKey(store, key, headers, partitioner)your StreamPartitioner, called with headers

If your serializer or partitioner uses headers, pass them, or the reported partition may not be the one the key was written to. The partitioner is called with a null value, as in Kafka Streams, so in Kotlin declare its value type nullable (StreamPartitioner<String, Value?>) if you use it here. A partitioner must return a single partition here: an empty or multi-partition set throws IllegalArgumentException, as in Kafka Streams, and so does Optional.empty() (Kafka Streams returns metadata without a usable partition instead). An unknown store throws UnknownStateStoreException.

store(...), query(...), storeNames() and queryMetadataForKey(...) are defined on the core StoatFlow engine, so programmatic interactive queries need a handle to that engine. A :core application holds it directly. The :runtime wrapper (StoatFlowRuntime.fromConfig) currently keeps its engine instance private and exposes no public query accessor, so typed in-process interactive queries are not available from a :runtime deployment today — use the :core API directly if you need them.

Isolation level for interactive queries

By default a query reads every write the processing lanes have made, including writes the next commit has not made durable yet — READ_UNCOMMITTED, as in Kafka Streams. Set the application to READ_COMMITTED and every handle store(...) returns reads only what the last commit made durable:

stoatflow:
  state:
    interactive-query-isolation-level: READ_COMMITTED   # Kafka Streams key: default.interactive.query.isolation.level

A single handle can choose its own level with readOnly(level), either way round. readOnly is on ReadOnlyKeyValueStore, ReadOnlyWindowStore, ReadOnlySessionStore, VersionedKeyValueStore and VersionedKeyValueStoreWithHeaders, as in Kafka Streams 4.4 (KIP-892). On a handle from store(...) it returns another handle that still looks the store up on every read; asking for the level a handle already has returns that handle.

import org.apache.kafka.common.IsolationLevel

val committed = store.readOnly(IsolationLevel.READ_COMMITTED)
val latest = committed.readOnly(IsolationLevel.READ_UNCOMMITTED)

What a READ_COMMITTED read sees:

  • The state of the last commit barrier. Under exactly-once that is the epoch whose transaction committed, so it matches what a read_committed consumer of the store's changelog sees (that consumer can trail it by a moment, while the broker writes the commit markers). Under at-least-once it is the state the last barrier flushed.
  • It lags processing by up to one commit interval (adaptive, 150 ms to 5 s by default, and longer on a quiet application) plus the commit itself, and right after a commit it can be current. A commit is readable as soon as it completes, while it is still being written to RocksDB. It is a consistent view of one commit, not a fresh one, and it never shows a write that could still be rolled back.
  • Point reads (get, fetch, fetchSession, a versioned get(key, asOf), …) read one commit. Iterators over RocksDB key-value stores and non-segmented RocksDB window and session stores read one commit too: a scan that races a commit starts again. Over in-memory stores and the default segmented window and session stores an iterator is weakly consistent: it never returns an uncommitted row, but an iterator held open can see rows from later commits — an in-memory store iterates its live data, and each segment is its own RocksDB instance, opened as the scan reaches it. Kafka Streams' segmented stores are not atomic across segments either.
  • Every store, global tables included. Kafka Streams' store() reads a global store uncommitted whatever the setting; StoatFlow applies the configured level to global stores too (KSC-144).
  • Versioned stores answer as of the last commit, validTo included: a newer, uncommitted version does not end a committed one early.
  • Stores without a commit buffer cannot honour it. An lruMap and an in-memory versioned store hold no committed state apart from their live one, so READ_COMMITTED reads them live, and StoatFlow logs a warning once per store — at startup when the application is configured READ_COMMITTED, otherwise the first time a handle asks.

approximateNumEntries() does not change with the level. approximateNumUncommittedBytes(), now on every StateStore (KIP-892), reports the bytes a store holds in memory for epochs not yet written to RocksDB — including the committed epoch still being written, which READ_COMMITTED can already read. "Uncommitted" there means memory, not visibility; the stoatflow.store.uncommitted.bytes gauge reports it per store.

In the test driver, the getters (getKeyValueStore, getWindowStore, …) read the latest writes whatever the configured level; call readOnly(IsolationLevel.READ_COMMITTED) on the store they return to read what the last commit (commitBarrier(), or each pipeInput with the default per-pipe commit) made durable. The driver runs every versioned store on the in-memory backend, so a test cannot show READ_COMMITTED for a versioned store, even one that is persistent in production.

Interactive Queries v2: query()

query(StateQueryRequest) is Kafka Streams' Interactive Queries v2 API (KIP-796), in io.stoatflow.core.query with the same types, factories and accessors as org.apache.kafka.streams.query. A request names a store and a query; the result says whether it succeeded, carries the answer, and reports how current the answer is.

import io.stoatflow.core.query.KeyQuery
import io.stoatflow.core.query.RangeQuery
import io.stoatflow.core.query.StateQueryRequest
import io.stoatflow.core.query.StateQueryResult

val result = stoatflow.query(StateQueryRequest.inStore("word-counts").withQuery(KeyQuery.withKey<String, Long?>("hello")))
val answer = result.getPartitionResults()[StateQueryResult.SINGLE_PARTITION]!!
if (answer.isSuccess()) {
    val count: Long? = answer.getResult()
} else {
    println("${answer.getFailureReason()}: ${answer.getFailureMessage()}")
}

// A range query returns an iterator: close it.
val range = StateQueryRequest.inStore("word-counts").withQuery(RangeQuery.withRange<String, Long>("a", "m"))
stoatflow.query(range).getPartitionResults()[StateQueryResult.SINGLE_PARTITION]!!.getResult().use { iterator ->
    iterator.forEach { println("${it.key} = ${it.value}") }
}

One store partition. StoatFlow is one instance with one store per name, so every successful result is keyed by partition 0 — read it with getPartitionResults()[StateQueryResult.SINGLE_PARTITION]. getGlobalResult() is always null. A request naming another partition (withPartitions(...)) gets a DOES_NOT_EXIST failure for it, the answer Kafka Streams documents; Kafka Streams itself returns NOT_PRESENT there, so a client written against that will not match. getOnlyPartitionResult() behaves as in Kafka Streams: it returns null for a successful null answer and throws next to a DOES_NOT_EXIST entry.

The queries and what they answer.

QueryStoreAnswer
KeyQuery, RangeQuerykey-value (plain, timestamped, with headers)the bare value, V
TimestampedKeyQuery, TimestampedRangeQuerytimestamped key-value (with headers too)ValueAndTimestamp<V>; on a plain key-value store UNKNOWN_QUERY_TYPE
WindowKeyQuery.withKeyAndWindowStartRangewindowWindowStoreIterator<V> — over a DSL windowed aggregation V is ValueAndTimestamp<V>, as in Kafka Streams
WindowRangeQuery.withWindowStartRangewindowKeyValueIterator<Windowed<K>, V>
WindowRangeQuery.withKeysessionKeyValueIterator<Windowed<K>, AGG>
VersionedKeyQuery (asOf)versionedVersionedRecord<V> — the latest, or the version valid at asOf
MultiVersionedKeyQuery (fromTime, toTime, order)versionedVersionedRecordIterator<V> — every version valid in the range; newest first unless withAscendingTimestamps()

A store with record headers answers these queries in the same shape, without the headers; the headers-aware query types return them. A KeyQuery or RangeQuery on a versioned store throws UnsupportedOperationException, and a MultiVersionedKeyQuery whose fromTime is after its toTime throws IllegalArgumentException, as in Kafka Streams. Any other pairing answers UNKNOWN_QUERY_TYPE, and so does a store the engine keeps for itself (a suppress buffer). The versioned range read is also on the store itself: ReadOnlyVersionedKeyValueStore.get(key, fromTime, toTime, order). On a RocksDB store both read one consistent snapshot, a few versions at a time, as Kafka Streams does: a long history neither holds up processing nor has to fit in memory at once, and opening one costs the queried key's own uncommitted writes, not the whole open epoch's. The open iterator keeps the versions it can see from being compacted away, so close it. skipCache() on KeyQuery, TimestampedKeyQuery and TimestampedKeyWithHeadersQuery is accepted and changes nothing: StoatFlow's store overlay holds the open transaction, not an eviction cache, so skipping it would change what the query may see. Use the isolation level.

Querying stored headers

Kafka Streams 4.4's headers-aware query types (KIP-1356) read a record back with its headers from a store that keeps them — a DSL store materialised withRecordHeaders() (or under dsl.store-format: HEADERS), or a Processor API store built from a Stores.*WithHeaders(...) supplier. Each element is a ReadOnlyRecord (io.stoatflow.core.processor) — key, value, timestamp, headers — and the range forms return a ReadOnlyRecordIterator (io.stoatflow.core.state).

QueryStoreAnswer
TimestampedKeyWithHeadersQuery.withKeytimestamped key-value with headersReadOnlyRecord<K, V>, or null for a missing key or a tombstone
TimestampedRangeWithHeadersQuery (withRange, withLowerBound, withUpperBound, withNoBounds; withDescendingKeys())timestamped key-value with headersReadOnlyRecordIterator<K, V>
TimestampedWindowKeyWithHeadersQuery.withKeyAndWindowStartRangetimestamped window with headersReadOnlyRecordIterator<Windowed<K>, V> — the key's windows starting in the range
TimestampedWindowRangeWithHeadersQuery.withWindowStartRangetimestamped window with headersReadOnlyRecordIterator<Windowed<K>, V> — every key's windows starting in the range
TimestampedWindowRangeWithHeadersQuery.withKeysession with headersReadOnlyRecordIterator<Windowed<K>, AGG> — the key's sessions
import io.stoatflow.core.query.StateQueryRequest
import io.stoatflow.core.query.StateQueryResult
import io.stoatflow.core.query.TimestampedKeyWithHeadersQuery
import io.stoatflow.core.query.TimestampedWindowRangeWithHeadersQuery

val record =
    stoatflow
        .query(StateQueryRequest.inStore("orders").withQuery(TimestampedKeyWithHeadersQuery.withKey<String, Long>("o-1")))
        .getPartitionResults()[StateQueryResult.SINGLE_PARTITION]!!
        .getResult()
val traceId = record?.headers()?.lastHeader("trace-id")?.value()

// A session store: one record per session, its timestamp the session's end. Close the iterator.
val sessions = StateQueryRequest.inStore("user-sessions").withQuery(TimestampedWindowRangeWithHeadersQuery.withKey<String, Long>("u-7"))
stoatflow.query(sessions).getPartitionResults()[StateQueryResult.SINGLE_PARTITION]!!.getResult().use { iterator ->
    iterator.forEach { println("${it.key().window()} = ${it.value()} @ ${it.timestamp()}") }
}
  • Frozen headers. The headers on a result are a copy, frozen: adding or removing one throws IllegalStateException. The copy is shallow, as in Kafka Streams — a header's value bytes are not copied — but every query decodes its own headers from the stored bytes, so changing them changes that record only, never the store. A record written without headers comes back with empty headers, never null.
  • Timestamps. The key-value and window queries report the stored record's event time, a negative one included (StoatFlow accepts negative event times; Kafka Streams fails such a record). A session has no event time of its own, so the session form reports the session window's end. A window's Windowed key spans [start, start + window size).
  • Which store answers. Each type is served by its headers-aware family only; every other store — the plain families, the versioned stores — answers UNKNOWN_QUERY_TYPE, without checking the position bound. Kafka Streams defines no headers query for the versioned store either. withWindowStartRange against a session store, or withKey against a window store, answers UNKNOWN_QUERY_TYPE naming the form the store supports.
  • Close the iterator, even when next() throws. A key-value or window iterator throws a StreamsException at an entry it cannot represent — a timestamp of Long.MIN_VALUE (StoatFlow's "no event time"), or a value your value serde deserializes to null — and stays open. The session form throws only for a session ending at Long.MIN_VALUE, which only a Processor API write makes; a session whose aggregate deserializes to null comes back with a null value. The point query answers a Long.MIN_VALUE timestamp with STORE_EXCEPTION.
  • Isolation and position work as for every query: READ_COMMITTED hides headers written in the open epoch.

Isolation level. A query reads at the configured isolation level; withIsolationLevel(IsolationLevel.READ_COMMITTED) sets it for one request. With enableExecutionInfo() the result names the store and the level it was read at — a store that cannot honour READ_COMMITTED reports READ_UNCOMMITTED.

Position. Every result read from the store carries a Position (a failure answered before the read, such as NOT_ACTIVE, has none): the source-topic offsets of the last commit, the same for every store. It is a lower bound under both isolation levels — the answer includes at least that much input. Pass a position back with withPositionBound(PositionBound.at(position)) and the query answers NOT_UP_TO_BOUND unless the committed position has reached it, so a reader never goes back in time. The position moves at each commit, not per record: a bound taken from a record just consumed answers NOT_UP_TO_BOUND until the next commit (up to one commit interval). A bound naming a topic StoatFlow does not read — a Kafka Streams repartition topic — is never reached. query() never waits for a bound. The position survives an in-place engine restart. It is not persisted: after a process restart it is rebuilt from the committed consumer offsets within seconds of the partition assignment, and a bound answers NOT_UP_TO_BOUND until then.

A store with logging disabled and no source topic is the exception. Nothing rebuilds it after a restart — an in-memory one comes back empty — so it reports only what this instance has committed since it started: after any restart or an HA failover, a bound on it answers NOT_UP_TO_BOUND until its partitions' next commit, rather than pass on a store that no longer holds that input. Kafka Streams' position for such a store restarts empty the same way.

When query() answers. It follows Kafka Streams' rules, not store(...)'s:

Application statequery()
any state, store name not in the topologythrows UnknownStateStoreException
not started, stopping, stopped or failedthrows IllegalStateException
HA standby, or an active handing offthrows, as store(...) does — query the active instance
starting, restoring, or an in-place engine restartNOT_ACTIVE failure; retry once RUNNING
RUNNING, PAUSED, DRAININGanswers, with or without requireActive()

So a paused application answers query() where store(...) throws — requireActive() included, as in Kafka Streams, whose pause() keeps the application's threads running. A query whose store closes while it reads — an in-place engine restart, a shutdown — answers NOT_ACTIVE too, never a partial or empty result, and so does a READ_COMMITTED read that commits kept overtaking: retry it. An iterator opened before an in-place engine restart throws InvalidStateStoreException at its next step that needs the closed store, or finishes with the entries it held when it was opened — never a mix. Query again for current data.

Reading a store in a test

In TopologyTestDriver (the in-memory test driver), read stores back directly with getKeyValueStore(name) (and getWindowStore / getSessionStore). Reads see the latest writes, cached or not. commitBarrier() commits the open epoch; with the default per-pipe commit every pipeInput already does, so call it yourself only with test.driver.commit-per-pipe=false:

import io.stoatflow.testutils.TopologyTestDriver

val driver = TopologyTestDriver.fromBuilder(builder)
// ... pipe input ...
driver.commitBarrier() // commit the epoch (only needed with commit-per-pipe=false)

val store = driver.getKeyValueStore<String, Long>("word-counts")
assertThat(store.get("the")).isEqualTo(3L)

Deep dives

  • KIP-1035: Why Kafka Streams 4.3 lets state stores own their offsetsDeep Dive — Kafka Streams kept each task's changelog offsets in a separate checkpoint file that could drift from the state it described. KIP-1035, in Kafka 4.3, moves them inside the state store — atomic with the data, and the keystone for transactional state stores.
  • KIP-1271: record headers in state stores, and the cost of a value formatDeep Dive — KIP-1271/1285 let a state store keep a record's headers next to its value — shipped in Apache Kafka 4.3.0. What the KIP is, where Kafka Streams has got to (and what is still in flight), how StoatFlow 1.0.0 compares — and why a one-varint format change becomes an engine-wide one.
  • A use-after-free in a RocksDB iterator, and the test that passed on LinuxEngineering — A StoatFlow state store layers each epoch's uncommitted writes over RocksDB in native write batches, and an iterator reads through all of them. Four defects let a batch be freed, or rewritten, under an iterator still reading it: segmentation faults, keys read twice, a value read back as garbage. None was reachable through a store StoatFlow builds. The interesting part is how we proved them — one JVM per scenario, the allocator scribbling freed memory — and why the first version of that test passed on Linux.