C# / .NET Kompendium PLEN
.NET / C# / Architektura rozproszona

Apache Kafka vs RabbitMQ - porównanie i implementacja w C

Czym są - fundamentalna różnica modelu

RabbitMQ to klasyczny broker wiadomości (message broker) - implementuje model kolejki: wiadomość trafia do kolejki, czeka, zostaje dostarczona i usunięta. Mówi protokołem AMQP (o czym mówiliśmy szczegółowo przy okazji Rebusa i RabbitMQ) - binarny protokół z modelem push, broker sam wypycha wiadomość do gotowego konsumenta.

Kafka to rozproszony log zdarzeń (distributed event streaming platform) - wiadomości są trwale przechowywane w partycjach przez skonfigurowany czas (retencję), niezależnie od tego, czy ktoś je odebrał. To nie jest "kolejka" w klasycznym sensie, tylko append-only log z możliwością wielokrotnego, niezależnego odczytu.

Tabela porównawcza

RabbitMQ Kafka
Model Kolejka (broker wiadomości) Rozproszony log (event streaming)
Protokół AMQP (binarny, push do konsumenta) Własny protokół binarny TCP
Trwałość po odebraniu Wiadomość usuwana po ACK Wiadomość zostaje (retencja czasowa, np. 7 dni)
Replay historii ❌ Nie (raz odebrana, zniknęła) ✅ Tak (nowy konsument może odtworzyć od początku)
Przepustowość Wysoka Bardzo wysoka (miliony wiadomości/s)
Routing Bogaty (exchange: direct/topic/fanout/headers) Prostszy (topic + partycje + klucz)
Kolejność Per-kolejka Per-partycja (nie globalnie w topicu)
Typowe zastosowanie Kolejkowanie zadań, RPC, komendy między serwisami Event sourcing, streaming logów, duże wolumeny zdarzeń, analytics
Krzywa wejścia Niższa Wyższa (partycje, consumer groups, offsety)

Najkrócej: RabbitMQ pytasz "zrób to zadanie" (komenda, ma się wykonać raz), Kafka mówisz "to się wydarzyło" (zdarzenie, może je odczytać wielu, wielokrotnie, później).

Implementacja w C# - RabbitMQ (biblioteka RabbitMQ.Client)

Producer

using RabbitMQ.Client;
using System.Text;
using System.Text.Json;

public class RabbitMqProducer : IDisposable
{
    private readonly IConnection _connection;
    private readonly IModel _channel;

    public RabbitMqProducer(string hostName = "localhost")
    {
        var factory = new ConnectionFactory { HostName = hostName };
        _connection = factory.CreateConnection();
        _channel = _connection.CreateModel();

        // Deklaracja kolejki - idempotentne, bezpieczne wywołać wielokrotnie
        _channel.QueueDeclare(queue: "orders-queue", durable: true, exclusive: false, autoDelete: false);
    }

    public void Publish(OrderPlacedEvent orderEvent)
    {
        var json = JsonSerializer.Serialize(orderEvent);
        var body = Encoding.UTF8.GetBytes(json);

        var properties = _channel.CreateBasicProperties();
        properties.Persistent = true; // wiadomość przetrwa restart brokera

        _channel.BasicPublish(exchange: "", routingKey: "orders-queue", basicProperties: properties, body: body);
    }

    public void Dispose()
    {
        _channel?.Dispose();
        _connection?.Dispose();
    }
}

Consumer

using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
using System.Text.Json;

public class RabbitMqConsumer : IDisposable
{
    private readonly IConnection _connection;
    private readonly IModel _channel;

    public RabbitMqConsumer(string hostName = "localhost")
    {
        var factory = new ConnectionFactory { HostName = hostName };
        _connection = factory.CreateConnection();
        _channel = _connection.CreateModel();
        _channel.QueueDeclare(queue: "orders-queue", durable: true, exclusive: false, autoDelete: false);
    }

