<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dare Famuyiwa on Medium]]></title>
        <description><![CDATA[Stories by Dare Famuyiwa on Medium]]></description>
        <link>https://medium.com/@darefamuyiwa?source=rss-6696e9d06f39------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vMCBxNl3py_HOCmgfMMEyQ.jpeg</url>
            <title>Stories by Dare Famuyiwa on Medium</title>
            <link>https://medium.com/@darefamuyiwa?source=rss-6696e9d06f39------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:25:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@darefamuyiwa/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Rethinking your business latency SLAs with Apache Kafka: Speed vs durability]]></title>
            <link>https://medium.com/@darefamuyiwa/rethinking-your-business-latency-slas-with-apache-kafka-speed-vs-durability-a489ba4a3883?source=rss-6696e9d06f39------2</link>
            <guid isPermaLink="false">https://medium.com/p/a489ba4a3883</guid>
            <category><![CDATA[edge-computing]]></category>
            <category><![CDATA[latency]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[stream-processing]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Dare Famuyiwa]]></dc:creator>
            <pubDate>Sat, 28 Jan 2023 16:16:01 GMT</pubDate>
            <atom:updated>2023-01-30T05:10:34.328Z</atom:updated>
            <content:encoded><![CDATA[<p>In the past, data was sedentary, captured and stored in disparate systems that were often locked up to keep data at rest, safe and less accessible from an integration point of view.</p><p>But in recent times, with the advent of the ongoing digital transformation, data is fast becoming a first class citizen for most businesses, powering lots of business growth by accelerating innovations that deliver huge business values.</p><p>With data unleashed and set in motion with self-serving, streaming capability, increased shareability and governance across multiple decentralized teams, the speed at which data traverses your enterprise systems, pipelines and infrastructures can’t be more crucial. Reliable data delivery is key as data needs to be streamed as fast as possible in a timely predictable manner.</p><p>And when the data in motion is critical as it is often the case for most business use cases, we want to minimize data loss or not lose data at all. So, data <strong>durability</strong> and <strong>speed</strong> are intertwined and should be considered closely together in mission critical, real time systems.</p><h3>Hard vs Soft Real Time</h3><p>All real time systems are attributed with speed where data flow and delivery is time-constrained in ascertaining the correctness and success of system operations. And the definition of real time system is often subjective and can span across a spectrum, from <strong>soft</strong> at one end to <strong>hard</strong> at the other end. However, some established properties can help to categorize any real time system as either <strong>soft</strong> or <strong>hard</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r5wemAXCi9wTl9fQvPtcOw.png" /></figure><ol><li><strong>Deadline: </strong>Realtime systems are deadline driven. Deadline here, refers to the time constraint placed on an operation for it to be completed within a set time frame. The stricter the deadline, the harder the realtime. That is to say that in hard real time, if a deadline is not met, the system is seen to have failed, a late event is a wrong event unlike soft real time where windowing can be used to process late arriving events.</li><li><strong>Safety: </strong>How mission-critical are the operations of the real time system in terms of safety? Heart monitoring ECG machines and flight controllers would be <strong>hard</strong> real time as transmitted signals have to be delivered in time without delays.</li><li><strong>Predictability</strong>: How predictable is the timing behaviour of a system so that it’s behaviour is always within an acceptable range? The higher the predictability, the harder the real time.</li><li><strong>Determinism: </strong>Hard real time systems run on deterministic <strong>TSN (Time Sensitive Network) </strong>with no anomalies and delays. On the other hand, soft real time is characterized by non-deterministic network with latency spikes and network fluctuations.</li><li><strong>Time granularity</strong>: The finer the processing time, the harder the real time. <strong>Hard</strong> real time systems experience no latency with E2E <strong>microsecond</strong> processing time or smaller and often seen in embedded systems, PLC (Programmable Logic Controllers), FPGA, Assemblers in C and OP (operation technology) generally. <strong>Soft real time</strong>, on the other hand, provides a processing time of <strong>at least a few milliseconds. IT (Information Technology), </strong>software applications and tools like Kafka, RabbitMQ, AWS Kinesis, Azure Event Hubs are soft real time.</li></ol><h3>The Value of Real Time Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z9xFsgvI3iJL9zN9O0qqug.png" /></figure><p>When data is treated as a product, it can foster collaboration among data teams that can lead to valuable decision making. Unquestionably, businesses need to leverage event data the seconds they happen as data can bring huge value to any business. While this is desirable, the truth is that this data business value is not constant but diminishes over time as the data goes from hot to cold.</p><p>When it’s hot, time-critical decisions like fraud and online security threat can be detected, nipped in the bud and mitigated. We can improve customer experience, loyalty and retention using data analytics that provide actionable insights and recommendations to customers.</p><p>However, most organisations are still being conflicted as to whether to<strong> unlock</strong> their data and it set in motion to drive innovations or continue to<strong> lock it up</strong> and keep it safe. Finding a right balance between both will be key to business success.</p><h3>Latency at the Edge, Cloud and Data-center</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ueg0o9boItPVxYb9SrgNTw.gif" /></figure><p>Let’s briefly discuss some real-world use cases powered by Kafka showing low latency processing in hybrid architectures and why the need to process streaming data at scale with speed and efficiency is becoming increasing important.</p><p>While the concept of <strong>cloud</strong> and <strong>data-center </strong>may sound familiar and not far-fetched, an <strong>edge </strong>here refers to anywhere at a remote distance with limited compute, power, storage, network bandwidth, low footprint and low touch (little or no DevOps presence) like restaurants, coffee shop, retail stores, trains, cruise ships, smart factories, smart meters, trucks etc.</p><p>Often these edge locations deploy edge hardware and software like HiveCell, StarlingX, Eclipse IoT and run remotely installed Kafka and applications without the need for onsite technicians.</p><p>With the tons of data generated at the edge and for cost effectiveness, speed and security, low latency data processing is happening at the edge rather on the cloud. 5G and Cloud-native infrastructures like AWS Outposts, Multi-access Edge Compute (MEC), Azure Edge Zones, Google Anthos, AWS Direct Connect, AWS Wavelength, GCP Interconnect and Azure ExpressRoute all provide and help in delivering low latency for mission-critical applications at the edge, in a close data centre or a public cloud.</p><p>Edges like Smart Factories can be autonomous, always connected with 5G Networks. Whereas others like trains and cruise ships are characterized with online/offline capability for business continuity. When offline, customers are still able to use their phones, cards, gadgets on the trains and ships to make payments, watch movies and view travel information. When there is internet connection, the aggregated data, payment information can be replicated to the cloud using Confluent cluster linking or any replicators like MM2, uReplicator — Uber, Mirus — (Salesforce), Brooklin (LinkedIn).</p><p>On the cloud, aggregated data from all edge sites are processed together using machine learning and advanced business analytics to generate and build analytic models.</p><p>These analytic models along with commands and control events are deployed back at the edge for predictive maintenance, condition monitoring, quality assurance, early part scrapping etc.</p><p>When physical assets like hardware, IIoT in <strong>OT</strong> (Operation Technology) are optimized and maintained this way using feedback from <strong>IT</strong> (Information Technology), this is referred to as <strong>Digital Twin.</strong></p><h3>Latency As a Service Goal</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IkU4MF8HEO53_ixBQRmB3w.gif" /></figure><p>Kafka is soft real time and as events traverse non-deterministic network from producers to consumers through Kafka, there will inevitably be network jitters, latency spikes. So, ensuring a fast, reliable and predictable data processing can’t be more important.</p><p>And this is an art, an art of profiling, benchmarking, designing and tuning our data streaming pipelines where <strong>end-to-end latency </strong>is bounded against these potential unforeseen delays.</p><p>Not only the E2E latency goal that needs to be set for non-deterministic network. For most businesses, some operations cannot just fail, be down for too long or run slower than an acceptable threshold. Some business have little or no tolerance for data loss.</p><p>So, it makes sense to consider both latency/speed and durability requirements together and identify any trade-off that might need to be made between them.</p><p>The fact that the default consumer behaviour is to read only committed messages, then optimising any pipelines for durability often increases end-to-end latency because it adds replication overhead and load to the brokers.</p><p>Therefore, platform team, data team and the business must be crystal on the criticality of the business data and decide on <strong>how much downtime or data loss is acceptable</strong>. The RTO (recovery time objective) and RPO (recovery point objective) would help in ensuring business continuity in the case of a disaster.</p><p>When latency objective is set properly for worst case scenario using 99th percentile, it could translate into business success in terms of</p><ol><li>Increase in revenue: Improve customer experience, loyalty and retention.</li><li>Mitigate Risk — Fraud detection</li><li>Decrease cost — Timely early part scrapping, predictive maintenance and condition monitoring</li></ol><h3>Understanding E2E Latency</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbH-4NpztNeZhFchySQGcQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZZFdqjuxAX6SZkoUY331lg.png" /></figure><p><strong>Producer Latency: </strong>Is the time taken from when a producer sends a record to a cluster to when it is acknowledged back via a response from the cluster. Usually depicted by Kafka_producer_request_latency_avg metric.</p><p><strong>Fetch Latency</strong>: Is the time taken from when a consumer sends a fetch request to a cluster until records are fetched and returned back from the cluster. Usually depicted by Kafka_consumer_fetch_manager_fetch_size_avg metric.</p><p><strong>E2E Latency</strong>: Is the time between when the producer produces a record via KafkaProducer.send() to when that record is consumed by a consumer via KafkaConsumer.poll() .</p><p>As the E2E flow shows, latency bottlenecks🙁 could develop at a few points due to micro-bursting, garbage collection, insufficient broker (replica, network and IO) threads, poor partitioning and key strategies, hardware I/O limitation, network latency, client compression, batching, throughput, replication factor, client/broker implementation and configuration etc</p><p>One common cause of high latencies from consumer implementation is the Head of Line Blocking Problem. Let’s discuss this classic problem briefly.</p><h3>Head Of Line Blocking Problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jywkirEiuNM96RG9jVl_Bg.gif" /></figure><p>Kafka Consumer is not thread safe! This means a couple of things:</p><ol><li>Multiple consumers belonging to same group can’t exist in one thread</li><li>Multiple threads can’t safely use the same consumer</li><li>Multi-threaded access must be properly synchronized. Unsynchronized access throws ConcurrentModificationException</li><li>General Rule is <strong>One thread per consumer</strong></li></ol><p>But the <strong>One Thread per Consumer </strong>comes with a limitation that processing of records returned after each poll, max.poll.records<strong> </strong>must be done within a time limit, max.poll.interval.ms <strong>. </strong>Because the consumed records could be processed at varying processing time, it’s always a challenge to set, max.poll.interval.ms and max.poll.records<strong> </strong>that would work all the time. If poll is not called after max.poll.interval.ms<strong>, </strong>the<strong> </strong>consumer is considered dead by the group coordinator, triggering group rebalance.</p><p>Head of Line blocking a.k.a “Slow Consumer” happens when tail records are unable to be processed because records at the head are waiting for a long-running blocking operation while being processed. The blocking operation could be due to CPU, I/O, or network bound constraint, garbage collection, slow response of a third-party system, such as a database or web server.</p><p>Solving a HOL blocking in Kafka consumer fundamentally involves:</p><ol><li>Dividing records into smaller chunks and processing them in parallel while taking as much time as needed to process a record.</li><li>This would allow retry until processing succeeds if necessary.</li><li>Processing strategy that would increase parallelism without increasing partition count should be adopted</li><li>Recommend using Confluent Parallel Consumer, <a href="https://github.com/confluentinc/parallel-consumer">https://github.com/confluentinc/parallel-consumer</a></li></ol><h3>Kafka Can Operate At Near Network Speed</h3><p>Kafka uses a binary protocol over TCP for clients and brokers to connect to one another and communicate bidirectionally and compatibly via a series of request and response calls.</p><p>To prove that Kafka can operate at near network speed, instead of using Kafka as a channel of communication between a publisher and a receiver, we would attempt to use a direct point to point, P2P TCP connection between them and the compare the E2E latencies from both.</p><p>We can run these tests using this configurable project against ZKafka, KRaft, Multinode Kafka cluster, SSL secured Kafka cluster.</p><p>The P2P TCP channel communication uses netty NIO library.</p><p>This result is interesting!</p><p><a href="https://github.com/darefam/p2p-vs-kafka-latency">https://github.com/darefam/p2p-vs-kafka-latency</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a489ba4a3883" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka Bidirectional Client/Broker Compatibility]]></title>
            <link>https://medium.com/@darefamuyiwa/kafka-bidirectional-client-broker-compatibility-21c1b26e9d61?source=rss-6696e9d06f39------2</link>
            <guid isPermaLink="false">https://medium.com/p/21c1b26e9d61</guid>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[big-data-analytics]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Dare Famuyiwa]]></dc:creator>
            <pubDate>Wed, 01 Dec 2021 11:39:58 GMT</pubDate>
            <atom:updated>2021-12-03T22:16:27.897Z</atom:updated>
            <content:encoded><![CDATA[<p>Since 0.10.0.0, Kafka clients and brokers are by design, bidirectionally compatible, meaning new clients can talk to old brokers, and old clients can talk to new brokers. But, how did Kafka manage to achieve this great feat?</p><p>Moreover, as Kafka is inherently a partitioned system, clients will likely need to maintain a connection to multiple brokers in order to direct their produce or fetch requests to the appropriate broker based on the topic/partitions they send to or fetch from. So, the question here is, how does a client find out which topics along with their partitions exist, and which brokers currently host these topic partitions so that it can direct its requests to the right hosts? Where is this metadata information stored, how is it built, distributed, maintained and kept up to date over time.</p><p>This article tries to address these questions succinctly and I hope you find it useful.</p><h3>API Versioning and API Version Request</h3><p>Kafka uses a binary protocol over TCP for connections between clients and brokers. The protocol currently has about 68 APIs, each of which is defined as a request and response message pair. These message pairs are schematised and versioned using API versioning to ensure that the clients and brokers can consistently communicate and evolve over time in a compatible manner.</p><p>In order to work against multiple broker versions, clients find out what versions of the various APIs a broker supports and then use the highest API version supported by both in their requests. The list of supported API versions is exposed to clients by brokers via the ApiVersionsRequest API.</p><p>Here is the sequence of steps that clients follow to bidirectionally and compatibly communicate with the brokers</p><ol><li><strong>Determining the latest API version supported by both client and broker</strong></li></ol><ul><li>After establishing connection with the broker and before sending any request, the client sends ApiVersionsRequest to a broker.</li><li>On receiving ApiVersionsRequest, a broker returns its full list of supported ApiKeys and versions</li><li>On receiving the list, the client chooses the highest API version supported by both itself and the broker</li><li>If no such version exists, an error is reported by the client.</li></ul><p><strong>2. Fetching the cluster metadata</strong></p><ul><li>The client (Producer, Consumer or AdminClient) sends MetadataRequest to a broker via the configured Kafka bootstrap server endpoint. The client should use the cluster load balancer endpoint (recommended where available) or a list of statically configured Kafka hosts as its bootstrap server endpoint.</li><li>When any of the brokers receive the MetadataRequest, it returns the cluster metadata that describes the current state of the cluster, the topics with their partitions, the leaders for those topic partitions, and the host and port information for the brokers.</li><li>On receiving the metadata, the client caches the metadata and doesn’t repeatedly poll for update from the cluster but occasionally refreshes in metadata.max.age.ms interval or until it receives an error while processing a request e.g. NotLeaderForPartition indicating that its cached metadata is out of date. When this happens, the client just refreshes its metadata by issuing a MetadataRequest and then tries the failed request again.</li></ul><p><strong>3. Updating the cluster metadata</strong></p><ul><li>All the brokers in a Kafka cluster can respond to MetadataRequest because they all maintain a local cache of the cluster metadata.</li><li>The broker, designated as the controller is responsible for building the cluster metadata and also for initialising and updating the metadata cache of other brokers via UpdateMetadataRequest.</li><li>The controller sends the UpdateMetadataRequest to all the brokers in any of the following scenarios:</li></ul><ol><li>A broker change (New broker being added or existing broker removed)</li><li>A new offline broker</li><li>A new leader election</li><li>A ISR change notification</li><li>A broker modification</li></ol><h3>Clients send MetadataRequest to fetch cluster metadata</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uzCLG0h_eQHJHgj9iW887Q.png" /></figure><h3>A Broker designated as the Controller sends UpdateMetadataRequest to other brokers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6mI5ttGcvGivKwoK3RGwOw.png" /></figure><h3>Metadata Design Changes without Zookeeper (KIP-500)</h3><p>So, how is metadata stored, maintained and synchronised among the brokers in a Kafka ecosystem without Zookeeper?</p><p>With reference to the Pre KIP-500 diagram above, I highlight Post KIP-500 design changes below:</p><ul><li>Metadata will be stored in Kafka as an event log of stream events for timeliness, ordering, robustness and scalability in cluster metadata management.</li><li>Everything currently stored in ZooKeeper, such as brokers, topics, partitions, ISRs, configurations etc will be stored in this log.</li><li>Self-managed metadata raft quorum of controllers will replace the zookeeper quorum</li><li>One of the controllers in the raft quorum is elected as the leader of the metadata topic partition</li><li>The leader of the metadata log is called the active controller</li><li>The active controller handles all RPCs made from the brokers</li><li>Brokers register themselves with the raft quorum via the active controller, replacing Step 2 in the diagram above with Zookeeper quorum</li><li>The active controller removes a broker from the cluster metadata if it has not sent a MetadataFetch heartbeat for a while replacing same broker de-registration functionality in Zookeeper quorum</li><li>The follower controllers replicate the data written to the active controller, and serve as hot standbys</li><li>In Pre KIP-500 world, the controller publishes the metadata to other brokers (Step 10) via UpdateMetadata Request. Now the brokers fetch the metadata updates from the active controller via the MetadataFetch Request.</li><li>The brokers will persist the metadata they fetch to disk for faster recovery and metadata durability</li><li>The brokers will periodically ask for metadata updates from the active controller</li></ul><h3>Further Reading</h3><p><a href="https://cwiki.apache.org/confluence/display/KAFKA/A+Guide+To+The+Kafka+Protocol">https://cwiki.apache.org/confluence/display/KAFKA/A+Guide+To+The+Kafka+Protocol</a></p><p><a href="https://kafka.apache.org/protocol">https://kafka.apache.org/protocol</a></p><p><a href="https://cwiki.apache.org/confluence/display/KAFKA/KIP-500%3A+Replace+ZooKeeper+with+a+Self-Managed+Metadata+Quorum">https://cwiki.apache.org/confluence/display/KAFKA/KIP-500%3A+Replace+ZooKeeper+with+a+Self-Managed+Metadata+Quorum</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21c1b26e9d61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End Kafka Dataflow & Compression]]></title>
            <link>https://medium.com/@darefamuyiwa/end-to-end-kafka-dataflow-compression-c0c54388d012?source=rss-6696e9d06f39------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0c54388d012</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[kafka-compression]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[kafka-compression-codecs]]></category>
            <category><![CDATA[kafka-requests]]></category>
            <dc:creator><![CDATA[Dare Famuyiwa]]></dc:creator>
            <pubDate>Mon, 22 Nov 2021 12:05:32 GMT</pubDate>
            <atom:updated>2021-11-25T09:41:45.857Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s quickly examine how data is transmitted in and out of a Kafka pipeline between the producers, brokers and consumers.</p><p>Typically, when compression is properly configured and enabled on the producers, messages are published compressed, stored compressed on the brokers, fetched compressed and then finally decompressed by the consumers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*af6nwECgA9YosH6lISxy3Q.png" /><figcaption>Produce/Fetch Request</figcaption></figure><h3>Produce Vs Fetch Request</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*E3aCYr9JtHiThHxh95nzUQ.png" /></figure><h3>Compression Flow</h3><p>If producer compression was enabled on a pipeline, a typical request/response dataflow would be as indicated below using markers in the diagram above.</p><ul><li>The producer batches and compresses messages: <strong>1</strong></li><li>The producer publishes compressed batches of messages: <strong>2</strong></li><li>The broker receives compressed batches: <strong>3, 4</strong></li><li>The broker processes and stores the batches compresssed: <strong>5, 6, 7, 8</strong></li><li>The broker serves and sends compressed batches to consumer : <strong>10,11,12, 2</strong></li><li>The consumer decompresses the fetched batches: <strong>1</strong></li></ul><h3>Avoid Compression Anti-Pattern/Misconfiguration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*JEbNQKE04fRwre61xMdBXA.png" /></figure><p>The use of appropriate compression algorithm in data pipelines cannot be over-emphasized in order to save cost on disk storage and reduce the risk of network saturation, especially in situation where there is a limited, often expensive dedicated connection bandwidth between the client network like on-prem data-center and Kafka cluster on the cloud.</p><p>Whereas either the producers or the brokers could be configured to perform compression, consumer would inevitably have to carry out decompression.</p><p>Common challenge and issue with enabling compression is how to avoid unnecessary and unsolicited compression and decompression cost. Typical anti-pattern use cases include:</p><ul><li>Double compression on both the producers and the brokers: <strong>Shown as 1 and 4</strong> above and may happen when the cluster compression.type is not consistent with that of the producers or is not set to “producer” in order to retain the original compression codec set by the producers.</li><li>Unintended broker decompression: <strong>Shown as 1 and 5</strong> above and may happen when the cluster compression.type is inadvertently set to uncompressed while the majority of the producers are setup with their preferred compression.type.</li></ul><p>Ideally, you want to set your choicest compression.type on the producers which often have spare, easily scalable CPU cycles rather than on the Kafka cluster. Besides that, the compression type of the topics being published to and that of the Kafka cluster must be set to “producer” or same as that of the producers. Luckily enough, the compression.type = producer on Brokers and Topics by default.</p><p>Another compression evil is with older consumers (0.10.0 and lower), where down conversion becomes more expensive when compression is enabled and used on their data pipelines. This is because, for the oldest message format version 0 supported by these old Kafka client versions, the brokers always decompress the messages to assign incremental individual offsets to inner messages. So, if majority of the consumers are running 0.10.0 and lower, you may experience high CPU spikes on the brokers and overall performance degradation.</p><p>Lastly, don’t rely on the default values for batch.size, linger.ms, buffer.memory when enabling producer compression. Tweak them for better compression ratio as most compression codecs perform optimally with large batches because of intrinsic repetition between messages of the same type.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0c54388d012" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka Log Compaction]]></title>
            <link>https://medium.com/@darefamuyiwa/kafka-log-compaction-9ce31ea3da70?source=rss-6696e9d06f39------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ce31ea3da70</guid>
            <category><![CDATA[kafka-log-compaction]]></category>
            <category><![CDATA[kafka-log-retention]]></category>
            <category><![CDATA[kafka-retention-policy]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <dc:creator><![CDATA[Dare Famuyiwa]]></dc:creator>
            <pubDate>Fri, 05 Nov 2021 11:08:52 GMT</pubDate>
            <atom:updated>2021-11-05T11:08:52.773Z</atom:updated>
            <content:encoded><![CDATA[<p>Kafka supports two cleanup policies which can be specified either cluster-wide “log.cleanup.policy” or topic-level override “cleanup.policy” configuration as a comma separated list of any of these values:</p><blockquote><strong>delete</strong>: Log Retention (how long or how much of a data you want to store)<br><strong>compact</strong>: Log Compaction (where you need to only store the latest value of each key)</blockquote><p>Both delete and compact can be specified together. This could be ideal for use cases where many keys potentially go stale and never updated again and taking up disk space. So, make sure you understand the behaviour and performance characteristics of your data pipelines before using this combined policy.</p><p>In most data platforms, the Kafka data retention strategy is often a decision for both the business and data architects and should be planned because of its cost implication, data integration and dependency concerns between upstream and downstream systems, and data compliance checks and regulations like GDPR.</p><h3>Log Compaction</h3><p>Log compaction is a native Kafka retention mechanism that retains the latest value for each key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*vmqJyn1poKwIi2Ck_EKgBw.png" /></figure><h4>Use cases</h4><ul><li>To reload and restore application state after a crash or system failure from a changelog</li><li>Database change capture</li><li>Journaling for high-availability e.g. group-by like and aggregation operations</li></ul><h4>Configuring Log Compaction</h4><p>Log compaction can be enabled for a topic via a topic-level configuration override, “cleanup.policy”. The equivalent of this configuration at the broker level is “log.cleanup.policy”. Below is the list of other useful log compaction configurations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*4xmFOJgAu-1Eq1c9NMG2XA.png" /></figure><h4>How Log Compaction works</h4><p>The compaction algorithm itself is not that complicated but can be very volatile and easily forgotten. So, I decided to go visual and depict it diagrammatically rather than provide a written illustration. I hope readers will better retain their knowledge of log compaction and also use the flowchart for future reference and illustration.</p><p>In light of this, the flowchart has been annotated with relevant broker configuration settings and where appropriate with the corresponding topic level configurations. You should always override the topic-level configuration settings in most cases unless you have a justifiable reason to make cluster-wide changes that will impact all topics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DPGjvvVyd91X6_X_Wcs2PA.png" /></figure><h4>Segment View of a Partition Log</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ermlwhC23SxOM8s6AwpinA.png" /></figure><h4>Important considerations</h4><ul><li>Consider tweaking the topic-level configurations, segment.ms and/or segment.bytes if you are seeing stale messages that should have been deleted or duplicate, uncompacted records. Your producer throughput is probably low to fill up the current active segment quickly enough (default size: 1 GB) to roll it into inactive segment for log retention and compaction to kick in.</li><li>Consider using a smaller, min.cleanable.dirty.ratio as a hint to the Log cleaner thread to make segments with less dirty head eligible to compaction sooner. Although this has the potential of saving storage, log cleaner may not keep up as it cleans the dirtiest inactive segments first.</li><li>Consider setting a topic’s min.compaction.lag.ms (default value: 0) to guarantee for a minimum time period to pass after the newest message has been written to segments before they can be compacted. This would be useful if you wanted to retain messages long enough for consumers to see them before they are subject to compaction</li><li>Although not a hard guarantee, consider setting a topic’s max.compaction.lag.ms to a desirable value to ensure any inactive segment is eligible for compaction within a maximum time frame since it was last written to. This can be used to prevent log with low produce rate from remaining ineligible for compaction for an unlimited period as depicted by this configuration default value (9223372036854775807). Depending on the available cluster resources and performance, Kafka will attempt to comply to this threshold on best effort.</li><li>Consider changing the default value of delete.retention.ms (1 day) to give more allowance for offline or intermittent consumers to read tombstone records when they are finally live and connected to the cluster and do handle them accordingly to consistently update their backends or downstream dependencies.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ce31ea3da70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka Storage Internals]]></title>
            <link>https://medium.com/@darefamuyiwa/kafka-storage-internals-36606917629c?source=rss-6696e9d06f39------2</link>
            <guid isPermaLink="false">https://medium.com/p/36606917629c</guid>
            <category><![CDATA[log-compaction]]></category>
            <category><![CDATA[kafka-storage-internals]]></category>
            <category><![CDATA[cloud-os]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Dare Famuyiwa]]></dc:creator>
            <pubDate>Fri, 05 Nov 2021 10:20:09 GMT</pubDate>
            <atom:updated>2021-11-05T10:20:09.051Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s take a quick dive into Kafka storage system and see what it entails. In the end, it is hoped that this short article unravels and simplifies Kafka file system and motivates someone to work more pragmatically with Kafka. We shouldn’t treat Kafka clusters as black boxes.</p><h3>Storage Fundamentals</h3><p>Let’s say we have a topic named, login-events with 3 partitions on a single node cluster and a producer using default partitioner publishing messages to the cluster. To clarify quickly,</p><ul><li>Default Partitioner uses the algorithm, “hash(key) % Number of Partitions” to determine which partition each message will be written to by its key.</li><li>It means that messages of the same key will always be written to the same partition unless the number of partitions in a topic is changed.</li><li>For sake of understanding, we have hypothetically used integer message keys in the diagram to simplify hash-code computation as the hash(int) = int.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zlEOAffrnujuqw6r.png" /></figure><p>Besides the meta and auxiliary file types which will be explained later, a Kafka cluster contains the following hierarchical data model/structure;</p><p><strong>Topic</strong>: A category or feed name used to logically organize messages. It is divided into a number of partitions for better throughput, storage efficiency and scalability.</p><p><strong>Partition</strong>: The basic unit of storage and parallelism. In a multi-node cluster, a partition can’t be shared between brokers but can be replicated to more than one broker. Each partition is broken into one or more files called segments.</p><p><strong>Segment</strong>: A segment is an append-only physical data file that is filled sequentially with messages and their offsets. The essence of breaking each otherwise large partition into smaller segment files is to make purging of stale messages more workable with minimal overhead and cost. A segment can either be active or inactive. An active segment is the one that is currently being written to by the producer and can’t be purged or cleaned. An inactive segment is any closed segment that is eligible for deletion or compaction. A segment name is fixed-length (20 digits long) and is always the base-offset, the offset of the first message in the segment padded with trailing zeros. A segment age is the timestamp of its newest message.</p><h3>Kafka File System Overview</h3><p>Each Broker has one or more data directories specified in the server.properties file. After a short period of producer activity, the Kafka broker data directory (specified by log.dirs property) usually looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/0*L_FawDZEUAutt8tS.png" /></figure><p>The subdirectories, “<strong>login-events-0</strong>“, “<strong>login-events-1</strong>“, “<strong>login-events-2</strong>” represent the 3 topic partitions. Each partition directory contains one or more segment, index and meta files. Let’s briefly explain the purposes of root files shown.</p><ul><li><strong>cleaner-offset-checkpoint</strong>: Where Kafka checkpoints the last cleaned offset of all topic partitions. It is used to compute the dirtyRatio of inactive segments prior to log compaction. The file format is <em>&lt;topic-name&gt; &lt;partition number&gt; &lt;offset&gt;</em></li><li><strong>recovery-point-offset-checkpoint</strong>: Where Kafka tracks which messages (from-to offset) were successfully flushed to disk for each topic partition.</li><li><strong>replication-offset-checkpoint</strong>: Where Kafka tracks which messages (from-to offset) were successfully replicated to other brokers for each topic partition. It’s like an offset high water mark of the last committed, replicated message.</li><li><strong>log-start-offset-checkpoint</strong>: Where Kafka tracks the first/earliest offset of each topic partition.</li><li><strong>meta.properties</strong>: Where Kafka checkpoints the latest cluster and broker metadata like clusterId and brokerId.</li></ul><p>Besides “meta.properties”, the format of the other 4 files is;</p><blockquote><em>1st line contains the version</em></blockquote><blockquote><em>2nd line contains the number of line entries to follow</em></blockquote><blockquote><em>each line has &lt;topic-name&gt; &lt;partition number&gt; &lt;offset&gt;</em></blockquote><h3>Partition Directory Overview</h3><p><strong>Indexes</strong>: The index files are used for retrieving messages by offset or timestamp. There are three index files.</p><ul><li>“<strong>.index</strong>” suffix file maps offsets to their byte positions in the associated segment file</li><li>“<strong>.timeindex</strong>” suffix file is a time-based index file that uses the message timestamp to transverse a segment file. It shares same name as the log segment.</li><li><strong>.txnindex</strong>” suffix file is only created if a transactional producer is publishing to a topic partition. It contains all of the aborted transactions for each partition segment. The “read_committed” consumers cache it so that they can skip aborted transactional messages.</li></ul><p><strong>Idempotent Producer Snapshot</strong>: “.<strong>snapshot</strong>” suffix file is only created if an idempotent producer is publishing to a topic partition. It maps the unique producerID, PID to a message sequence number. It shares same name as the log segment, the base-offset which is the offset of the first message in the associated segment file.</p><p><strong>Leader Epoch Checkpoint</strong>: Designated as “<strong>leader-epoch-checkpoint</strong>” file on each partition, it is where Kafka checkpoints the latest recorded <em>leader epoch</em> and the leader’s latest offset upon becoming leader. Each row is a checkpoint containing two columns namely, the epoch and the offset by definition.</p><p>Others include “.deleted”, “.cleaned” and “.swap” suffix files that are used by the log cleaner to purge and swap log and index files.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36606917629c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>