Table of Contents

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()
    {
    }
}

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()
    {
    }
}

Full source code: https://github.com/BEagle1984/silverback/tree/main/samples/Kafka/CatchUp.Consumer

Additional Resources