DEV Community

Mario Mastrodicasa
Mario Mastrodicasa

Posted on Originally published at Medium on

KEFCore re-engineered: Apache Kafka™ as an Entity Framework Core provider, three years later

Photo by Fotis Fotopoulos on Unsplash
Photo by Fotis Fotopoulos on Unsplash

This article is a follow-up to KEFCore: Apache Kafka™ provider for Entity Framework Core. If you are new to KEFCore, start there. You may also find the how it works and use cases and performance articles useful background.

The first article showed that you could replace a SQL Server connection string with a single line and have EF Core write to and read from Apache Kafka™ topics. That core idea has not changed. What has changed substantially is everything around it: the configuration model, the conventions system, per-entity control, query optimization, schema evolution, and broker compatibility. This article covers where KEFCore stands today.

Versions and compatibility

KEFCore today ships in two active lines:

KEFCore | KNet | Apache Kafka™ | .NET
------------------------------------------
3.x | 2.9.x | 3.9.x | 8+
4.x | 3.x.x | 4.x.x | 8+
Enter fullscreen mode Exit fullscreen mode

Both lines support the full feature set described in this article. Pick the version that matches the Kafka cluster you are connecting to.

Still one line of code — but a much better foundation

The original example still works:

KEFCore.CreateGlobalInstance();
using var context = new BloggingContext()
{
    BootstrapServers = "MY-KAFKA-BROKER:9092",
    ApplicationId = "MyAppId",
    DbName = "MyDB",
};
context.Database.EnsureCreated();
context.Add(new Blog { Url = "https://example.com", Rating = 5 });
context.SaveChanges();
var blogs = context.Blogs.Where(b => b.Rating > 3).ToList();
Enter fullscreen mode Exit fullscreen mode

Under the hood, this is now built on a much more solid architecture. Two years ago KEFCore used KNetCompactedReplicator as one of its backends — a custom replication mechanism that has since been deprecated and removed. Today the engine is exclusively built on Apache Kafka™ Streams, which provides a well-understood, battle-tested local state store backed either by RocksDB or in-memory storage.

Stable topic names: the naming convention system

In the original KEFCore, topic names were derived from the full CLR type name — namespace included. Renaming a class or moving it to a different namespace would silently break alignment with existing data in the cluster.

Today, KEFCoreTopicNamingConvention resolves the topic name at model finalization time using a clear priority:

  1. [KEFCoreTopicAttribute("my-topic")] on the entity class
  2. [Table("Blog", Schema = "Blogging")] — same attribute used by EF Core for relational providers
  3. Full CLR type name (fallback — not recommended for production)

Always decorate your entities:

[Table("Blog", Schema = "Blogging")]
public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public int Rating { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Topic prefix can be set globally in OnModelCreating or per-entity:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.UseKEFCoreTopicPrefix("MyApp"); // → "MyApp.Blogging.Blog"
    base.OnModelCreating(modelBuilder);
}
Enter fullscreen mode Exit fullscreen mode

This is not just a naming nicety — it is what makes migrations safe. See conventions for the full resolution priority.

Singleton vs context-scoped options

One of the most important architectural changes is the explicit separation of options into two categories.

Singleton options are shared across all DbContext instances pointing to the same physical cluster. They affect EF Core's internal Service Provider cache key — two contexts with different singleton options will use separate Service Providers. These include serialization types, BootstrapServers, ApplicationId, and UseKNetStreams.

Context-scoped options are specific to each DbContext instance and do not affect caching. They control runtime behavior: synchronization timeouts, query optimization hints, read-only mode.

// Singleton options — must be consistent across all contexts on the same cluster
using var context = new BloggingContext()
{
    BootstrapServers = "MY-KAFKA-BROKER:9092",
    ApplicationId = "MyAppId",
    UsePersistentStorage = true, // RocksDB vs in-memory
    DefaultNumPartitions = 3,
};
// Context-scoped options - can differ per instance
context.DefaultSynchronizationTimeout = 5000; // ms
context.UseStoreSingleKeyLookup = true; // query optimization
context.ReadOnlyMode = false;
Enter fullscreen mode Exit fullscreen mode

See options for the complete reference.

Per-entity configuration

The original KEFCore had only cluster-level configuration. Today, most options can be overridden per entity type — either via attributes or fluent API.

Topic partitions and replication:

[KEFCoreTopicPartitionsAttribute(6)]
[KEFCoreTopicReplicationFactorAttribute(3)]
[Table("HighThroughputEntity")]
public class HighThroughputEntity { ... }
Enter fullscreen mode Exit fullscreen mode

Producer configuration per entity  — mix throughput and reliability profiles on the same cluster:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<AuditLog>()
        .HasKEFCoreProducer(p => p
            .WithAcks("all")
            .WithCompressionType("gzip")
            .WithLingerMs(5));
}
Enter fullscreen mode Exit fullscreen mode

Retention per entity:

modelBuilder.Entity<SessionData>()
    .HasKEFCoreTopicRetention(
        retentionMs: 86_400_000, // 24 hours
        retentionBytes: 536_870_912); // 512 MB
Enter fullscreen mode Exit fullscreen mode

Read-only entities  — prevent writes for reference data while allowing writes for others in the same SaveChanges:

[KEFCoreReadOnlyAttribute]
[Table("CountryCodes")]
public class CountryCode { ... }
Enter fullscreen mode Exit fullscreen mode

Kafka transactions and exactly-once semantics

