Skip to content

Apache Kafka

Giriş

Apache Kafka, yüksek performanslı, dağıtık bir event streaming platformudur. Büyük veri işleme, gerçek zamanlı veri akışı ve event-driven mimariler için ideal bir çözümdür.

Kafka Temel Kavramlar

  1. Topic
  2. Mesajların kategorize edildiği yapı
  3. Partition'lara bölünür
  4. Replication ile çoğaltılır

  5. Partition

  6. Topic'in parçalara bölünmesi
  7. Paralel işleme sağlar
  8. Sıralı mesaj garantisi

  9. Producer

  10. Mesaj üreten uygulama
  11. Partition seçimi
  12. Mesaj gönderim stratejileri

  13. Consumer

  14. Mesaj tüketen uygulama
  15. Consumer grupları
  16. Offset yönetimi

Kafka Mimarisi

  1. Broker
  2. Kafka sunucusu
  3. Topic ve partition yönetimi
  4. Replication koordinasyonu

  5. Zookeeper

  6. Cluster koordinasyonu
  7. Broker yönetimi
  8. Topic yapılandırması

  9. Cluster

  10. Birden fazla broker
  11. Yüksek erişilebilirlik
  12. Veri replikasyonu

.NET'te Kafka Kullanımı

Temel Kurulum

// NuGet paketleri
Install-Package Confluent.Kafka

Producer Örneği

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

    public KafkaProducer(string bootstrapServers)
    {
        var config = new ProducerConfig
        {
            BootstrapServers = bootstrapServers
        };

        _producer = new ProducerBuilder<Null, string>(config).Build();
    }

    public async Task ProduceAsync(string topic, string message)
    {
        try
        {
            var result = await _producer.ProduceAsync(topic, new Message<Null, string> { Value = message });
            Console.WriteLine($"Delivered to {result.TopicPartitionOffset}");
        }
        catch (ProduceException<Null, string> e)
        {
            Console.WriteLine($"Delivery failed: {e.Error.Reason}");
        }
    }

    public void Dispose()
    {
        _producer?.Dispose();
    }
}

Consumer Örneği

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

    public KafkaConsumer(string bootstrapServers, string groupId)
    {
        var config = new ConsumerConfig
        {
            BootstrapServers = bootstrapServers,
            GroupId = groupId,
            AutoOffsetReset = AutoOffsetReset.Earliest
        };

        _consumer = new ConsumerBuilder<Ignore, string>(config).Build();
    }

    public void StartConsuming(string topic, Action<string> messageHandler)
    {
        _consumer.Subscribe(topic);

        try
        {
            while (true)
            {
                var result = _consumer.Consume();
                messageHandler(result.Message.Value);
            }
        }
        catch (OperationCanceledException)
        {
            _consumer.Close();
        }
    }

    public void Dispose()
    {
        _consumer?.Dispose();
    }
}

Kafka Best Practices

  1. Topic Tasarımı
  2. Anlamlı isimlendirme
  3. Partition sayısı
  4. Replication faktörü
  5. Retention politikası

  6. Producer Yapılandırması

  7. Batch size
  8. Compression
  9. Retry politikası
  10. Timeout ayarları

  11. Consumer Yapılandırması

  12. Consumer grupları
  13. Offset yönetimi
  14. Commit stratejisi
  15. Poll interval

  16. Cluster Yapılandırması

  17. Broker sayısı
  18. Replication faktörü
  19. Network ayarları
  20. Disk yapılandırması

Kafka Monitoring

  1. JMX Metrikleri
  2. Broker metrikleri
  3. Topic metrikleri
  4. Consumer metrikleri
  5. Producer metrikleri

  6. Prometheus Integration

  7. Metrik toplama
  8. Alerting
  9. Grafana dashboards

  10. Logging

  11. Broker logs
  12. Producer logs
  13. Consumer logs
  14. Error logs

Mülakat Soruları

Temel Sorular

  1. Kafka nedir ve nasıl çalışır?
  2. Cevap: Kafka, yüksek performanslı, dağıtık bir event streaming platformudur. Topic'ler üzerinden mesajların partition'lara bölünerek işlenmesini sağlar.

  3. Kafka'da partition ve replication nedir?

  4. Cevap:

    • Partition: Topic'in parçalara bölünmesi
    • Replication: Partition'ların kopyalanması
    • Leader/Follower yapısı
    • ISR (In-Sync Replicas)
  5. Kafka'da consumer grupları nedir?

  6. Cevap:

    • Paralel işleme
    • Yük dengeleme
    • Offset yönetimi
    • Consumer rebalancing
  7. Kafka'da mesaj garantisi nasıl sağlanır?

  8. Cevap:

    • ACK mekanizması
    • ISR yapılandırması
    • Producer retry
    • Consumer commit
  9. Kafka'da yük dengeleme nasıl yapılır?

  10. Cevap:
    • Partition dağılımı
    • Consumer grupları
    • Replication
    • Load balancing