    public void StartConsuming()
    {
        var consumer = new EventingBasicConsumer(_channel);

        // PUSH - broker SAM wywołuje ten handler, gdy przyjdzie wiadomość
        consumer.Received += (model, ea) =>
        {
            var json = Encoding.UTF8.GetString(ea.Body.ToArray());
            var orderEvent = JsonSerializer.Deserialize<OrderPlacedEvent>(json);

            Console.WriteLine($"Otrzymano: zamówienie {orderEvent.OrderId}");

            _channel.BasicAck(ea.DeliveryTag, multiple: false); // potwierdzenie odbioru
        };

        _channel.BasicConsume(queue: "orders-queue", autoAck: false, consumer: consumer);
    }

    public void Dispose()
    {
        _channel?.Dispose();
        _connection?.Dispose();
    }
}

Kluczowe elementy: autoAck: false + ręczny BasicAck - dopóki nie potwierdzisz, RabbitMQ uważa wiadomość za "niedostarczoną" i odda ją ponownie (np. jeśli konsument padnie w trakcie przetwarzania) - to jest ten sam mechanizm "at-least-once delivery", o którym mówiliśmy przy Outbox Pattern.

Implementacja w C# - Kafka (biblioteka Confluent.Kafka)

Producer

using Confluent.Kafka;

public class KafkaProducer : IDisposable
{
    private readonly IProducer<string, string> _producer;

    public KafkaProducer(string bootstrapServers = "localhost:9092")
    {
        var config = new ProducerConfig { BootstrapServers = bootstrapServers };
        _producer = new ProducerBuilder<string, string>(config).Build();
    }

    public async Task PublishAsync(OrderPlacedEvent orderEvent)
    {
        var json = System.Text.Json.JsonSerializer.Serialize(orderEvent);

        await _producer.ProduceAsync("order-events", new Message<string, string>
        {
            Key = orderEvent.OrderId.ToString(), // decyduje, do KTÓREJ partycji trafi (kolejność per klucz)
            Value = json
        });
    }

    public void Dispose() => _producer?.Dispose();
}

Consumer

using Confluent.Kafka;

public class KafkaConsumer
{
    private readonly IConsumer<string, string> _consumer;

    public KafkaConsumer(string bootstrapServers = "localhost:9092", string groupId = "order-service-group")
    {
        var config = new ConsumerConfig
        {
            BootstrapServers = bootstrapServers,
            GroupId = groupId, // consumer group - dzieli partycje między instancjami tej samej grupy
            AutoOffsetReset = AutoOffsetReset.Earliest
        };
        _consumer = new ConsumerBuilder<string, string>(config).Build();
    }

    public void Consume(CancellationToken cancellationToken)
    {
        _consumer.Subscribe("order-events");

        while (!cancellationToken.IsCancellationRequested)
        {
            var result = _consumer.Consume(cancellationToken); // blokuje do przyjścia wiadomości

            var orderEvent = System.Text.Json.JsonSerializer.Deserialize<OrderPlacedEvent>(result.Message.Value);
            Console.WriteLine($"Otrzymano z partycji {result.Partition}: zamówienie {orderEvent.OrderId}");

            _consumer.Commit(result); // zapisuje offset - "dotąd doczytałem"
        }
    }
}

Kluczowa różnica widoczna w kodzie: Kafka nie ma BasicAck na pojedynczej wiadomości - zamiast tego Commit() zapisuje offset (pozycję w partycji). To odzwierciedla fundamentalną różnicę modelu: RabbitMQ potwierdza konkretną wiadomość, Kafka potwierdza punkt w logu, do którego doczytałeś.

Działający przykład - uruchom RabbitMQ i Kafkę i zobacz różnicę

Poniżej kompletny, minimalny projekt konsolowy (.NET 8), który można uruchomić: jedna aplikacja z czterema trybami (rabbit-send, rabbit-receive, kafka-send, kafka-receive) i brokery w Dockerze. Wystarczy skopiować poniższe pliki do jednego folderu MessagingDemo.