KEFCore supports Kafka transactional producers via Database.BeginTransaction(). Assign entity types to a transaction group and they will be written atomically:

[KEFCoreTransactionalAttribute("orders")]
public class Order { ... }
[KEFCoreTransactionalAttribute("orders")]
public class OrderLine { ... }
using var tx = context.Database.BeginTransaction();
context.Orders.Add(order);
context.OrderLines.AddRange(lines);
context.SaveChanges();
tx.Commit(); // maps to CommitTransaction() on the Kafka transactional producer
Enter fullscreen mode Exit fullscreen mode

Consumers reading from these topics must set isolation.level = read_committed in their StreamsConfig to correctly filter aborted transactions.

Query optimization: talking directly to the state store

KEFCore’s query engine now includes a set of store-level optimizations that bypass full table scans by delegating directly to the underlying Kafka Streams state store:

// Single key lookup — PK equality predicate → store.get(key)
var blog = context.Blogs.Single(b => b.BlogId == 42);
// Key range - PK range → store.range(from, to)
var recent = context.Blogs
    .Where(b => b.BlogId >= 100 && b.BlogId <= 200)
    .ToList();
// Reverse iteration - Last() without range → store.reverseAll()
var latest = context.Blogs.OrderByDescending(b => b.BlogId).First();
Enter fullscreen mode Exit fullscreen mode

These are controlled by context-scoped flags (UseStoreSingleKeyLookup, UseStoreKeyRange, UseStoreReverse, UseStoreReverseKeyRange) that default to true. They can also be tuned per entity via KEFCoreStoreLookupAttribute or HasKEFCoreStoreLookup().

Persistent storage and restart behavior

UsePersistentStorage (singleton, default: false) switches the Streams state store from in-memory to RocksDB:

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

With persistent storage, on restart the Streams topology reads the RocksDB checkpoint and only consumes records produced after the previous shutdown — no full replay. For services with large datasets or frequent restarts, this reduces startup latency proportionally to the number of new records since the last run, not to the total topic size.

RocksDB options can be tuned per entity at the store level via KEFCoreRocksDbLifecycleAttribute or fluent API — block cache size, bloom filters, compaction settings, all at the individual state store level. See performance tips.

ComplexType support

EF Core ComplexTypes are fully supported. KEFCore requires them to implement value equality — detected at model finalization time by KEFCoreComplexTypeEquatableConvention:

[ComplexType]
public class Address : IEquatable<Address>
{
    public string Street { get; set; }
    public string City { get; set; }
    public bool Equals(Address other)
        => other != null && Street == other.Street && City == other.City;
    public override bool Equals(object obj) => Equals(obj as Address);
    public override int GetHashCode() => HashCode.Combine(Street, City);
}
Enter fullscreen mode Exit fullscreen mode

For types not natively supported by the underlying serializer, register a converter:

[KEFCoreComplexTypeConverterAttribute(typeof(AddressConverter))]
public class Address : IEquatable<Address> { ... }
Enter fullscreen mode Exit fullscreen mode

Schema evolution — no migrations tool required

KEFCore does not support EF Core migrations in the traditional sense. Schema evolution is handled intrinsically by the serialization layer:

  • Removed properties  — data for missing properties is silently discarded on read.
  • Added properties  — new properties not present in stored records are returned with their default value.
  • Namespace or class rename  — if you use [Table] or [KEFCoreTopicAttribute], the topic name is independent of the CLR type name. Refactoring is safe.

The one limitation: type changes on existing properties (same name, different CLR type) are not supported. See migration for details.

Broker compatibility

KEFCore communicates with the broker exclusively through the Kafka wire protocol via KNet. Any broker that implements it is compatible — not only Apache Kafka™:

Broker Compatibility
---------------------------------------------------------------
Apache Kafka™ Full
Redpanda Full
Amazon MSK Full
Confluent Platform / Cloud Full
Aiven for Apache Kafka™ Full
IBM Event Streams Full
WarpStream Full
Azure Event Hubs Partial - some Admin API features
                              may not be supported
Enter fullscreen mode Exit fullscreen mode

For brokers requiring TLS or SASL authentication:

optionsBuilder.UseKEFCore(opt => opt
    .WithBootstrapServers("KAFKA-SERVER:9093")
    .WithApplicationId("MyApp")
    .WithSecurityProtocol(SecurityProtocol.SASL_SSL)
    .WithSslConfig(new SslConfigsBuilder()
        .WithSslTruststoreLocation("/path/to/truststore.jks")
        .WithSslTruststorePassword(new Password("password")))
    .WithSaslConfig(new SaslConfigsBuilder()
        .WithSaslMechanism("PLAIN")
        .WithSaslJaasConfig(new Password(
            "org.apache.kafka.common.security.plain.PlainLoginModule required " +
            "username=\"user\" password=\"pass\";")))
);
Enter fullscreen mode Exit fullscreen mode

Reading KEFCore topics from external applications

EntityExtractor allows non-EF-Core applications to consume and deserialize records stored by KEFCore, receiving the original .NET entity objects:

KEFCore.CreateGlobalInstance();
EntityExtractor.FromTopic<Blog>(
    "MY-KAFKA-BROKER:9092",
    topicName: null, // resolved automatically from IModel
    (entity, exception) =>
    {
        if (entity != null) Console.WriteLine(entity);
    },
    cancellationToken,
    model: model);
Enter fullscreen mode Exit fullscreen mode

The topic name, serializer type, and entity type are all resolved from the model — the external application does not need to know the internal KEFCore storage format. See external application.

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)