<?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 Thanh Tung Dao on Medium]]></title>
        <description><![CDATA[Stories by Thanh Tung Dao on Medium]]></description>
        <link>https://medium.com/@dttung2905?source=rss-2ddf21046cf6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AFuiccq2JsHsOii4qi1rUg.jpeg</url>
            <title>Stories by Thanh Tung Dao on Medium</title>
            <link>https://medium.com/@dttung2905?source=rss-2ddf21046cf6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 06:31:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dttung2905/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[Setting Up Cilium Clustermesh with Helm: tips and gotcha’s moments]]></title>
            <link>https://dttung2905.medium.com/setting-up-cilium-clustermesh-with-helm-tips-and-gotchas-moments-e6b35c3d54a9?source=rss-2ddf21046cf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6b35c3d54a9</guid>
            <category><![CDATA[helm]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[cilium]]></category>
            <dc:creator><![CDATA[Thanh Tung Dao]]></dc:creator>
            <pubDate>Sun, 19 Nov 2023 16:16:21 GMT</pubDate>
            <atom:updated>2023-11-19T16:16:21.371Z</atom:updated>
            <content:encoded><![CDATA[<p>Setting up things following official docs is easy right? May be … may be not. In this blog, I will share my experience setting up Cilium Clustermesh with Helm and GitOps, specifically the blockers that I encountered. Hopefully, someone is going to spend lesser time setting this super useful feature up</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*2gNePxWXwnUIK0tY.png" /><figcaption>source: <a href="https://cilium.io/blog/2019/03/12/clustermesh/">https://cilium.io/blog/2019/03/12/clustermesh/</a></figcaption></figure><h3>1.Firewall network</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/0*hBYZvyggTEVDPa4Y.jpg" /><figcaption>source: the Internet</figcaption></figure><p>Let me say it out loud for you again. Firewall firewall firewall. This might be the part where you scream out uncontrollably, blaming yourself for not doing it earlier because things never works. There is a long list of rules that we have to create in the <a href="https://docs.cilium.io/en/stable/operations/system_requirements/#firewall-rules">official Cilium doc</a>. Depending on the organisation, this might be the most time-consuming part of the setting up process, simply because wehave to create a ticket and rely on someone else to setup for you.</p><h3>2. DNS /TLS</h3><p>Wow, we just jump from one hole to another (even bigger) hole is’nt it.</p><h4>2.1 Annotations — DNS record creation</h4><p>We might get an error from the other cluster’s Cilium agent pod saying that the Domain Names is not resolvable/ reachable. If you get this error, please check again whether your DNS record again. It might be in a private DNS hosted zone or even not created at all.</p><p>If we leave the DNS record management to something like <a href="https://cert-manager.io/">cert-manager</a>, its recommended to check clustermesh.apiserver.service.annotation . An example would look like this</p><pre>clustermesh:<br>  apiserver:<br>    service:<br>      annotations:<br>        external-dns.aplpha.kubernetes.io/hostname: &quot;example.hostname&quot;<br>        external-dns.alpha.kubernetes.io/ttl: &quot;1m&quot;</pre><h4>2.1 ExtraDnsNames</h4><p>Now the DNS record does exist. But this time we get another (new) error.</p><pre>&quot;transport: authentication handshake failed: tls: failed to verify certificate: x509: certificate is valid for clustermesh-apiserver.cilium.io, *.mesh.cilium.io, clustermesh-apiserver.kube-system.svc, not cluster.use1.companydomain.com\&quot;</pre><p>This can be traced back to this <a href="https://github.com/cilium/cilium/blob/d25d328955273c55814729548cb7dc32bce51c14/install/kubernetes/cilium/templates/clustermesh-apiserver/tls-certmanager/server-secret.yaml#L18-L19">line of code in Cilium</a>. I have included this below</p><pre>{{- if and (or .Values.externalWorkloads.enabled .Values.clustermesh.useAPIServer) .Values.clustermesh.apiserver.tls.auto.enabled (eq .Values.clustermesh.apiserver.tls.auto.method &quot;certmanager&quot;) }}<br>---<br>apiVersion: cert-manager.io/v1<br>kind: Certificate<br>metadata:<br>  name: clustermesh-apiserver-server-cert<br>  namespace: {{ .Release.Namespace }}<br>  {{- with .Values.clustermesh.annotations }}<br>  annotations:<br>    {{- toYaml . | nindent 4 }}<br>  {{- end }}<br>spec:<br>  issuerRef:<br>    {{- toYaml .Values.clustermesh.apiserver.tls.auto.certManagerIssuerRef | nindent 4 }}<br>  secretName: clustermesh-apiserver-server-cert<br>  commonName: clustermesh-apiserver.cilium.io<br>  dnsNames: # &lt;- HERE<br>  - clustermesh-apiserver.cilium.io<br>  - &quot;*.mesh.cilium.io&quot;<br>  - &quot;clustermesh-apiserver.{{ .Release.Namespace }}.svc&quot;<br>  {{- range $dns := .Values.clustermesh.apiserver.tls.server.extraDnsNames }}<br>  - {{ $dns | quote }}<br>  {{- end }}<br>  ipAddresses:<br>  - &quot;127.0.0.1&quot;<br>  - &quot;::1&quot;<br>  {{- range $ip := .Values.clustermesh.apiserver.tls.server.extraIpAddresses }}<br>  - {{ $ip | quote }}<br>  {{- end }}<br>  duration: {{ printf &quot;%dh0m0s&quot; (mul .Values.clustermesh.apiserver.tls.auto.certValidityDuration 24) }}<br>{{- end }}</pre><p>I think you probably have some theories in your mind. And yes, you are right. The TLS handshake is being established and the client is checking for the Common Name / Subject Alternate Names (SANs) of the Cilium Clustermesh apiserver to match the Domain Name you provided. Hence, the solution for this would be to provide value for the field clustermesh.apiserver.tls.server.extraDnsNamesso that Helm would add it to the list of SANs in the Cilium Clustermesh apiserver cert</p><h4>2.3 What about trusting CA ? Its Helm 14.1</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/0*sB_pjD-NoyiAoe-j.jpg" /><figcaption>source: the Internet</figcaption></figure><p>My advice is to use Cilium Helm chart greater than 14.0. Let me tell you why. When we create a Cilium deployment, there are two options for us: either supply our own CA or let Helm deployment auto-generate one for us.</p><p>With Helm 1.14.0, this second option is made possible as Cilium can trust different CAs from different clusters instead of using a centralised CAs for all. Even if we go with the centralised CA option ( I’m not saying which one is better) , we can always set them to be the same in clustermesh.apiserver.tls.ca.cert . The commit that allows all this to work is here <a href="https://github.com/cilium/cilium/commit/46ecd9a6516319ff97d78a05d2d7011a41d9076e">https://github.com/cilium/cilium/commit/46ecd9a6516319ff97d78a05d2d7011a41d9076e</a></p><h3>3. Cluster ID — No zero</h3><p>From the <a href="https://github.com/cilium/cilium/commit/46ecd9a6516319ff97d78a05d2d7011a41d9076e">documentation</a>, we have to give our cluster a unique numeric cluster ID.</p><pre>Each cluster must be assigned a unique human-readable name as well as a numeric cluster ID (1-255). <br>It is best to assign both these attributes at installation time of Cilium:</pre><p>Please note that it must be unique so the number must be decided before setting up clustermesh. And wait, I know you remember the 255 number, but please don’t forget number 1. It means you can’t use zero index counting and start your first cluster with ID 0</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*ny7kfSOb2StAcOSi.jpg" /><figcaption>source: its in the picture</figcaption></figure><h3>4. It takes two hands to clap</h3><p>Its by far the most confusing thing to me. On one hand, from the <a href="https://docs.cilium.io/en/stable/network/clustermesh/clustermesh/#connect-clusters">official doc</a>, it says we have to do it only once</p><pre>Finally, connect the clusters. This step only needs to be done in one direction. The connection will automatically be established in both directions:</pre><p>It means that if we want to establise a clustermesh between CLUSTER1and CLUSTER2, we just need to run this</p><pre>cilium clustermesh connect --context $CLUSTER1 --destination-context $CLUSTER2</pre><p>On the other hand, I suddenly remember: if I don’t put the client certificate and the CA of the CLUSTER1into CLUSTER2the kuberenetes secret cilium-clustermesh , how can the CLUSTER2 establish TLS connections. Further more, when I ran cilium clustermesh status for both clusters, only CLUSTER1 shows active clustermesh connection.</p><p>Hence, I finally accept that there might be nuances between setting up with CLI (like in the official docs) and Helm chart. We have to repeat whatever steps we have done on N clusters we we want to create a clustermesh with. At the time of this document, there is even an open issue for this <a href="https://github.com/cilium/cilium/issues/19057">https://github.com/cilium/cilium/issues/19057</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*euWtzYCUrcceAkYeMdo_ig.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6b35c3d54a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Kafka Connect helps move data seamlessly]]></title>
            <link>https://dttung2905.medium.com/how-kafka-connect-helps-move-data-seamlessly-1a919c65ce2d?source=rss-2ddf21046cf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a919c65ce2d</guid>
            <category><![CDATA[kafka-connect]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[debezium]]></category>
            <category><![CDATA[mirrormaker2]]></category>
            <category><![CDATA[azure-data-explorer]]></category>
            <dc:creator><![CDATA[Thanh Tung Dao]]></dc:creator>
            <pubDate>Wed, 13 Sep 2023 03:21:48 GMT</pubDate>
            <atom:updated>2023-09-13T03:21:48.628Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>My original post is written at Grab Engineering blog </em><a href="https://engineering.grab.com/kafka-connect">https://engineering.grab.com/kafka-connect</a></blockquote><p>Grab’s real-time data platform team a.k.a. Coban has written about <a href="https://engineering.grab.com/plumbing-at-scale">Plumbing at scale</a>, <a href="https://engineering.grab.com/optimally-scaling-kafka-consumer-applications">Optimally scaling Kakfa consumer applications</a>, and <a href="https://engineering.grab.com/exposing-kafka-cluster">Exposing Kafka via VPCE</a>. In this article, we will cover the importance of being able to easily move data in and out of Kafka in a low-code way and how we achieved this with Kafka Connect.</p><p>To build a <a href="https://www.cio.com/article/220351/what-is-noops-the-quest-for-fully-automated-it-operations.html">NoOps</a> managed streaming platform in Grab, the Coban team has:</p><ul><li>Engineered an ecosystem on top of Apache Kafka.</li><li>Successfully adopted it to production for both transactional and analytical use cases.</li><li>Made it a battle-tested industrial-standard platform.</li></ul><p>In 2021, the Coban team embarked on a new journey (Kafka Connect) that enables and empowers Grabbers to move data in and out of Apache Kafka seamlessly and conveniently.</p><h3>Kafka Connect stack in Grab</h3><p>This is what Coban’s Kafka Connect stack looks like today. Multiple data sources and data sinks, such as MySQL, S3 and Azure Data Explorer, have already been supported and productionised.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/0*e3aAIzmoe7UaZ1_O.png" /></figure><p>The Coban team has been using Protobuf as the serialisation-deserialisation (SerDes) format in Kafka. Therefore, the role of Confluent schema registry (shown at the top of the figure) is crucial to the Kafka Connect ecosystem, as it serves as the building block for conversions such as Protobuf-to-Avro, Protobuf-to-JSON and Protobuf-to-Parquet.</p><h3>What problems are we trying to solve?</h3><h3>Problem 1: Change Data Capture (CDC)</h3><p>In a big organisation like Grab, we handle large volumes of data and changes across many services on a daily basis, so it is important for these changes to be reflected in real time.</p><p>In addition, there are other technical challenges to be addressed:</p><ol><li>As shown in the figure below, data is written twice in the code base — once into the database (DB) and once as a message into Kafka. In order for the data in the DB and Kafka to be consistent, the two writes have to be atomic in a two-phase commit protocol (or other atomic commitment protocols), which is non-trivial and impacts availability.</li><li>Some use cases require data both before and after a change.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/0*Sn8WzebhqaBJ_aDX.png" /></figure><h3>Problem 2: Message mirroring for disaster recovery</h3><p>The Coban team has done some research on Kafka MirrorMaker, an open-source solution. While it can ensure better data consistency, it takes significant effort to adopt it onto existing Kubernetes infrastructure hosted by the Coban team and achieve high availability.</p><p>Another major challenge that the Coban team faces is offset mirroring and translation, which is a known challenge in Kafka communities. In order for Kafka consumers to seamlessly resume their work with a backup Kafka after a disaster, we need to cater for <a href="https://cwiki.apache.org/confluence/display/KAFKA/KIP-545%3A+support+automated+consumer+offset+sync+across+clusters+in+MM+2.0#:~:text=The%20offset%20translation%20is%20great,off%20at%20the%20primary%20cluster%2C">offset translation</a>.</p><h3>Data ingestion into Azure Event Hubs</h3><p>Azure Event Hubs has a Kafka-compatible interface and natively supports JSON and Avro schema. The Coban team uses Protobuf as the SerDes framework, which is not supported by Azure Event Hubs. It means that conversions have to be done for message ingestion into Azure Event Hubs.</p><h3>Solution</h3><p>To tackle these problems, the Coban team has picked Kafka Connect because:</p><ol><li>It is an open-source framework with a relatively big community that we can consult if we run into issues.</li><li>It has the ability to plug in transformations and custom conversion logic.</li></ol><p>Let us see how Kafka Connect can be used to resolve the previously mentioned problems.</p><h3>Kafka Connect with Debezium connectors</h3><p>Debezium is a framework built for capturing data changes on top of Apache Kafka and the Kafka Connect framework. It provides a series of connectors for various databases, such as MySQL, MongoDB and Cassandra.</p><p>Here are the benefits of MySQL binlog streams:</p><ol><li>They not only provide changes on data, but also give snapshots of data before and after a specific change.</li><li>Some producers no longer have to push a message to Kafka after writing a row to a MySQL database. With Debezium connectors, services can choose not to deal with Kafka and only handle MySQL data stores.</li></ol><h4>Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZyqGzlIdxFUfyVHm.png" /></figure><h4>In case of DB upgrades and outages</h4><p>DB Data Definition Language (DDL) changes, migrations, splits and outages are common in database operations, and each operation type has a systematic resolution.</p><p>The Debezium connector has built-in features to handle DDL changes made by DB migration tools, such as pt-online-schema-change, which is used by the Grab DB Ops team.</p><p>To deal with MySQL instance changes and database splits, the Coban team leverages on the Kafka Connect framework’s ability to change the offsets of connectors. By changing the offsets, Debezium connectors can properly function after DB migrations and resume binlog synchronisation from any position in any binlog file on a MySQL instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/0*j2lqrsYeS54UhMdE.png" /></figure><p>Refer to the <a href="https://debezium.io/documentation/faq/%23how_to_change_the_offsets_of_the_source_database">Debezium documentation</a> for more details.</p><h4>Success stories</h4><p>The CDC project on MySQL via Debezium connectors has been greatly successful in Grab. One of the biggest examples is its adoption in the Elasticsearch optimisation carried out by GrabFood, which has been published in <a href="https://engineering.grab.com/search-indexing-optimisation">another blog</a>.</p><h3>MirrorMaker2 with offset translation</h3><p><a href="https://github.com/apache/kafka/tree/trunk/connect/mirror">Kafka MirrorMaker2</a> (MM2), developed in and shipped together with the Apache Kafka project, is a utility to mirror messages and consumer offsets. However, in the Coban team, the MM2 stack is deployed on the Kafka Connect framework per connector because:</p><ol><li>A few Kafka Connect clusters have already been provisioned.</li><li>Compared to launching three connectors bundled in MM2, Coban can have finer controls on MirrorSourceConnector and MirrorCheckpointConnector, and manage both of them in an infrastructure-as-code way via Hashicorp Terraform.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/0*gkQp9OWJ9Bn7ZTKA.png" /></figure><h4>Success stories</h4><p>Ensuring business continuity is a key priority for Grab and this includes the ability to recover from incidents quickly. In 2021H2, there was a campaign that ran across many teams to examine the readiness and robustness of various services and middlewares. Coban’s Kafka is one of these services that proved to be robust after rounds of chaos engineering. With MM2 on Kafka Connect to mirror both messages and consumer offsets, critical services and pipelines could safely be replicated and launched across AWS regions if outages occur.</p><p>Because the Coban team has proven itself as the battle-tested Kafka service provider in Grab, other teams have also requested to migrate streams from self-managed Kafka clusters to ones managed by Coban. MM2 has been used in such migrations and brought zero downtime to the streams’ producers and consumers.</p><h3>Mirror to Azure Event Hubs with an in-house converter</h3><p>The Analytics team runs some real time ingestion and analytics projects on Azure. To support this cross-cloud use case, the Coban team has adopted MM2 for message mirroring to Azure Event Hubs.</p><p>Typically, Event Hubs only accept JSON and Avro bytes, which is incompatible with the existing SerDes framework. The Coban team has developed a custom converter that converts bytes serialised in Protobuf to JSON bytes at runtime.</p><p>These steps explain how the converter works:</p><ol><li>Deserialise bytes in Kafka to a Protobuf DynamicMessage according to a schema retrieved from the Confluent™ schema registry.</li><li>Perform a recursive post-order depth-first-search on each field descriptor in the DynamicMessage.</li><li>Convert every Protobuf field descriptor to a JSON node.</li><li>Serialise the root JSON node to bytes.</li></ol><p>The converter has not been open sourced yet.</p><h3>Deployment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/0*B6-b8TBcJXRKtvX_.png" /></figure><p>Docker containers are the Coban team’s preferred infrastructure, especially since some production Kafka clusters are already deployed on Kubernetes. The long-term goal is to provide Kafka in a software-as-a-service (SaaS) model, which is why Kubernetes was picked. The diagram below illustrates how Kafka Connect clusters are built and deployed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/0*JKFlMpv66Wq1gQSA.png" /></figure><h3>What’s next?</h3><p>The Coban team is iterating on a unified control plane to manage resources like Kafka topics, clusters and Kafka Connect. In the foreseeable future, internal users should be able to provision Kafka Connect connectors via RESTful APIs and a graphical user interface (GUI).</p><p>At the same time, the Coban team is closely working with the Data Engineering team to make Kafka Connect the preferred tool in Grab for moving data in and out of external storages (S3 and Apache Hudi).</p><h3>Coban is hiring!</h3><p>The Coban (Real-time Data Platform) team at Grab in Singapore is hiring software and site reliability engineers at all levels as we double down on growing our platform capabilities.</p><p>Join us in building state-of-the-art, mission critical, TB/hour scale data platforms that enable thousands of engineers, data scientists, and analysts to serve millions of consumers, businesses, and partners across Southeast Asia!</p><h3>Join us</h3><p>Grab is a leading superapp in Southeast Asia, providing everyday services that matter to consumers. More than just a ride-hailing and food delivery app, Grab offers a wide range of on-demand services in the region, including mobility, food, package and grocery delivery services, mobile payments, and financial services across over 400 cities in eight countries. Powered by technology and driven by heart, our mission is to drive Southeast Asia forward by creating economic empowerment for everyone. If this mission speaks to you, <a href="https://grab.careers/">join our team</a> today!</p><p><em>Originally published at </em><a href="https://engineering.grab.com/kafka-connect"><em>https://engineering.grab.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a919c65ce2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zero trust with Kafka]]></title>
            <link>https://dttung2905.medium.com/zero-trust-with-kafka-91376f7e162d?source=rss-2ddf21046cf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/91376f7e162d</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[open-policy-agent]]></category>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[strimzi]]></category>
            <category><![CDATA[hashicorp-vault]]></category>
            <dc:creator><![CDATA[Thanh Tung Dao]]></dc:creator>
            <pubDate>Wed, 13 Sep 2023 03:14:18 GMT</pubDate>
            <atom:updated>2023-09-13T03:14:18.895Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>My original post is written at Grab Engineering blog <a href="https://engineering.grab.com/zero-trust-with-kafka">https://engineering.grab.com/zero-trust-with-kafka</a></blockquote><h3>Introduction</h3><p>Grab’s real-time data platform team, also known as Coban, has been operating large-scale Kafka clusters for all Grab verticals, with a strong focus on ensuring a best-in-class-performance and 99.99% availability.</p><p>Security has always been one of Grab’s top priorities and as fraudsters continue to evolve, there is an increased need to continue strengthening the security of our data streaming platform. One of the ways of doing this is to move from a pure network-based access control to state-of-the-art security and zero trust by default, such as:</p><ul><li><strong>Authentication</strong>: The identity of any remote systems — clients and servers — is established and ascertained first, prior to any further communications.</li><li><strong>Authorisation</strong>: Access to Kafka is granted based on the principle of least privilege; no access is given by default. Kafka clients are associated with the whitelisted Kafka topics and permissions — consume or produce — they strictly need. Also, granted access is auditable.</li><li><strong>Confidentiality</strong>: All in-transit traffic is encrypted.</li></ul><h3>Solution</h3><p>We decided to use mutual Transport Layer Security (mTLS) for authentication and encryption. mTLS enables clients to authenticate servers, and servers to reciprocally authenticate clients.</p><p>Kafka supports other authentication mechanisms, like OAuth, or Salted Challenge Response Authentication Mechanism (SCRAM), but we chose mTLS because it is able to verify the peer’s identity offline. This verification ability means that systems do not need an active connection to an authentication server to ascertain the identity of a peer. This enables operating in disparate network environments, where all parties do not necessarily have access to such a central authority.</p><p>We opted for <a href="https://www.vaultproject.io/">Hashicorp Vault</a> and its <a href="https://www.vaultproject.io/docs/secrets/pki">PKI engine</a> to dynamically generate clients and servers’ certificates. This enables us to enforce the usage of short-lived certificates for clients, which is a way to mitigate the potential impact of a client certificate being compromised or maliciously shared. We said zero trust, right?</p><p>For authorisation, we chose Policy-Based Access Control (PBAC), a more scalable solution than Role-Based Access Control (RBAC), and the <a href="https://www.openpolicyagent.org/">Open Policy Agent</a> (OPA) as our policy engine, for its wide community support.</p><p>To integrate mTLS and the OPA with Kafka, we leveraged <a href="https://strimzi.io/">Strimzi</a>, the Kafka on Kubernetes operator. In a previous <a href="https://engineering.grab.com/exposing-kafka-cluster">article</a>, we have alluded to Strimzi and hinted at how it would help with scalability and cloud agnosticism. Built-in security is undoubtedly an additional driver of our adoption of Strimzi.</p><h3>Server authentication</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nlu8FgXxdD0rNIpH.png" /></figure><p>We first set up a single Root Certificate Authority (CA) for each environment (staging, production, etc.). This Root CA, in blue on the diagram, is securely managed by the Hashicorp Vault cluster. Note that the color of the certificates, keys, signing arrows and signatures on the diagrams are consistent throughout this article.</p><p>To secure the cluster’s internal communications, like the communications between the Kafka broker and Zookeeper pods, Strimzi sets up a Cluster CA, which is signed by the Root CA (step 1). The Cluster CA is then used to sign the individual Kafka broker and zookeeper certificates (step 2). Lastly, the Root CA’s public certificate is imported into the truststores of both the Kafka broker and Zookeeper (step 3), so that all pods can mutually verify their certificates when authenticating one with the other.</p><p>Strimzi’s embedded Cluster CA dynamically generates valid individual certificates when spinning up new Kafka and Zookeeper pods. The signing operation (step 2) is handled automatically by Strimzi.</p><p>For client access to Kafka brokers, Strimzi creates a different set of intermediate CA and server certificates, as shown in the next diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lIPNnpJ6YV8sY4TH.png" /></figure><p>The same Root CA from Figure 1 now signs a different intermediate CA, which the Strimzi community calls the Client CA (step 1). This naming is misleading since it does not actually sign any client certificates, but only the server certificates (step 2) that are set up on the external listener of the Kafka brokers. These server certificates are for the Kafka clients to authenticate the servers. This time, the Root CA’s public certificate will be imported into the Kafka Client truststore (step 3).</p><h3>Client authentication</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iGNQXx-MotNKyUpW.png" /></figure><p>For client authentication, the Kafka client first needs to authenticate to Hashicorp Vault and request an ephemeral certificate from the Vault PKI engine (step 1). Vault then issues a certificate and signs it using its Root CA (step 2). With this certificate, the client can now authenticate to Kafka brokers, who will use the Root CA’s public certificate already in their truststore, as previously described (step 3).</p><h3>CA tree</h3><p>Putting together the three different authentication processes we have just covered, the CA tree now looks like this. Note that this is a simplified view for a single environment, a single cluster, and two clients only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vlEkOm8xXCfuYXk8.png" /></figure><p>As mentioned earlier, each environment (staging, production, etc.) has its own Root CA. Within an environment, each Strimzi cluster has its own pair of intermediate CAs: the Cluster CA and the Client CA. At the leaf level, the Zookeeper and Kafka broker pods each have their own individual certificates.</p><p>On the right side of the diagram, each Kafka client can get an ephemeral certificate from Hashicorp Vault whenever they need to connect to Kafka. Each team or application has a dedicated Vault PKI role in Hashicorp Vault, restricting what can be requested for its certificate (e.g., Subject, TTL, etc.).</p><h3>Strimzi deployment</h3><p>We heavily use Terraform to manage and provision our Kafka and Kafka-related components. This enables us to quickly and reliably spin up new clusters and perform cluster scaling operations.</p><p>Under the hood, Strimzi Kafka deployment is a Kubernetes deployment. To increase the performance and the reliability of the Kafka cluster, we create dedicated Kubernetes nodes for each Strimzi Kafka broker and each Zookeeper pod, using <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/">Kubernetes taints and tolerations</a>. This ensures that all resources of a single node are dedicated solely to either a single Kafka broker or a single Zookeeper pod.</p><p>We also decided to go with a single Kafka cluster by Kubernetes cluster to make the management easier.</p><h3>Client setup</h3><p>Coban provides backend microservice teams from all Grab verticals with a popular Kafka SDK in Golang, to standardise how teams utilise Coban Kafka clusters. Adding mTLS support mostly boils down to upgrading our SDK.</p><p>Our enhanced SDK provides a default mTLS configuration that works out of the box for most teams, while still allowing customisation, e.g., for teams that have their own Hashicorp Vault Infrastructure for compliance reasons. Similarly, clients can choose among various Vault auth methods such as <a href="https://developer.hashicorp.com/vault/docs/auth/aws">AWS</a> or <a href="https://developer.hashicorp.com/vault/docs/auth/kubernetes">Kubernetes</a> to authenticate to Hashicorp Vault, or even implement their own logic for getting a valid client certificate.</p><p>To mitigate the potential risk of a user maliciously sharing their application’s certificate with other applications or users, we limit the maximum Time-To-Live (TTL) for any given certificate. This also removes the overhead of maintaining a Certificate Revocation List (CRL). Additionally, our SDK stores the certificate and its associated private key in memory only, never on disk, hence reducing the attack surface.</p><p>In our case, Hashicorp Vault is a dependency. To prevent it from reducing the overall availability of our data streaming platform, we have added two features to our SDK — a configurable retry mechanism and automatic renewal of clients’ short-lived certificates when two thirds of their TTL is reached. The upgraded SDK also produces new metrics around this certificate renewal process, enabling better monitoring and alerting.</p><h3>Authorisation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jey_Cqg2upAvpJfo.png" /></figure><p>For authorisation, we set up the Open Policy Agent (OPA) as a standalone deployment in the Kubernetes cluster, and configured Strimzi to integrate the Kafka brokers with that OPA.</p><p>OPA policies — written in the <a href="https://www.openpolicyagent.org/docs/latest/policy-language/">Rego</a> language — describe the authorisation logic. They are created in a GitLab repository along with the authorisation rules, called data sources (step 1). Whenever there is a change, a GitLab CI pipeline automatically creates a bundle of the policies and data sources, and pushes it to an S3 bucket (step 2). From there, it is fetched by the OPA (step 3).</p><p>When a client — identified by its TLS certificate’s Subject — attempts to consume or produce a Kafka record (step 4), the Kafka broker pod first issues an authorisation request to the OPA (step 5) before processing the client’s request. The outcome of the authorisation request is then cached by the Kafka broker pod to improve performance.</p><p>As the core component of the authorisation process, the OPA is deployed with the same high availability as the Kafka cluster itself, i.e. spread across the same number of Availability Zones. Also, we decided to go with one dedicated OPA by Kafka cluster instead of having a unique global OPA shared between multiple clusters. This is to reduce the blast radius of any OPA incidents.</p><p>For monitoring and alerting around authorisation, we submitted an <a href="https://github.com/StyraInc/opa-kafka-plugin/pull/38">Open Source contribution</a> in the opa-kafka-plugin project in order to enable the OPA authoriser to expose some metrics. Our contribution to the open source code allows us to monitor various aspects of the OPA, such as the number of authorised and unauthorised requests, as well as the cache hit-and-miss rates. Also, we set up alerts for suspicious activity such as unauthorised requests.</p><p>Finally, as a platform team, we need to make authorisation a scalable, self-service process. Thus, we rely on the Git repository’s permissions to let Kafka topics’ owners approve the data source changes pertaining to their topics.</p><p>Teams who need their applications to access a Kafka topic would write and submit a JSON data source as simple as this:</p><pre>{<br> &quot;example_topic&quot;: {<br>   &quot;read&quot;: [<br>     &quot;clientA.grab&quot;,<br>     &quot;clientB.grab&quot;<br>   ],<br>   &quot;write&quot;: [<br>     &quot;clientB.grab&quot;<br>   ]<br> }<br>}</pre><h3>What’s next?</h3><p>The performance impact of this security design is significant compared to unauthenticated, unauthorised, plaintext Kafka. We observed a drop in throughput, mostly due to the low performance of encryption and decryption in Java, and are currently benchmarking different encryption ciphers to mitigate this.</p><p>Also, on authorisation, our current PBAC design is pretty static, with a list of applications granted access for each topic. In the future, we plan to move to Attribute-Based Access Control (ABAC), creating dynamic policies based on teams and topics’ metadata. For example, teams could be granted read and write access to all of their own topics by default. Leveraging a versatile component such as the OPA as our authorisation controller enables this evolution.</p><p>Grab is the leading superapp platform in Southeast Asia, providing everyday services that matter to consumers. More than just a ride-hailing and food delivery app, Grab offers a wide range of on-demand services in the region, including mobility, food, package and grocery delivery services, mobile payments, and financial services across 428 cities in eight countries.</p><p>Powered by technology and driven by heart, our mission is to drive Southeast Asia forward by creating economic empowerment for everyone. If this mission speaks to you, <a href="https://grab.careers/">join our team</a> today!</p><p><em>Originally published at </em><a href="https://engineering.grab.com/zero-trust-with-kafka"><em>https://engineering.grab.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91376f7e162d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka Internals: KIP-651 Using PEM certificate for SSL listener]]></title>
            <link>https://dttung2905.medium.com/kafka-internals-kip-651-using-pem-certificate-for-ssl-listener-679b56cc9c59?source=rss-2ddf21046cf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/679b56cc9c59</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[real-time-streaming-data]]></category>
            <category><![CDATA[tls]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Thanh Tung Dao]]></dc:creator>
            <pubDate>Sat, 05 Nov 2022 10:36:13 GMT</pubDate>
            <atom:updated>2022-11-05T10:36:13.645Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*oIzwQxyLwztjmide.png" /><figcaption>source: <a href="https://www.confluent.io/blog/apache-kafka-security-authorization-authentication-encryption/">https://www.confluent.io/blog/apache-kafka-security-authorization-authentication-encryption/</a></figcaption></figure><h3>1.Motivation</h3><ul><li>Previously, when we connect to TLS listener in Kafka, we have to prepare the keystore and truststore in JKS format. JKS stands for Java Keystore which means it used explicitly for Java world. However, the rest of the world have adopted a common format i.e PEM</li><li>Recently, <a href="https://cwiki.apache.org/confluence/display/KAFKA/KIP-651+-+Support+PEM+format+for+SSL+certificates+and+private+key">KIP-651</a> proposes additional support to use PEM format for SSL certificates. However, the documentation from Kafka is not cleared and this blog aims to fill that gap</li></ul><h3>2.How-to</h3><p>Lets jump straight into how to do it. There are two ways to provide the certificates: as string or as file. This blog will demonstrate using kafka console client for simplicity</p><h4>2.1 Provide certifcate as files</h4><p>This will be your client.properties file</p><pre>bootstrap.servers=kafka.server:9092<br>security.protocol=SSL<br>ssl.truststore.type=PEM<br>ssl.truststore.location=truststore.pem</pre><pre>ssl.keystore.type=PEM<br>ssl.keystore.location=keystore.pem<br>ssl.key.password=hello</pre><p>Detail steps:</p><p><strong>Step 1</strong>: You must encrypt your private key in <strong>PKCS8</strong> format and only your private key. The command for it is: ( please remember to use hello as your encrypted password in this example)</p><pre>openssl pkcs8 -topk8 -in privateKey.key -out encryptedPrivateKey.p9</pre><p><strong>Step 2</strong>: Copy the content of your encrypted private key and put into the <strong>keystore.pem</strong> file in this <strong>exact</strong> order:</p><ul><li>your private key</li><li>your signed certificate</li><li>any intermediate CA and root CA</li></ul><p>The output is something like this</p><pre>-----BEGIN ENCRYPTED PRIVATE KEY-----<br>xxxx<br>-----END ENCRYPTED PRIVATE KEY-----<br>-----BEGIN CERTIFICATE-----<br>xxxx<br>-----END CERTIFICATE-----<br>-----BEGIN CERTIFICATE-----<br>xxxx<br>-----END CERTIFICATE-----</pre><p><strong>Step 3</strong>: Run the command</p><pre>./bin/kafka-console-consumer.sh --bootstrap-server your.endpoint:9092 --topic your.topic --producer.config client.properties</pre><h4>Common mistake I made:</h4><ul><li>If you don’t put ssl.keys.password it won’t work too</li></ul><pre>org.apache.kafka.common.KafkaException: Failed to construct kafka producer  at org.apache.kafka.clients.producer.KafkaProducer.&lt;init&gt;(KafkaProducer.java:440)  at org.apache.kafka.clients.producer.KafkaProducer.&lt;init&gt;(KafkaProducer.java:291)  at org.apache.kafka.clients.producer.KafkaProducer.&lt;init&gt;(KafkaProducer.java:318)  at org.apache.kafka.clients.producer.KafkaProducer.&lt;init&gt;(KafkaProducer.java:303)  at kafka.tools.ConsoleProducer$.main(ConsoleProducer.scala:45)  at kafka.tools.ConsoleProducer.main(ConsoleProducer.scala) Caused by: org.apache.kafka.common.errors.InvalidConfigurationException: SSL PEM key store is specified, but key password is not specified.</pre><ul><li>if you don’t encrypt your private key, this error will pop up</li></ul><pre>org.apache.kafka.common.KafkaException: Failed to construct kafka producer  at org.apache.kafka.clients.producer.KafkaProducer.&lt;init&gt;(KafkaProducer.java:440)  at org.apache.kafka.clients.producer.KafkaProducer.&lt;init&gt;(KafkaProducer.java:291)  at org.apache.kafka.clients.producer.KafkaProducer.&lt;init&gt;(KafkaProducer.java:318)  at org.apache.kafka.clients.producer.KafkaProducer.&lt;init&gt;(KafkaProducer.java:303)  at kafka.tools.ConsoleProducer$.main(ConsoleProducer.scala:45)  at kafka.tools.ConsoleProducer.main(ConsoleProducer.scala) Caused by: org.apache.kafka.common.errors.InvalidConfigurationException: Failed to load PEM SSL keystore wong-format.pem Caused by: org.apache.kafka.common.errors.InvalidConfigurationException: Invalid PEM keystore configs Caused by: java.io.IOException: overrun, bytes = xxx</pre><h4>2.2 Providing certificates as strings</h4><p>This will be the content of your <strong>client.properties</strong> file</p><pre>bootstrap.servers=kafka.server:9092<br>security.protocol=SSL<br>ssl.truststore.type=PEM<br>ssl.truststore.certificates=-----BEGIN CERTIFICATE-----\nxxxx\n-----END CERTIFICATE-----</pre><pre>ssl.keystore.type=PEM<br>ssl.keystore.certificate.chain=-----BEGIN CERTIFICATE-----\nxxxx\n-----END CERTIFICATE-----<br>ssl.keystore.key=-----BEGIN ENCRYPTED PRIVATE KEY-----\nxxxx\n-----END ENCRYPTED PRIVATE KEY-----<br>ssl.key.password=hello</pre><p><strong>Step 1</strong>: You must encrypt your private key in <strong>PKCS8</strong> format and only your private key. The command for it is: ( please remember to use hello as your encrypted password in this example)</p><pre>openssl pkcs8 -topk8 -in privateKey.key -out encryptedPrivateKey.p9</pre><p><strong>Step 2</strong>: Copy the content of your encrypted private key and put into the ssl.keystore.key section of the client.properties file. Remember that everything must be on a single line</p><p><strong>Step 3</strong>: Run the command</p><pre>./bin/kafka-console-consumer.sh --bootstrap-server your.endpoint:9092 --topic your.topic --producer.config client.properties</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=679b56cc9c59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Kubernetes Cluster At Scale: Cluster Overprovisioning]]></title>
            <link>https://dttung2905.medium.com/managing-kubernetes-cluster-at-scale-cluster-overprovisioning-b62e5afdc54b?source=rss-2ddf21046cf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b62e5afdc54b</guid>
            <category><![CDATA[cluster-autoscaler]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[site-reliability-engineer]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Thanh Tung Dao]]></dc:creator>
            <pubDate>Sat, 09 Jul 2022 10:29:42 GMT</pubDate>
            <atom:updated>2022-07-09T10:29:42.408Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RrjgKi6oMmkKEvCD.png" /><figcaption><a href="https://kubernetes.io/">source</a></figcaption></figure><h3>Is Cluster Autoscaler alone enough ?</h3><p><a href="https://github.com/kubernetes/autoscaler/tree/master/cluster-autoscaler">Cluster Autoscaler</a> (CA) is part of the Kubernetes ecosystem that allows automatical addition or removal or nodes in a cluster based on resource request from pods. You may have heard of <a href="https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/">Horizonal Pod Autoscaler</a> (HPA) and <a href="https://github.com/kubernetes/autoscaler/tree/master/vertical-pod-autoscaler">Vertical Pod Autoscaler</a> (VPA) but let’s save those topics for another day :P</p><p>In a nutshelf, Cluster Autoscaler is designed to perform two main tasks:</p><ul><li>Add more nodes to the K8s node group if there are pending pods. The default scan interval for pods is 10 seconds which you can modify using --scan-interval flag</li><li>Remove “underutilized” nodes from the cluster. What is the condition to scale down ? Its Sum ( CPU &amp; Memory requests ) of all pods running on a node &lt; threshold. The threshold default value is 50% but could be configured using --scale-down-utilization-threshold flag</li></ul><p>That sounds great right. We can make our K8s cluster elastic while our SRE team can enjoy a good sleep without PagerDuty call. However, Cluster Autoscaler alone does not guarantee high availability of application</p><h3>What’s the problem with Cluster Autoscaler?</h3><p>Actually, it is not the problem with Cluster Autoscaler, it is about how fast we can get a node to join the cluster. It could take as long as 7 mins to get that node and running. Let me repeat, its 7 freaking minutes. During that 7 mins , our new pods will be sitting there in Pending state and as a software engineer, you want that Pending state time as short as possible</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/0*C2qCIOY8IEG95KJY.jpeg" /></figure><p>Actually, with some tweak and a combination of <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/pod-priority-preemption/">Pod Priority and Preemption</a> and <a href="https://github.com/kubernetes-sigs/cluster-proportional-autoscaler">cluster-proportional-autoscaler</a>, we can shorten this time to a matter of seconds</p><h3>Pod Priority and Preemption</h3><p>Just by looking at the names, we can definitely guess that these features help us to assign priorities to pods. We can group applications deployed by order of importance and assign priorities accordingly ( for example: overprovision, low, high, monitoring, system-eritical). When node resources are scarced, pods with lower priority are evicted to give way to higher priority pods to be scheduled</p><p>Interestingly, this means that we can create a lowest priority class just for overprovisioning. Those pods with overprovisioning priority is called pause pod, with a sole purpose of reserving extra resources in our K8s cluster, which will be evicted to give space as long as “real” pods need to run.</p><p>This is how the flow is going to be:</p><ul><li>We have several pause pod running as buffer. All nodes are running at near full capacity</li><li>A new deployment is created with higher priority than pause pod.</li><li>Pause pods will be evicted. Its state changes from RUNNING to PENDING while new deployment pods take the pause pods place in the current set of nodes</li><li>Cluster Autoscaler scan every 60 seconds and found out pause pod is running in PENDING state, and hence new nodes are created to host those pause pods</li></ul><p>The reason of running actual pods for overprovisioning is more than just CPU and memory requests. It could be exhausted IP addresses which happen quite frequently if we run a big enough cluster. I’m sure many people have encountered this issue once when managing K8s cluster</p><pre>Warning  FailedCreatePodSandBox  10m                    kubelet, ip-10-60-200-192.ec2.internal  Failed create pod sandbox: rpc error: code = Unknown desc = failed to set up sandbox container &quot;abcxyz&quot; network for pod &quot;xxxxx-xxxxxserver-deployment-123456abc-xxxx&quot;: networkPlugin cni failed to set up pod &quot;xxxxx-xxxxxserver-deployment-123456abc-xxxx_default&quot; network: add cmd: failed to assign an IP address to container</pre><p>There are <a href="https://aws.amazon.com/blogs/containers/optimize-ip-addresses-usage-by-pods-in-your-amazon-eks-cluster/">articles</a> on AWS to guide users to resolve this issue and I’m sure there are similar articles for other cloud providers too but let’s just use AWS as a representative for now</p><h3>How much buffer to set?</h3><p>Now we know what we can skillfully use Pod Priority to create pause pod acting as our buffer. The next question is deciding appropriate level of buffer. Would a 100-node cluster be given the same amount of buffer as a 10 node cluster? Surely we do not want to hardcode any absolute number of buffer nodes but rather a percentage of the cluster.</p><p>Luckly, there is cluster-proportional-autoscaler (CPA) which helps us to achieve this. CPA, to put it simply is just a deployment that dynamically increases/ decreases the number of replicas based on the total number of cores of the cluster and the number of nodes of the cluster which are set by coresPerReplica and nodesPerReplica respectively.</p><p>The reason we need both values is to account for two types of cluster: core heavy cluster and node heavy cluster. Core heavy means we can have a cluster of few nodes but each node is made up of a very powerful VM instance. Node heavy cluster is the opposite. It refers to cluster of many nodes but smaller instance type</p><pre>kind: ConfigMap<br>apiVersion: v1<br>metadata:<br>  name: nginx-autoscaler<br>  namespace: default<br>data:<br>  linear: |-<br>    {<br>      &quot;coresPerReplica&quot;: 2,<br>      &quot;nodesPerReplica&quot;: 1,<br>      &quot;preventSinglePointFailure&quot;: true<br>    }<br>---<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx-autoscale-example<br>  namespace: default<br>spec:<br>  selector:<br>    matchLabels:<br>      run: nginx-autoscale-example<br>  replicas: 1<br>  template:<br>    metadata:<br>      labels:<br>        run: nginx-autoscale-example<br>    spec:<br>      containers:<br>      - name: nginx-autoscale-example<br>        image: nginx<br>        ports:<br>        - containerPort: 80<br>---<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx-autoscaler<br>  namespace: default<br>  labels:<br>    app: autoscaler<br>spec:<br>  selector:<br>    matchLabels:<br>      app: autoscaler<br>  replicas: 1<br>  template:<br>    metadata:<br>      labels:<br>        app: autoscaler<br>    spec:<br>      containers:<br>        - image: gcr.io/google_containers/cluster-proportional-autoscaler-amd64:{LATEST_RELEASE}<br>          name: autoscaler<br>          command:<br>            - /cluster-proportional-autoscaler<br>            - --namespace=default<br>            - --configmap=nginx-autoscaler<br>            - --target=deployment/nginx-autoscale-example<br>            - --logtostderr=true<br>            - --v=2</pre><h3>Summary</h3><p>Cluster Autoscaler + Pods Priority + Cluster-proportional-autoscaler = Profit</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b62e5afdc54b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debezium, Kafka and Transactional Outbox — The challenges]]></title>
            <link>https://dttung2905.medium.com/debezium-kafka-and-transactional-outbox-the-challenges-bc955c1a2ad8?source=rss-2ddf21046cf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc955c1a2ad8</guid>
            <category><![CDATA[debezium]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[kafka-connect]]></category>
            <dc:creator><![CDATA[Thanh Tung Dao]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 09:28:13 GMT</pubDate>
            <atom:updated>2022-04-24T09:28:13.530Z</atom:updated>
            <content:encoded><![CDATA[<h3>Debezium, Kafka and Transactional Outbox — The challenges</h3><p>What I have learnt from running Debezium Connectors with Kafka cluster at scales</p><h3>Why do we need transactional outbox?</h3><p>In the realm of microservices, often, application will have its own datastore. It can be a MySQL or PostgreSQL database that the application can persist data into. At the same time, the same application will want to send an event/notification to other downstream applications via a message queue. This dual write solution may cause potential inconsistencies. This could happen when either of the writes ( to message queue or to local database ) experiences failure while the other is sent successfully</p><p>Hence, we will have this question.</p><blockquote>How to reliably update the database and send messages/ events?</blockquote><h3>What is Transactional Outbox Pattern then?</h3><p>This pattern consists of an OUTBOX table that service/application will insert message/ event into. After that, we have a message relay (Debezium Connector in this case) that listens to the table changes (via binlog file) and publish the data into message broker ( Kafka cluster )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YLcHfN844wVFcBBpDJ13LQ.png" /><figcaption>Outbox Pattern (<a href="https://debezium.io/blog/2019/02/19/reliable-microservices-data-exchange-with-the-outbox-pattern/">source</a>)</figcaption></figure><p>Subsequently, separate downstream applications will consume from those event in Kafka topics as a form of events</p><h3>What are the benefits of Transational Outbox Pattern?</h3><ul><li>Upstream application only needs to write once to the database</li><li>Messages to downstream applications are guaranteed to be sent if and only if the database transations successfully commits</li><li>The message are sent to Kafka broker in the order they were sent by the application</li></ul><p>Now we have some context about Transactional Outbox Pattern, lets discuss its challenges and how I overcome it when running in production environment</p><h3>The Setting</h3><ul><li>A Kafka Connect cluster will be spun up to run several Debezium Kafka Connectors. Each cluster will consists of minimum 3 worker nodes. In this article, each worker node corresponds to a Kubernetes pods</li><li>Each Debezium Connector consists of a single Connector task. This task will resides in one of the worker pod. There can be multiple debezium connectors running in a single worker pod</li></ul><h3>Challenge 1: Connector Status is RUNNING but Task Status is FAILED</h3><pre>{<br>  &quot;name&quot;: &quot;test&quot;,<br>  &quot;connector&quot;: {<br>    &quot;state&quot;: &quot;RUNNING&quot;,<br>    &quot;worker_id&quot;: &quot;localhost:8083&quot;<br>  },<br>  &quot;tasks&quot;: [<br>    {<br>      &quot;state&quot;: &quot;FAILED&quot;,<br>      &quot;id&quot;: 0,<br>      &quot;trace&quot;: &quot;ERROR MESSAGE&quot;,<br>      &quot;worker_id&quot;: &quot;localhost:8083&quot;<br>    }<br>  ]<br>}</pre><p>Actually, this is a “common” problem for all other types of Kafka Connector, not just Debezium. What we can see from the picture is that</p><ul><li>There is only 1 task running for this Debezium connector</li><li>This task status is FAILED while the connector status is still RUNNING. Technically speaking, the connector is down</li></ul><p><strong>Solution</strong>:</p><ul><li>Usually, in this case, the first thing we try ( and so often it works wonderfully) is to restart the connector task via <a href="https://docs.confluent.io/platform/current/connect/references/restapi.html#post--connectors-(string-name)-tasks-(int-taskid)-restart">Connector API</a></li><li>Set proper alerting rules at the task level, not connector level</li><li>If we want to automate this restart operation even more, we can create a cron-job that restart all failed task after a fixed period of time (15 mins might be a good start). rmoff has outlined this in detailed in this <a href="https://rmoff.net/2019/06/06/automatically-restarting-failed-kafka-connect-tasks/">blog</a></li></ul><h3>Challenge 2: Source Database cutover</h3><p>How does Kafka Connect Debezium tracks its offset? So that in case of failure, it can continue to read from the point where it left off previously? Internally, Kafka Connect tracks the offset in a metadata kafka topic that is indicated in offset.storage.topic config. Please take note that Connector does not store offset in __consumer_offsets topic like the normal consumer group</p><p>Often, Debezium connector connects to source database host via a DNS record. I.In many of the case, there will be updates to the database instance, that sits behind this DNS record (version update, hot fix etc) .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*GtSWkhiVPVxRxmjQ8-S2Kg.png" /><figcaption>Blue Green Deployment (<a href="https://aws.amazon.com/blogs/database/performing-major-version-upgrades-for-amazon-aurora-mysql-with-minimum-downtime/">Source</a>)</figcaption></figure><p>As seen in the picture above, when the Green( Non Production ) Database cluster is switched over, the binlog file name and position is not the same as the old one that we stored in offset.storage.topic kafka topic .If we don’t do anything to our connector, it is guaranteed to fail.</p><p><strong>Solution</strong>:</p><ul><li>During the switch over ( step 4 of the diagram ) we need to “tell” the connector which new binlog position, binlog file and server name it will continue to read from. We should be able to get it from our Database Ops team .</li><li>Pause the connector</li><li>Manually insert this offset position, binlog file name and server name into the offset topic from offset.storage.topic . The detailed step can be found from Debezium official doc <a href="https://debezium.io/documentation/faq/#how_to_change_the_offsets_of_the_source_database">here</a></li><li>Restart the connector</li></ul><h3>Challenge 3: Huge DML operation , CPU throttled and noisy neighbor</h3><p>As Debezium records changes from the binlog file at the row level. Each row affected will be counted as 1 event/ kafka message. Hence, for huge DML operation that affect millions of row ( yes I have worked with DML changes resulting in 50 Millions rows), there will be a sudden influx of messages from our Debezium</p><p>With a sudden huge number of messages are sent into our Kafka topic, some part of our system can become the bottle neck:</p><ul><li>If we don’t provision enough resources ( CPU cores ) to our worker node pod, there will be CPU throttled, leading to very few messages produced into Kafka</li><li>If our Kafka topic does not support that high level of throughput, it can limit how many messages per second can be consumed/produced to kafka</li></ul><p>We will run a risk of (a) failure to produce that much messages to kafka before the binlog retention. This will cause data loss (b) failure to consume that much message from Kafka by downstream application before Kafka topic retention period (c) affecting all of the Debezium Connector running in that same pod because of this noisy neighbor</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*VPmCe_EZwPoLnGeGIKMADg.jpeg" /></figure><p><strong>Solution</strong>: some of these / a combinations of these solutions have proven to work for me</p><ul><li>Clear communication of such events : Prevention is better than cure. If we can prepare for this event, instead of reactively fighting the fire, it would be much better. This is even more crucial when each component is own by different teams ( database by Database Ops team, Debezium and Kafka by Platform team, downstream applications by respective service team etc)</li><li>Increase the retention period binlog file / kafka topic. This will allow Debezium/ Kafka Consumer to be able to produce/ consume all of the event</li><li>Set appropriate number of partition for our Kafka topic. The number of partition per topic determine the level of parallelism for our topic. It can greatly increase the read/write throughput of our Debezium/ downstream application. <strong>Note : </strong>once you increase the partition number of a topic, you won’t be able to decrease it back</li><li>Temprorarily privision for more resource: For Kafka Connect worker node, you can increase the number of CPU core or set a much higher cpu_limit than the current cpu_request . For application downstream, if possible, we can increase the number of host to match the number of partition of the topic ( number of host &gt; number of partition does not work as it leads to idle consumer)</li><li>Set proper monitoring: we can set monitoring for the following (a) lag between debezium and host database (b) consumer lag (c) Abnormal changes in the incoming message ( week over week difference)</li></ul><p><strong>Note: </strong>There are some discussion from Debezium community about the performance of Debezium. I will leave it <a href="https://issues.redhat.com/browse/DBZ-3477">here</a> for you to read more on</p><h3>Challenge 4: Reading from non-existence binlog file</h3><p>As the name suggests, the connector is trying to read from the binlog position which has been flushed by the database and no longer exists. Unfortunately, from my experience, there is not much we can do but accept the fact that we might have some missing data</p><p><strong>Solution</strong>:</p><ul><li>Increase the retention period of the source data base.This is more like a preventive solution</li></ul><h3>Challenge 5: At-least-once delivery semantics</h3><p>As we are in the realm of distributed system, failure is always expected. Things may be running fine most of the time, but what counts is in the unwanted event of failure. If Debezium <a href="https://debezium.io/documentation/faq/#why_must_consuming_applications_expect_duplicate_events">crashes</a> after it has sent message A to kafka but before it can commit the offset, things get complicated. After the restart, Debezium connector will look back at the offset, and fire event A again leading to duplicate data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*vANLjC6dn9bsiuXB0FE1tQ.jpeg" /></figure><p><strong>Solution</strong>:</p><p>When building downstream consumer application, we should have a deduplication mechanism in place. Once possible way is to used kafka message_id to as deduplication key</p><h3>Summary</h3><p>Transactional Outbox Pattern with Kafka and Debezium is a very useful and commonly used pattern. However, comes with it is another level of operational complexity that we have to account for</p><p>Hence, before we consider this approach, we need to asnwer a few questions:</p><ul><li>What do we stand to gain from this new implementation? What is the trade-off?</li><li>Do we have an existing Kafka cluster and Kafka Connector cluster in use , or we are setting them up and managing them from scratch ?</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc955c1a2ad8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka Internals: client dns lookup]]></title>
            <link>https://dttung2905.medium.com/kafka-internals-client-dns-lookup-c993955810e3?source=rss-2ddf21046cf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c993955810e3</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[network]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[infrastructure]]></category>
            <dc:creator><![CDATA[Thanh Tung Dao]]></dc:creator>
            <pubDate>Sat, 14 Aug 2021 10:59:16 GMT</pubDate>
            <atom:updated>2021-08-14T11:41:12.580Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*nqt-h45RCQE1USDN.png" /></figure><p>Recently, I’m really lucky to have a chance to work with Kafka and have a deeper understanding on how it works. Hence, this post will be about client.dns.lookup , one of the many nuances that you have to deal with when working with, maintaining kafka cluster.</p><h3>What is it about?</h3><p>It is one of the properties that is set for Kafka clients client.dns.lookup . In older version of kafka (before Kafka 2.6), the default value would be default . Internally, it resolve a symbolic hostname by using:</p><pre><strong>new</strong> InetSocketAddress(String hostname, <strong>int</strong> port)</pre><p>which it onlys choose the first IP address even if the DNS has many A records for the hostname. This is because of the following logic:</p><pre>InetAddress.getAllByName(hostname)[0]</pre><h3>Why does it matter?</h3><p>This is problematic because if you have many IP addresses, and in an unfortunate event that the first IP you pick up is down, your whole application (consumer, producer) will throw errors too.</p><p>You will be scratching your head because on the surface , your kafka cluster is working fine, all metrics in your monitoring system is good.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/0*YeRHF2yCtmM7V9pb.jpg" /><figcaption>what’s happening</figcaption></figure><h3><strong>How do we solve it?</strong></h3><p>Luckily, the Kafka community has long realised the flawed in the logic and has introduced changes in <a href="https://cwiki.apache.org/confluence/display/KAFKA/KIP-302+-+Enable+Kafka+clients+to+use+all+DNS+resolved+IP+addresses">KIP-302</a> to introduce another logic. It is to enable Kafka clients to use all DNS resolved IP addresses. By doing so, if one IP address is not reachable, the Kafka client will move on to the next IP in the list, until there is none. Only then it will throw error. It will reduce the failure rate of your kafka consumer/ producer if you have something on going on your Kafka cluster side ( broker rotation for example). This is more important when your run everything in cloud and containerized environments where a single host name may resolve to multiple IP.</p><p>It was taken up further that default value of client.dns.lookup changes from &quot;default&quot; to &quot;use_all_dns_ips&quot; (I like the pun here) in <a href="https://cwiki.apache.org/confluence/display/KAFKA/KIP-602%3A+Change+default+value+for+client.dns.lookup">KIP-602</a> and to be released in Kafka 2.6 among other amazing changes.</p><p>If your Kafka is still recent enough to have &quot;use_all_dns_ips&quot; option but the version is still below 2.6, well, you need to override this properties in your application code.</p><p>Lets take Kafka Connect running on docker for example. I use Kafka Connect to demonstrate because it has bother consumer and producer ( source and sink connector). To make the changes, you just need to add it as the environment variable.</p><pre><strong>CONNECT_CLIENT_DNS_LOOKUP=</strong>&quot;use_all_dns_ips&quot;</pre><p>The full example is here:</p><pre>docker run -d <strong>\</strong><br>  --name<strong>=</strong>kafka-connect <strong>\</strong><br>  --net<strong>=</strong>host <strong>\</strong><br>  -e CONNECT_BOOTSTRAP_SERVERS<strong>=</strong>localhost:29092 <strong>\</strong><br>  -e CONNECT_REST_PORT<strong>=</strong>28082 <strong>\</strong><br>  -e CONNECT_GROUP_ID<strong>=</strong>&quot;quickstart&quot; <strong>\</strong><br>  -e CONNECT_CONFIG_STORAGE_TOPIC<strong>=</strong>&quot;quickstart-config&quot; <strong>\</strong><br>  -e CONNECT_OFFSET_STORAGE_TOPIC<strong>=</strong>&quot;quickstart-offsets&quot; <strong>\</strong><br>  -e CONNECT_STATUS_STORAGE_TOPIC<strong>=</strong>&quot;quickstart-status&quot; <strong>\</strong><br>  -e CONNECT_KEY_CONVERTER<strong>=</strong>&quot;org.apache.kafka.connect.json.JsonConverter&quot; <strong>\</strong><br>  -e CONNECT_VALUE_CONVERTER<strong>=</strong>&quot;org.apache.kafka.connect.json.JsonConverter&quot; <strong>\</strong><br>  -e CONNECT_INTERNAL_KEY_CONVERTER<strong>=</strong>&quot;org.apache.kafka.connect.json.JsonConverter&quot; <strong>\</strong><br>  -e CONNECT_INTERNAL_VALUE_CONVERTER<strong>=</strong>&quot;org.apache.kafka.connect.json.JsonConverter&quot; <strong>\</strong><br>  -e CONNECT_REST_ADVERTISED_HOST_NAME<strong>=</strong>&quot;localhost&quot; <strong>\</strong><br>  -e CONNECT_PLUGIN_PATH<strong>=</strong>/usr/share/java <strong>\</strong><br>  confluentinc/cp-kafka-connect:6.2.0<br>  -e CONNECT_CLIENT_DNS_LOOKUP<strong>=</strong>&quot;use_all_dns_ips&quot;</pre><p>You might wonder why its client.dns.lookup in the official doc but we are using CONNECT_CLIENT_DNS_LOOKUP . If you look closely in the docs <a href="https://docs.confluent.io/platform/current/installation/docker/config-reference.html">here</a>, you will find out that:</p><blockquote>For the Kafka Connect (cp-kafka-connect) image, convert the property variables as below and use them as environment variables:</blockquote><blockquote>Prefix with CONNECT_.</blockquote><blockquote>Convert to upper-case.</blockquote><blockquote>Replace a period (.) with a single underscore (_).</blockquote><blockquote>Replace a dash (-) with double underscores (__).</blockquote><blockquote>Replace an underscore (_) with triple underscores (___).</blockquote><p>It took me a while to string all the pieces together so I hope this will help you in some way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/0*TZWL_-QUYSXWomBw" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c993955810e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>