1. Brokery w Dockerze - docker-compose.yml

services:
  rabbitmq:
    image: rabbitmq:3-management
    ports:
      - "5672:5672"     # AMQP (used by the app)
      - "15672:15672"   # management UI: http://localhost:15672 (guest / guest)

  kafka:
    image: apache/kafka:3.8.0   # single node, KRaft mode (no ZooKeeper)
    ports:
      - "9092:9092"
docker compose up -d   # poczekaj ok. 20 s na start Kafki

2. Projekt - MessagingDemo.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="RabbitMQ.Client" Version="7.0.0" />
    <PackageReference Include="Confluent.Kafka" Version="2.6.0" />
  </ItemGroup>

</Project>

Utworzenie od zera: dotnet new console -n MessagingDemo, potem dotnet add package RabbitMQ.Client oraz dotnet add package Confluent.Kafka. Przykład używa asynchronicznego API RabbitMQ.Client 7.x (CreateConnectionAsync, BasicPublishAsync, AsyncEventingBasicConsumer).

3. Wiadomość - OrderMessage.cs

namespace MessagingDemo;

// The message sent through both brokers (serialized as JSON).
public record OrderMessage(int Id, string Customer, decimal Amount);

4. RabbitMQ - RabbitDemo.cs

using System.Text.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;

namespace MessagingDemo;

public static class RabbitDemo
{
    private const string QueueName = "orders";

    private static ConnectionFactory CreateFactory() => new()
    {
        HostName = "localhost",
        Port = 5672,
        UserName = "guest",
        Password = "guest"
    };

    // PRODUCER: publishes messages to a queue (default exchange routes by queue name).
    public static async Task SendAsync(int count)
    {
        await using var connection = await CreateFactory().CreateConnectionAsync();
        await using var channel = await connection.CreateChannelAsync();

        // Idempotent: creates the queue if it does not exist. Durable = survives broker restart.
        await channel.QueueDeclareAsync(queue: QueueName, durable: true, exclusive: false, autoDelete: false);

        for (var i = 1; i <= count; i++)
        {
            var order = new OrderMessage(i, $"Customer {i}", 10m * i);
            var body = JsonSerializer.SerializeToUtf8Bytes(order);
            var props = new BasicProperties { Persistent = true, ContentType = "application/json" };

            await channel.BasicPublishAsync(
                exchange: string.Empty,      // default exchange: routingKey == queue name
                routingKey: QueueName,
                mandatory: false,
                basicProperties: props,
                body: body);

            Console.WriteLine($"[RabbitMQ] sent: {order}");
        }
    }

    // CONSUMER: the broker PUSHES messages; we must ACK each one, otherwise it is redelivered.
    public static async Task ReceiveAsync(CancellationToken ct)
    {
        await using var connection = await CreateFactory().CreateConnectionAsync();
        await using var channel = await connection.CreateChannelAsync();

        await channel.QueueDeclareAsync(queue: QueueName, durable: true, exclusive: false, autoDelete: false);

        // Fair dispatch: at most 1 unacknowledged message per consumer.
        await channel.BasicQosAsync(prefetchSize: 0, prefetchCount: 1, global: false);

        var consumer = new AsyncEventingBasicConsumer(channel);
        consumer.ReceivedAsync += async (_, ea) =>
        {
            var order = JsonSerializer.Deserialize<OrderMessage>(ea.Body.Span);
            Console.WriteLine($"[RabbitMQ] received: {order}");

            await Task.Delay(300); // simulate work

            // Confirm THIS message. After the ACK the broker deletes it from the queue.
            await channel.BasicAckAsync(ea.DeliveryTag, multiple: false);
        };

        await channel.BasicConsumeAsync(queue: QueueName, autoAck: false, consumer: consumer);

        Console.WriteLine("[RabbitMQ] waiting for messages... (Ctrl+C to quit)");
        try { await Task.Delay(Timeout.Infinite, ct); }
        catch (OperationCanceledException) { }
    }
}

