DEV Community

Mario Mastrodicasa
Mario Mastrodicasa

Posted on Originally published at Medium on

KEFCore performance: query optimization and persistent storage

Photo by Nicolas Hoizey on Unsplash
Photo by Nicolas Hoizey on Unsplash

Part of the KEFCore series. See also: introduction · how it works · original performance article

The original performance article compared KNetCompactedReplicator against Kafka Streams as two backend options. That comparison no longer applies — KNetCompactedReplicator has been deprecated and removed. KEFCore today is built exclusively on Kafka Streams, and the performance story is about how well you use that engine.

This article covers the query-level optimizations introduced since then, persistent storage behavior, RocksDB tuning, and the configuration knobs that matter most in production.

How KEFCore queries work

Every DbContext instance backed by KEFCore maintains a local Kafka Streams state store — either in-memory or RocksDB. LINQ queries are translated by the EF Core query pipeline and then executed against this local store. No network round-trip to the broker happens at query time; the store is always local and always up to date via the Streams topology.

The default query path is a full store scan. The optimizations described below short-circuit that scan by delegating directly to the state store API when the query shape allows it.

Store-level query optimizations

Four optimizations are available, all context-scoped (can differ between DbContext instances on the same cluster) and enabled by default:

Single key lookup — UseStoreSingleKeyLookup (default: true)

For primary key equality predicates, KEFCore calls store.get(key) directly instead of scanning:

// Full scan without optimization → O(n)
// Direct store.get(key) with optimization → O(log n) on RocksDB, O(1) on in-memory
var blog = context.Blogs.Single(b => b.BlogId == 42);
var blog = context.Blogs.Find(42);
Enter fullscreen mode Exit fullscreen mode

Key range scan — UseStoreKeyRange (default: true)

For primary key range predicates, KEFCore calls store.range(from, to):

var blogs = context.Blogs
    .Where(b => b.BlogId >= 100 && b.BlogId <= 200)
    .ToList();
Enter fullscreen mode Exit fullscreen mode

Reverse iteration — UseStoreReverse (default: true)

For Last()/LastOrDefault() without a range, KEFCore calls store.reverseAll():

var latest = context.Blogs.OrderByDescending(b => b.BlogId).First();
Enter fullscreen mode Exit fullscreen mode

Reverse range scan — UseStoreReverseKeyRange (default: true)

For Last()/LastOrDefault() with a primary key range:

var latestInRange = context.Blogs
    .Where(b => b.BlogId >= 100 && b.BlogId <= 200)
    .OrderByDescending(b => b.BlogId)
    .First();
Enter fullscreen mode Exit fullscreen mode

Per-entity overrides

All four optimizations can be overridden per entity type without affecting the global configuration:

// Via attribute
[KEFCoreStoreLookupAttribute(
    useSingleKeyLookup: true,
    useKeyRange: true,
    useReverse: false,
    useReverseKeyRange: false)]
public class Blog { ... }

// Via fluent API
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Blog>()
        .HasKEFCoreStoreLookup(useReverse: false, useReverseKeyRange: false);
}
Enter fullscreen mode Exit fullscreen mode

Disable what you do not need to reduce state store API surface and avoid unexpected behavior on non-standard key types.

In-memory vs persistent storage

UsePersistentStorage (singleton, default: false) controls the Streams state store backend:

In-memory RocksDB Startup Instant — empty store Fast — resumes from checkpoint Memory All data in RAM Spills to disk Restart behavior Full replay from topic Incremental — only new records Best for Development, short-lived processes Production, large datasets

using var context = new BloggingContext()
{
    BootstrapServers = "MY-KAFKA-BROKER:9092",
    ApplicationId = "MyApp",
    UsePersistentStorage = true,
};
Enter fullscreen mode Exit fullscreen mode

With persistent storage, the RocksDB state directory is identified by ApplicationId and the storage ID derived from the entity topic name and cluster ID. Changing any of these between restarts will produce a new storage ID and trigger a full rebuild.

To force a clean rebuild even with persistent storage — for example after a schema change — call context.Database.EnsureDeleted() before EnsureCreated(). This deletes the topics and the local state directory.

RocksDB lifecycle configuration

When UsePersistentStorage = true, per-store RocksDB options can be tuned via KEFCoreRocksDbLifecycleAttribute or fluent API. Two models are supported:

Handler type

using Org.Apache.Kafka.Streams.State;

public class MyRocksDbHandler : IRocksDbLifecycleHandler
{
    public void OnSetConfig(Org.Rocksdb.Options options,
                            IKNetConfigurationFromMap config,
                            IDictionary<string, object> data)
    {
        var blockCache = new Org.Rocksdb.LRUCache(256 * 1024 * 1024L);
        options.SetBlockBasedTableFactory(
            new Org.Rocksdb.BlockBasedTableConfig().SetBlockCache(blockCache));
        data["blockCache"] = blockCache; // keep alive - released in OnClose
    }

    public void OnClose(Org.Rocksdb.Options options, IDictionary<string, object> data)
    {
        if (data.TryGetValue("blockCache", out var bc))
            (bc as IDisposable)?.Dispose();
    }
}

[KEFCoreRocksDbLifecycleAttribute(typeof(MyRocksDbHandler))]
[Table("SensorReading")]
public class SensorReading { ... }
Enter fullscreen mode Exit fullscreen mode