Teknik Sorular

  1. Kafka'da producer yapılandırması nasıl yapılır?
  2. Cevap:

    public class ConfiguredProducer
    {
        private readonly IProducer<Null, string> _producer;
    
        public ConfiguredProducer(string bootstrapServers)
        {
            var config = new ProducerConfig
            {
                BootstrapServers = bootstrapServers,
                Acks = Acks.All,
                MessageSendMaxRetries = 3,
                RetryBackoffMs = 1000,
                CompressionType = CompressionType.Snappy,
                BatchSize = 16384,
                LingerMs = 5
            };
    
            _producer = new ProducerBuilder<Null, string>(config).Build();
        }
    }
    

  3. Kafka'da consumer yapılandırması nasıl yapılır?

  4. Cevap:

    public class ConfiguredConsumer
    {
        private readonly IConsumer<Ignore, string> _consumer;
    
        public ConfiguredConsumer(string bootstrapServers, string groupId)
        {
            var config = new ConsumerConfig
            {
                BootstrapServers = bootstrapServers,
                GroupId = groupId,
                AutoOffsetReset = AutoOffsetReset.Earliest,
                EnableAutoCommit = false,
                MaxPollIntervalMs = 300000,
                SessionTimeoutMs = 10000,
                HeartbeatIntervalMs = 3000
            };
    
            _consumer = new ConsumerBuilder<Ignore, string>(config).Build();
        }
    }
    

  5. Kafka'da transaction nasıl kullanılır?

  6. Cevap:

    public class TransactionalProducer
    {
        private readonly IProducer<string, string> _producer;
    
        public TransactionalProducer(string bootstrapServers)
        {
            var config = new ProducerConfig
            {
                BootstrapServers = bootstrapServers,
                TransactionalId = "my-transactional-id"
            };
    
            _producer = new ProducerBuilder<string, string>(config).Build();
            _producer.InitTransactions(TimeSpan.FromSeconds(10));
        }
    
        public async Task ProduceTransactionally(string topic, string key, string value)
        {
            _producer.BeginTransaction();
            try
            {
                await _producer.ProduceAsync(topic, new Message<string, string>
                {
                    Key = key,
                    Value = value
                });
                _producer.CommitTransaction();
            }
            catch
            {
                _producer.AbortTransaction();
                throw;
            }
        }
    }
    

  7. Kafka'da consumer offset yönetimi nasıl yapılır?

  8. Cevap:

    public class OffsetManagedConsumer
    {
        private readonly IConsumer<Ignore, string> _consumer;
    
        public OffsetManagedConsumer(string bootstrapServers, string groupId)
        {
            var config = new ConsumerConfig
            {
                BootstrapServers = bootstrapServers,
                GroupId = groupId,
                EnableAutoCommit = false
            };
    
            _consumer = new ConsumerBuilder<Ignore, string>(config).Build();
        }
    
        public void ProcessMessages(string topic)
        {
            _consumer.Subscribe(topic);
    
            try
            {
                while (true)
                {
                    var result = _consumer.Consume();
                    try
                    {
                        // Process message
                        _consumer.Commit(result);
                    }
                    catch
                    {
                        // Handle error without committing offset
                    }
                }
            }
            finally
            {
                _consumer.Close();
            }
        }
    }
    

  9. Kafka'da topic yapılandırması nasıl yapılır?

  10. Cevap:
    public class TopicConfigurator
    {
        private readonly AdminClientConfig _config;
    
        public TopicConfigurator(string bootstrapServers)
        {
            _config = new AdminClientConfig
            {
                BootstrapServers = bootstrapServers
            };
        }
    
        public async Task CreateTopic(string topicName, int numPartitions, short replicationFactor)
        {
            using var adminClient = new AdminClientBuilder(_config).Build();
    
            await adminClient.CreateTopicsAsync(new[]
            {
                new TopicSpecification
                {
                    Name = topicName,
                    NumPartitions = numPartitions,
                    ReplicationFactor = replicationFactor,
                    Configs = new Dictionary<string, string>
                    {
                        { "retention.ms", "604800000" },
                        { "cleanup.policy", "delete" }
                    }
                }
            });
        }
    }
    

İleri Seviye Sorular

  1. Kafka'da cluster yapılandırması nasıl yapılır?
  2. Cevap:

    • Broker yapılandırması
    • Zookeeper yapılandırması
    • Network ayarları
    • Disk yapılandırması
    • Replication stratejisi
  3. Kafka'da high availability nasıl sağlanır?

  4. Cevap:

    • Replication
    • ISR yapılandırması
    • Broker dağılımı
    • Network redundancy
    • Failover stratejisi
  5. Kafka'da performans optimizasyonu nasıl yapılır?

  6. Cevap:

    • Partition sayısı
    • Replication faktörü
    • Producer batch size
    • Consumer poll interval
    • Disk I/O optimizasyonu
  7. Kafka'da monitoring ve alerting nasıl yapılır?

  8. Cevap:

    • JMX metrikleri
    • Prometheus integration
    • Custom metrics
    • Alert rules
    • Dashboard creation
  9. Kafka'da güvenlik nasıl sağlanır?

  10. Cevap:
    • SSL/TLS
    • SASL authentication
    • ACL yapılandırması
    • Network security
    • Encryption