Kafka - Catch-Up
This sample loads the in-memory state of a service from a Kafka topic: the consumer reads the whole topic at every start and notifies once all the messages written so far are processed (see Kafka Catch-Up).
What This Sample Shows
- Producing a bunch of price changes of a set of products, using the product id as message key.
- Assigning all the partitions of the topic statically with
ConsumeFromBeginning, without a consumer group and with the offsets commit disabled, so that the whole topic is consumed at every start.
- Enabling the catch-up with
NotifyWhenCaughtUp, to keep consuming (and updating the catalog) once caught up.
- Getting notified via an
IKafkaConsumerCaughtUpCallback.
- Awaiting
WaitUntilCaughtUpAsync in a BackgroundService that must not use the catalog before it's loaded.
How to Run
Start the infrastructure as described in Samples, then run the producer from the repository root: it produces 1000 price changes and exits.
dotnet run --project ./samples/Kafka/CatchUp.Producer/.
Then run the consumer.
dotnet run --project ./samples/Kafka/CatchUp.Consumer/.
Observe the console output: the callback logs that the catalog is loaded, while the background service, which waited for the catch-up, periodically reports the content of the catalog. Run the producer again, in another terminal, to see the catalog kept up to date, or restart the consumer to see it loaded again from the beginning of the topic.
Note
The producer stops after a bunch of messages, because a partition that keeps receiving messages more often than fetch.wait.max.ms may never report its end (see Kafka Catch-Up).
Common
The message being exchanged is defined in a common project.
namespace Silverback.Samples.Kafka.CatchUp.Common;
public class ProductPriceChanged
{
public string ProductId { get; set; } = "";
public decimal Price { get; set; }
}
Full source code: https://github.com/BEagle1984/silverback/tree/main/samples/Kafka/CatchUp.Common
Producer
The producer uses a hosted service to change the price of a random product 1000 times, then stops the application.
using Microsoft.Extensions.DependencyInjection;
using Silverback.Configuration;
using Silverback.Messaging.Configuration;
namespace Silverback.Samples.Kafka.CatchUp.Producer;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Enable Silverback
services.AddSilverback()
// Use Apache Kafka as message broker
.WithConnectionToMessageBroker(options => options.AddKafka())
// Delegate the broker clients configuration to a separate class
.AddBrokerClientsConfigurator<BrokerClientsConfigurator>();
// Add the hosted service that produces a bunch of price changes and stops the application
services.AddHostedService<ProducerBackgroundService>();
}
public void Configure()
{
}
}
using Silverback.Messaging.Configuration;
using Silverback.Samples.Kafka.CatchUp.Common;
namespace Silverback.Samples.Kafka.CatchUp.Producer;
public class BrokerClientsConfigurator : IBrokerClientsConfigurator
{
public void Configure(BrokerClientsConfigurationBuilder builder)
{
builder
.AddKafkaClients(
clients => clients
// The bootstrap server address is needed to connect
.WithBootstrapServers("PLAINTEXT://localhost:19092")
// Add a producer
.AddProducer(
producer => producer
// Produce the ProductPriceChanged to the samples-catch-up topic
.Produce<ProductPriceChanged>(
endpoint => endpoint
.ProduceTo("samples-catch-up")
// Use the product id as message key, so that all the
// changes of a product are written to the same partition
.SetKafkaKey(message => message?.ProductId))));
}
}
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Silverback.Messaging.Publishing;
using Silverback.Samples.Kafka.CatchUp.Common;
namespace Silverback.Samples.Kafka.CatchUp.Producer;
public class ProducerBackgroundService : BackgroundService
{
private const int ProductsCount = 20;
private const int MessagesCount = 1000;
private readonly IPublisher _publisher;
private readonly IHostApplicationLifetime _applicationLifetime;
private readonly ILogger<ProducerBackgroundService> _logger;
public ProducerBackgroundService(
IPublisher publisher,
IHostApplicationLifetime applicationLifetime,
ILogger<ProducerBackgroundService> logger)
{
_publisher = publisher;
_applicationLifetime = applicationLifetime;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
int producedCount = 0;
// Produce a bunch of price changes
for (int i = 1; i <= MessagesCount && !stoppingToken.IsCancellationRequested; i++)
{
// Change the price of a random product
string productId = $"product-{Random.Shared.Next(1, ProductsCount + 1):00}";
decimal price = Random.Shared.Next(100, 10000) / 100m;
if (await TryProduceMessageAsync(productId, price))
producedCount++;
if (i % 100 == 0)
_logger.LogInformation("Produced {Count} price changes", producedCount);
}
_logger.LogInformation("Done: {Count} price changes produced", producedCount);
// Then stop the application
_applicationLifetime.StopApplication();
}
private async Task<bool> TryProduceMessageAsync(string productId, decimal price)
{
try
{
await _publisher.PublishAsync(
new ProductPriceChanged
{
ProductId = productId,
Price = price
});
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to produce {ProductId}", productId);
return false;
}
}
}
Full source code: https://github.com/BEagle1984/silverback/tree/main/samples/Kafka/CatchUp.Producer
Consumer
The consumer applies each price change to the in-memory catalog. The callback logs once the catalog is loaded, while the background service waits for the catch-up before reporting the content of the catalog.
using Microsoft.Extensions.DependencyInjection;
using Silverback.Configuration;
using Silverback.Messaging.Configuration;
namespace Silverback.Samples.Kafka.CatchUp.Consumer;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// The in-memory state loaded from the topic
services.AddSingleton<ProductCatalog>();
// Enable Silverback
services.AddSilverback()
// Use Apache Kafka as message broker
.WithConnectionToMessageBroker(options => options.AddKafka())
// Delegate the broker clients configuration to a separate class
.AddBrokerClientsConfigurator<BrokerClientsConfigurator>()
// Register the subscriber updating the catalog
.AddSingletonSubscriber<ProductPriceChangedSubscriber>()
// Register the callback invoked once the consumer is caught up
.AddSingletonBrokerClientCallback<CatalogLoadedCallback>();
// Add the hosted service that waits until the catalog is loaded before using it
// (registered after Silverback, so that the consumer is already created)
services.AddHostedService<CatalogReportService>();
}
public void Configure()
{
}
}
using Silverback.Messaging.Configuration;
using Silverback.Samples.Kafka.CatchUp.Common;
namespace Silverback.Samples.Kafka.CatchUp.Consumer;
public class BrokerClientsConfigurator : IBrokerClientsConfigurator
{
public const string ConsumerName = "catalog-loader";
public void Configure(BrokerClientsConfigurationBuilder builder)
{
builder
.AddKafkaClients(
clients => clients
// The bootstrap server address is needed to connect
.WithBootstrapServers("PLAINTEXT://localhost:19092")
// Add a consumer, named to retrieve it from the IConsumerCollection
.AddConsumer(
ConsumerName,
consumer => consumer
// Notify once all the partitions are consumed until their end,
// then keep consuming to keep the catalog up to date
.NotifyWhenCaughtUp()
// The whole topic is consumed at every start, so there's no need
// to commit the offsets (nor to join a consumer group)
.DisableOffsetsCommit()
// Consume the ProductPriceChanged from the samples-catch-up topic
.Consume<ProductPriceChanged>(
endpoint => endpoint
// Assign all the partitions of the topic and consume
// them from the beginning
.ConsumeFromBeginning("samples-catch-up"))));
}
}
using System.Collections.Concurrent;
namespace Silverback.Samples.Kafka.CatchUp.Consumer;
public class ProductCatalog
{
private readonly ConcurrentDictionary<string, decimal> _prices = new();
public int Count => _prices.Count;
public void SetPrice(string productId, decimal price) => _prices[productId] = price;
public decimal? GetPrice(string productId) => _prices.TryGetValue(productId, out decimal price) ? price : null;
}
using Silverback.Samples.Kafka.CatchUp.Common;
namespace Silverback.Samples.Kafka.CatchUp.Consumer;
public class ProductPriceChangedSubscriber
{
private readonly ProductCatalog _catalog;
public ProductPriceChangedSubscriber(ProductCatalog catalog)
{
_catalog = catalog;
}
public void OnPriceChanged(ProductPriceChanged message) => _catalog.SetPrice(message.ProductId, message.Price);
}
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Silverback.Messaging.Broker;
using Silverback.Messaging.Broker.Callbacks;
namespace Silverback.Samples.Kafka.CatchUp.Consumer;
public class CatalogLoadedCallback : IKafkaConsumerCaughtUpCallback
{
private readonly ProductCatalog _catalog;
private readonly ILogger<CatalogLoadedCallback> _logger;
public CatalogLoadedCallback(ProductCatalog catalog, ILogger<CatalogLoadedCallback> logger)
{
_catalog = catalog;
_logger = logger;
}
// Invoked once all the messages written to the topic until now are processed
public Task OnConsumerCaughtUpAsync(IKafkaConsumer consumer)
{
_logger.LogInformation(
"Catalog loaded by {ConsumerName}: {ProductsCount} products",
consumer.Name,
_catalog.Count);
return Task.CompletedTask;
}
}
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Silverback.Messaging.Broker;
namespace Silverback.Samples.Kafka.CatchUp.Consumer;
public class CatalogReportService : BackgroundService
{
private readonly IConsumerCollection _consumers;
private readonly ProductCatalog _catalog;
private readonly ILogger<CatalogReportService> _logger;
public CatalogReportService(
IConsumerCollection consumers,
ProductCatalog catalog,
ILogger<CatalogReportService> logger)
{
_consumers = consumers;
_catalog = catalog;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
IKafkaConsumer consumer = (IKafkaConsumer)_consumers[BrokerClientsConfigurator.ConsumerName];
// Don't use the catalog until it's loaded
_logger.LogInformation("Waiting for the catalog to be loaded...");
await consumer.WaitUntilCaughtUpAsync(stoppingToken);
// The consumer keeps the catalog up to date with the new price changes
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation(
"{ProductsCount} products in the catalog, product-01 costs {Price}",
_catalog.Count,
_catalog.GetPrice("product-01"));
await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
}
}
}
Full source code: https://github.com/BEagle1984/silverback/tree/main/samples/Kafka/CatchUp.Consumer
Additional Resources