Inline callbacks

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<SensorReading>()
        .HasKEFCoreRocksDbLifecycle(
            onSetConfig: (options, config, data) =>
            {
                var blockCache = new Org.Rocksdb.LRUCache(256 * 1024 * 1024L);
                options.SetBlockBasedTableFactory(
                    new Org.Rocksdb.BlockBasedTableConfig().SetBlockCache(blockCache));
                data["blockCache"] = blockCache;
            },
            onClose: (options, data) =>
            {
                if (data.TryGetValue("blockCache", out var bc))
                    (bc as IDisposable)?.Dispose();
            });
}
Enter fullscreen mode Exit fullscreen mode

The data dictionary is the per-store lifetime container. Any managed .NET object referenced by a native RocksDB component after OnSetConfig returns must be stored in data to prevent GC collection before OnClose is called.

UsePersistentStorage = true is required for RocksDB lifecycle callbacks to be invoked. With in-memory storage the callbacks are never called.

Producer configuration per entity

ProducerConfig is a cluster-level first-wins option. Individual entity types can override producer settings to achieve mixed throughput and reliability profiles on the same cluster:

// High-throughput entity: batching, compression, relaxed acks
[KEFCoreProducerAttribute(acks: "1", lingerMs: 10, batchSize: 65536,
                          compressionType: "lz4")]
[Table("MetricSample")]
public class MetricSample { ... }

// Audit entity: full durability
[KEFCoreProducerAttribute(acks: "all", retries: 5)]
[Table("AuditEvent")]
public class AuditEvent { ... }
Enter fullscreen mode Exit fullscreen mode

Or via fluent API:

modelBuilder.Entity<MetricSample>()
    .HasKEFCoreProducer(p => p
        .WithAcks("1")
        .WithLingerMs(10)
        .WithCompressionType("lz4"));
Enter fullscreen mode Exit fullscreen mode

Synchronization timeout

DefaultSynchronizationTimeout (context-scoped, default: Timeout.Infinite) controls how long KEFCore waits after SaveChanges for the Streams state store to acknowledge the new offsets:

// Wait up to 5 seconds after SaveChanges
context.DefaultSynchronizationTimeout = 5000;

// Disable synchronization - for write-only producers
context.DefaultSynchronizationTimeout = 0;
Enter fullscreen mode Exit fullscreen mode

For high-throughput write scenarios where you do not need to immediately read back what you wrote, set DefaultSynchronizationTimeout = 0:

optionsBuilder.UseKEFCore(opt => opt
    .WithBootstrapServers("KAFKA-SERVER:9092")
    .WithDefaultSynchronizationTimeout(0)
);
Enter fullscreen mode Exit fullscreen mode

Synchronization is only available when event management is enabled for the entity. If [KEFCoreIgnoreEventsAttribute] is applied or HasKEFCoreManageEvents(false) is set, the synchronization wait is skipped regardless of DefaultSynchronizationTimeout.

Event management per entity

By default KEFCore activates TimestampExtractor for all entity types, enabling real-time local state updates and post-SaveChanges synchronization. For entities that are never written by the current process — reference data, lookup tables — disable event management to reduce CPU overhead:

[KEFCoreIgnoreEventsAttribute]
[Table("CountryCodes")]
public class CountryCode { ... }

// Or globally, for pure consumers
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.UseKEFCoreManageEvents(false);
    base.OnModelCreating(modelBuilder);
}
Enter fullscreen mode Exit fullscreen mode

Data transfer: byte[] vs ByteBuffer

KEFCore supports two data transfer modes between .NET and the JVM for serialization:

  • byte[] (default): standard managed array, copied across the JVM boundary on each operation.
  • ByteBuffer : direct JVM buffer, avoids array copying — lower memory pressure and better throughput under load.
optionsBuilder.UseKEFCore(opt => opt
    .WithBootstrapServers("KAFKA-SERVER:9092")
    .WithKeyByteBufferDataTransfer() // default: false
    .WithValueContainerByteBufferDataTransfer() // default: false
);
Enter fullscreen mode Exit fullscreen mode

These are singleton options — they affect the Streams topology and must be consistent across all contexts on the same cluster. Enable ByteBuffer when throughput is a priority and your serializer supports it. The default JSON serializer supports both modes; Avro and Protobuf serializers also support ByteBuffer via their Buffered variants.

JCOBridge HPA edition

Several intermittent errors under sustained load — including TimestampExtractor callback failures — share the same root cause: non-deterministic GC interactions at the JVM↔CLR boundary under sustained call pressure.

Workarounds at the application level (disabling event management, REPLACE_THREAD recovery) reduce frequency or recover gracefully but do not eliminate the root cause. The JCOBridge HPA (High Performance Application) edition addresses these failures at the interop layer. If your application:

  • runs with event management enabled on high-throughput entities
  • uses ByteBuffer data transfer
  • experiences intermittent stream thread failures under load

then the HPA edition is the recommended path. See jcobridge.com for licensing and availability.

Where to go from here

KAFKA is a registered trademark of The Apache Software Foundation. MASES Group has no affiliation with and is not endorsed by The Apache Software Foundation.

Top comments (0)