5. Kafka - KafkaDemo.cs

using System.Text.Json;
using Confluent.Kafka;
using Confluent.Kafka.Admin;

namespace MessagingDemo;

public static class KafkaDemo
{
    private const string Topic = "orders";
    private const string Bootstrap = "localhost:9092";

    // Creates the topic with 3 partitions (does nothing if it already exists).
    private static async Task EnsureTopicAsync()
    {
        using var admin = new AdminClientBuilder(new AdminClientConfig { BootstrapServers = Bootstrap }).Build();
        try
        {
            await admin.CreateTopicsAsync(new[]
            {
                new TopicSpecification { Name = Topic, NumPartitions = 3, ReplicationFactor = 1 }
            });
        }
        catch (CreateTopicsException e) when (e.Results.All(r => r.Error.Code == ErrorCode.TopicAlreadyExists))
        {
            // already there - fine
        }
    }

    // PRODUCER: appends messages to the log. The KEY decides the partition
    // (same key => same partition => ordering is preserved per key).
    public static async Task SendAsync(int count)
    {
        await EnsureTopicAsync();

        var config = new ProducerConfig { BootstrapServers = Bootstrap, Acks = Acks.All };
        using var producer = new ProducerBuilder<string, string>(config).Build();

        for (var i = 1; i <= count; i++)
        {
            var order = new OrderMessage(i, $"Customer {i}", 10m * i);
            var message = new Message<string, string>
            {
                Key = $"customer-{i % 3}",
                Value = JsonSerializer.Serialize(order)
            };

            var result = await producer.ProduceAsync(Topic, message);
            Console.WriteLine($"[Kafka] sent: {order} -> partition {result.Partition.Value}, offset {result.Offset.Value}");
        }
    }

    // CONSUMER: PULLS messages (Consume) and remembers its position (offset) per consumer GROUP.
    // Messages are NOT deleted - another group (or a reset offset) can read them again.
    public static async Task ReceiveAsync(string groupId, CancellationToken ct)
    {
        await EnsureTopicAsync();

        var config = new ConsumerConfig
        {
            BootstrapServers = Bootstrap,
            GroupId = groupId,
            AutoOffsetReset = AutoOffsetReset.Earliest, // new group starts from the beginning of the log
            EnableAutoCommit = false                    // we commit the offset manually
        };

        using var consumer = new ConsumerBuilder<string, string>(config).Build();
        consumer.Subscribe(Topic);

        Console.WriteLine($"[Kafka] group '{groupId}' waiting for messages... (Ctrl+C to quit)");
        try
        {
            while (!ct.IsCancellationRequested)
            {
                var cr = consumer.Consume(ct);
                var order = JsonSerializer.Deserialize<OrderMessage>(cr.Message.Value);
                Console.WriteLine($"[Kafka] received: {order} (key {cr.Message.Key}, partition {cr.Partition.Value}, offset {cr.Offset.Value})");

                await Task.Delay(300); // simulate work

                // Save the position in the log - NOT an ACK of a single message.
                consumer.Commit(cr);
            }
        }
        catch (OperationCanceledException) { }
        finally
        {
            consumer.Close(); // leave the group cleanly
        }
    }
}

6. Punkt wejścia - Program.cs

using MessagingDemo;

// Usage: dotnet run -- <mode> [argument]
//   rabbit-send [count]       publish messages to RabbitMQ
//   rabbit-receive            consume messages from RabbitMQ
//   kafka-send [count]        publish messages to Kafka
//   kafka-receive [groupId]   consume messages from Kafka (default group: demo-group)

using var cts = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) => { e.Cancel = true; cts.Cancel(); };

var mode = args.Length > 0 ? args[0] : string.Empty;
var arg = args.Length > 1 ? args[1] : null;
var count = int.TryParse(arg, out var n) ? n : 5;

try
{
    switch (mode)
    {
        case "rabbit-send":    await RabbitDemo.SendAsync(count); break;
        case "rabbit-receive": await RabbitDemo.ReceiveAsync(cts.Token); break;
        case "kafka-send":     await KafkaDemo.SendAsync(count); break;
        case "kafka-receive":  await KafkaDemo.ReceiveAsync(arg ?? "demo-group", cts.Token); break;
        default:
            Console.WriteLine("Usage: dotnet run -- <rabbit-send|rabbit-receive|kafka-send|kafka-receive> [argument]");
            break;
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Error: {ex.Message}");
    Console.WriteLine("Is the broker running? Start it with: docker compose up -d");
    Environment.ExitCode = 1;
}

7. Scenariusze do wypróbowania

RabbitMQ - wiadomość znika po odebraniu:

dotnet run -- rabbit-send 5      # 5 wiadomości trafia do kolejki "orders"
dotnet run -- rabbit-receive     # odbiera 5 wiadomości (Ctrl+C kończy)
dotnet run -- rabbit-receive     # ponownie: pusto, bo po ACK wiadomości zostały usunięte

Uruchom dwa rabbit-receive naraz i wyślij więcej wiadomości - zostaną rozdzielone między konsumentów (competing consumers). Panel zarządzania: http://localhost:15672 (guest / guest).

Kafka - log można czytać wielokrotnie:

dotnet run -- kafka-send 6               # klucze customer-0/1/2 trafiają do różnych partycji
dotnet run -- kafka-receive              # grupa "demo-group" czyta wszystko od początku
dotnet run -- kafka-receive              # ta sama grupa: nic nowego (offset zapisany)
dotnet run -- kafka-receive inna-grupa   # NOWA grupa czyta całą historię jeszcze raz

Co ten przykład pokazuje

  • Ten sam komunikat, inny los: w RabbitMQ po BasicAck wiadomość znika z kolejki; w Kafce po Commit konsument tylko zapamiętuje pozycję w logu, a wiadomości zostają i może je przeczytać inna grupa.
  • Push vs pull: RabbitMQ wypycha wiadomości do konsumenta (ReceivedAsync), a konsument Kafki sam je pobiera (Consume).
  • Klucz i partycje: w Kafce Key decyduje o partycji, więc wiadomości z tym samym kluczem zachowują kolejność; w wyjściu widać partition i offset.
  • Competing consumers vs consumer groups: wielu konsumentów jednej kolejki dzieli się wiadomościami; w Kafce dzieli się nimi wielu członków jednej grupy (po partycjach), a każda kolejna grupa dostaje komplet.
  • Sprzątanie: po testach docker compose down -v usuwa brokery razem z danymi.

Kiedy które

RabbitMQ - gdy masz komendy/zadania, które mają się wykonać raz, z bogatym routingiem (fanout do wielu kolejek, routing po wzorcach) i niższą krzywą wejścia. Kafka - gdy masz zdarzenia biznesowe, które wiele niezależnych systemów chce czytać (czasem z różnym tempem), potrzebujesz replay'u historii, albo skalujesz do bardzo dużych wolumenów (logi, telemetria, event sourcing).

Relacja do pozostałych tematów na tej stronie

To porównanie zbiera w jedno miejsce wątki rozsiane po innych tematach kategorii "Distributed": Rebus (i MassTransit/NServiceBus) to biblioteki abstrahujące ponad konkretnym transportem - mogą używać RabbitMQ albo (rzadziej) Kafki "pod maską", bez zmiany kodu handlerów. Saga Pattern i Outbox Pattern dotyczą obu technologii jednakowo - niezależnie czy publikujesz przez RabbitMQ.Client czy Confluent.Kafka, potrzebujesz tej samej gwarancji atomowości zapisu i publikacji zdarzenia.

Postaw mi kawę