<?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 Kam Singh on Medium]]></title>
        <description><![CDATA[Stories by Kam Singh on Medium]]></description>
        <link>https://medium.com/@chkamalsingh?source=rss-fca4d38493bf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*FdLxzUifDgVQ1Ccq.jpg</url>
            <title>Stories by Kam Singh on Medium</title>
            <link>https://medium.com/@chkamalsingh?source=rss-fca4d38493bf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 20:09:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chkamalsingh/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[Microservices Core Principles]]></title>
            <link>https://medium.com/@chkamalsingh/microservices-core-principles-80e427261bc8?source=rss-fca4d38493bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/80e427261bc8</guid>
            <dc:creator><![CDATA[Kam Singh]]></dc:creator>
            <pubDate>Mon, 13 Sep 2021 15:43:28 GMT</pubDate>
            <atom:updated>2024-10-14T09:21:43.734Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Single Responsibility / Function</strong></p><p>Each Microservice delivers a single complete business capability. A complete business capability is a process that can be finished consecutively without interruptions or excursions to other services. This means that a business capability should not depend on other services to complete its work. Well-designed microservices are aligned to a single business capability, so they perform only one function. A unit with more than one responsibility indicates tight coupling. Therefore develop the microservices based on distinct features with zero overlaps with other functions. combining different areas in one service can rely on code sharing sometimes which makes it very difficult to maintain individual parts of code independently.</p><p>Each microservice must be responsible for a specific feature or functionality or aggregation of cohesive functionality. The thump rule to apply this principle is: “Gather those things which change for the same reason, separate those things which change for the different reason”. At no point should two units share one responsibility or one unit have more than one responsibility. High cohesiveness should be achieved in the design. Where Service has unrelated behaviors and responsibilities change in the requirements are likely to impact unrelated functionality. This will take away the agility regarding changes.</p><p><strong>Lightweight / Small</strong></p><p>Microservices are designed to be small. But defining “small” is subjective. There is no consensus or litmus test for this, as the right answer depends on the business and organizational context. Viewing the size of services as the primary structuring mechanism can lead to too many services which are hard to maintain until and unless automation is in place. Instead, the important point should be to create loosely coupled services so we have autonomy of development, deployment, and scale, for each service. More important than the size of the microservice is the internal cohesion it must have and its independence from other services.</p><p>Services in nature are ought to be small in size, messaging-enabled, bounded by contexts, autonomously developed, independently deployable, decentralized, and built and released with automated processes. On the other hand, it is considered bad practice to make the service too small, as then the runtime overhead and the operational complexity can overwhelm the benefits of the approach.</p><p>Some industry experts talk about few techniques to define the size of microservice, they are :</p><p>It should be small enough to be owned by a small agile development team, re-writable within one or two agile sprints ( typically two to four weeks) or the complexity does not require to refactoring or require further division into another microservice. In some cases, it also depends on how the services have been decomposed. Capability-based service could be heavier than a subdomain-driven service, e.g. Order management (capability-based service) will need to handle order-related functions such as processing, charging customers, and making inventory updates wherein the subdomain-based approach these can all be three distinct services dividing overall responsibilities between themselves.</p><p><strong>Loose Coupling</strong></p><p>The changes in one microsystem should have zero or minimum impact on other services in the ecosystem. The main objective is to reduce the interaction between services so that they are highly cohesive and loosely coupled. If we separate the functionality across wrong boundaries will lead to tight coupling and increased complexity between services.</p><p>This principle also suggests having loosely coupled communication methods between the microservices. Microservices are self-contained, independently deployable, and autonomous services that take full responsibility of a business capability and its execution. Fewer communications between the services should also be preferred.</p><p><strong>Stateless</strong></p><p>A stateless application handles every request with the information contained only within it. Microservices must be stateless and it must service the request without remembering the previous communications from the external system.</p><p><strong>Single database per service</strong></p><p>Each microservice has its own database. You should not set up multiple services to access or share the same database, since it defeats the purpose of the autonomous microservice operation. Data pertaining to a specific microservice is private to that service. Use APIs to let other services access a microservice’s owned data. Aim for one or two database tables per service.</p><p><strong>Separate Code base</strong></p><p>Continuing the Loosely coupled principle each microservice has its own codebase/repo to allow them to independently deploy and upgrade to achieve business agility.</p><p><strong>Scalable</strong></p><p>Microservices must be scale-able both horizontally and vertically. Being horizontally scale-able, we can have multiple instances of the microservice to increase the performance of the system. The design of the microservices must support horizontal scaling (scale-out). Self contained (Each service, aligned to a specific business capability, owns its data and logic) , loosely coupled, stateless and cohesive services supports scalability</p><p><strong>Polyglot</strong></p><p>As microservices are autonomous and abstract everything behind service APIs, it is possible to have different architectures for different microservices.</p><p>Services as the first-class citizen</p><p>In the microservices architecture, services are first-class citizens. Microservices expose service endpoints as APIs and abstract all their realization details. The internal implementation logic, architecture, and technologies (including programming language, database, quality of services mechanisms, and so on) are completely hidden behind the service API.</p><p><strong>Separation of Concern</strong></p><p>Components addressing common and cross-cutting concerns (e.g. Logging, Error handling, security) should be separated into distinct sections such that each section addresses a separate concern. The value of separation of concerns is to simplify the development and maintenance of components to enjoy agility</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80e427261bc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microservices Design patterns]]></title>
            <link>https://medium.com/@chkamalsingh/microservices-design-patterns-49c3bcf71053?source=rss-fca4d38493bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/49c3bcf71053</guid>
            <dc:creator><![CDATA[Kam Singh]]></dc:creator>
            <pubDate>Mon, 13 Sep 2021 15:39:49 GMT</pubDate>
            <atom:updated>2022-03-10T13:47:08.249Z</atom:updated>
            <content:encoded><![CDATA[<p>The sensible use of design patterns will ensure delivering the following qualities of the Microservices Architecture</p><ul><li>Independent</li><li>autonomous</li><li>Scalability</li><li>Continuous delivery through DevOps</li><li>Speed to delivery</li><li>Agility</li><li>Failure isolation</li></ul><p>Deployment strategy is out of scope for this paper</p><p><strong>Event Sourcing:</strong></p><p>The Event Sourcing pattern defines an approach to handling operations on data that’s driven by a sequence of events, each of which is persisted in an append-only store as opposed to the typical approach where only the last state of data is available (i.e. overriding previous states). Each event represents a set of changes to the data (such as RemovedItemFromCart). Because data is stored as a series of events rather than via direct updates to data stores, various services can replay events from the event store to compute the appropriate state of their respective data stores. CQRS patterns is needed to create and datastore fed from the Event store to allow read the data</p><p><strong>CQRS:</strong></p><p>Once we implement database-per-service, there is a requirement to query, which requires joint data from multiple services. CQRS suggests splitting the application into two parts — the command side and the query side.</p><p><strong>When to use:</strong></p><p>Use CQRS if any one of the below is true</p><ul><li>Event Sourcing</li><li>Read pattern (Load) is different from Write</li><li>Read schema needs to be different from Write</li><li>Read DB technology needs to be different from write (SQL vs. NoSQL)</li></ul><p><strong>Back-end for Front-end (BFF) /Experience APIs</strong></p><p>It is a variation of the API Gateway pattern. Rather than a single point of entry for the clients, it provides multiple gateways based upon the client. The purpose is to provide tailored API responses according to the needs of the client, removing a lot of bloats caused by making generic APIs for all the clients. It is also known with different names such as Channel Service or Experience services.</p><p><strong>When to use:</strong></p><p>Backends for Frontends pattern could be used in scenarios where each UI gets a separate backend customized for the specific UI. It also provides other advantages, like acting as a Facade for downstream Microservices, thus reducing the chatty communication between the UI and downstream Microservice.</p><p><strong>Service Decomposition</strong></p><p>Decompose by Business Capability — Decomposition by Business Capability guides the system design according to the way the business is structured</p><ul><li>Examples-Order Management is responsible for orders, Customer Management is responsible for customers</li></ul><p>Decompose by Subdomain (with Bounded Context i.e. Domain Driven Design) — Decomposition by Domain guides the system design according to the analysis of the processes and information flows. Its a loosely coupled independently deployable element of software architecture owned by a single team</p><ul><li>Examples — Product catalog service, Inventory management services, Order management services, Delivery management services</li></ul><p>There could be several types of domains- e.g. core subdomains, supporting subdomains, and Generic subdomains.</p><p>One of the most basic concepts of DDD is its 4-layer architecture.</p><ul><li>Presentation / Experience Layer</li><li>Domain Layer</li><li>Application Layer / System APIs</li><li>Infrastructure Layer</li></ul><p>In API business, an Business Services (Coarse-grained) layer on top of the above can also become a useful choice</p><p><strong>When to use:</strong></p><p>When converting a Monolith application into Microservice or Creating a Microservice environment for the first time.</p><p>‘Decomposition by Subdomain’ instead of ‘Decomposition by Business Capability’ sometimes stands better as ‘Decomposition by Business Capability’ will carry forward the business inefficiencies, if any, into the application design if they are not determined before application design. whereas ‘Decomposition by Subdomain’ determine if there are any business inefficiencies in the domain. also at capability level. Whilst decomposing an application using business capabilities might seem easy but sometimes we face a situation where we some classes which would be common across multiple services and therefore are not easy to decompose.</p><p>Decompose by verb or use case and define services that are responsible for a particular action. e.g. a shipping service that is responsible for shipping complete orders</p><p>Decompose by nouns or resources by defining a service that is all responsible for all operations on entities/resources of a given type. e.g. an Account Service that is responsible for managing user accounts</p><p><strong>Observability</strong></p><ul><li>Log Aggregation — A centralized logging service that aggregates logs from each service instance, for example, AWS CloudWatch.</li><li>Performance Metrics — A metrics service is required to gather statistics about individual operations. It should aggregate the metrics of an application service, which provides reporting and alerting. There are two models for aggregating metrics:</li><li>Push — the service pushes metrics to the metrics service e.g. NewRelic, AppDynamics</li><li>Pull — the metrics services pulls metrics from the service e.g. Prometheus</li><li>Distributed Tracing — When a request spans multiple services, it is worth having a trace ID, we trace a request end-to-end. The following approach can be used to introduce a trace ID.</li><li>Assigns each external request a unique external request-id.</li><li>Passes the external request id to all services.</li><li>Includes the external request-id in all log messages.</li><li>Health Check — Each service needs to have an endpoint that can be used to check the health of the application, such as /health. This API should o check the status of the host, the connection to other services/infrastructure, and any specific logic.</li></ul><p><strong>When to use:</strong></p><p>When there is a need to define an Observability strategy for the Microservices architecture.</p><p><strong>Circuit Breaker</strong></p><p>When the number of consecutive failures crosses a threshold, the circuit breaker trips, and for the duration of a timeout period, all attempts to invoke the remote service will fail immediately (This is known as Open state) . After the timeout expires the circuit breaker allows a limited number of test requests to pass through (This is known as the half-open state). If those requests succeed, the circuit breaker resumes normal operation (This is known as a closed state).</p><p><strong>Saga</strong></p><p>To ensure data consistency across services, when each service has its own database and a business transaction spans multiple services SAGA pattern is required. It can be implemented in two ways:</p><p>Choreography — There is no central coordination, each service produces and listens to another service’s events and decides if an action should be taken or not. Use choreography when coordination across domains of control/visibility is required. Messaging /Queues can be used by services to communicate with each other through events.</p><p>Orchestration — An orchestrator (object) / Transaction Manager takes responsibility for a saga’s decision-making and sequencing business logic. use when you have control over all the actors in a process. when they’re all in one domain of control and you can control the flow of activities.</p><p><strong>Anti Corruption Layer</strong></p><p>The goal of the anti-corruption layer is to avoid corrupting the model of the downstream system when it needs to integrate with an upstream system that has a different model. The idea is to create a layer whose responsibility is to translate from one model to another, providing clients with an interface in terms of their own domain model. That Layer can be implemented as a set of services (i.e. Integration services). Internally, one way of implementing the anticorruption layer is by combining a set of façades, adapters, and translators.</p><p>Side car pattern / Service mesh</p><p>Service mesh through Sidecar proxy achieves the following by leaving developers to focus on the business logic of the service only</p><ul><li>Circuit Breaker</li><li>Load balancer</li><li>Service Discovery</li><li>health Checks</li><li>Security Policies</li><li>Authentication</li><li>Logging</li><li>network communication</li></ul><p><strong>When to use:</strong></p><p>When the number and diversity of Microservices is too high to build and maintain more efficiently and consistently. Generally, these decisions are taken at the beginning of the Journey to use Microservices. A genuine case for it to become a Principle.</p><p><strong>Aggregator / Composition Pattern</strong></p><p>The Aggregator pattern helps to address the situation when a business functionality is broken into several smaller logical pieces of code, it becomes necessary to think about how to collaborate the data returned by each service. This can be done in two ways.</p><ol><li>A composite microservice will make calls to all the required microservices, consolidate the data, and transform the data before sending it back. The composition can be message-driven as well (in addition to Sync)</li><li>An API Gateway can also partition the request to multiple microservices and aggregate the data before sending it to the consumer.</li></ol><p>It is recommended if any business logic is to be applied, then choose a composite microservice. Otherwise, the API Gateway is the established solution.</p><p><strong>One Database per service</strong></p><p>Services must be loosely coupled. They can be developed, deployed, and scaled independently. one database per microservice must be designed so that there is no strong coupling between services in the database layer; it must be private to that service only. It should be accessed by the microservice API only. It cannot be accessed by other services directly. For example, for relational databases, we can use private-tables-per-service, schema-per-service, or database-server-per-service. It may be inevitable that some duplicate data is stored across the services as a result of it.</p><p><strong>When to use:</strong></p><p>Generally, these decisions are taken at the beginning of the Journey to use Microservices, as a principle is supposed to underpin the overall Microservices strategy</p><p><strong>Strangler Pattern</strong></p><p>Strangler pattern means incrementally migrating a Monolithic application to Microservice Architecture by gradually replacing specific functionality with new Microservices. Also, new functionalities are only added in Microservices, bypassing the legacy Monolithic application. A Facade (API Gateway) is then configured to route the requests between the legacy Monolith and Microservices. Once the functionality is migrated from the Monolith to Microservices, the Facade then intercepts the client request and route to the new Microservices. Once all the legacy monolith’s functionalities are migrated, the legacy Monolithic application is “strangled,” i.e., decommissioned.</p><p><strong>Transaction Management</strong></p><p>Two (2) Phase Commit patterns is used to handle a transaction that is distributed to multiple services that are called in a sequence to complete the entire transaction in a synchronous manner (see Saga for asynchronous which should be <strong>preferred</strong>). The approach guarantees that the transaction is atomic. The transaction will end with either all microservices being successful or all microservices have nothing changed so that consistency is maintained across Microservices. In the preparation phase, all microservices involved prepare for the commit and notify the coordinator that they are ready to complete the transaction. Then in the commit phase, either a commit or a rollback command is issued by the transaction coordinator to all microservices. The Drawback is that two-phase commits are quite slow compared to the time for operation of a single microservice. They are highly dependent on the transaction coordinator, which can really slow down the system during high loads. The other main drawback is the locking of database rows. The lock could become a performance bottleneck and it is possible to have a Deadlock, where two transactions mutually lock each other.</p><p><strong>Orchestration / Coordinator / Process APIs</strong></p><p>The first rule is to minimize the inter-service calls between the Microservices. The second rule is to leave the Orchestration responsibilities to the client /caller system. However there are times when we need orchestration on the server-side to support the unique business process or Experience then we should prefer async over sync orchestration, if possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49c3bcf71053" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka White Paper]]></title>
            <link>https://medium.com/@chkamalsingh/kafka-white-paper-594d6ab2fb6b?source=rss-fca4d38493bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/594d6ab2fb6b</guid>
            <dc:creator><![CDATA[Kam Singh]]></dc:creator>
            <pubDate>Tue, 24 Aug 2021 10:09:25 GMT</pubDate>
            <atom:updated>2025-01-16T10:46:25.422Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kafka Introduction</h3><p>Kafka was developed by LinkedIn in 2010, and it has been a top-level Apache project since 2012. It is a highly scalable, distributed, durable, and fault-tolerant publish-subscribe event streaming and messaging system and is written in Scala and Java. Kafka is maintained by <strong>Apache Software Foundation</strong>.</p><p>Following Diagram gives and overview of Kafka and its various types of clients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*LVRmg7734S2eOeBTDBeaLA.png" /></figure><p>Generally, there are two types of messaging patterns available, i.e. Queuing (point to point) and publish-subscribe (pub-sub) messaging system.</p><ol><li>Queuing (Point-to-Point)</li><li>Publish-Subscribe (Pub/Sub)</li></ol><p>Kafka enables both the above models through “<strong>Consumer group</strong>” concept making it scalable in processing and a multi-subscriber.</p><p>As with a queue, the consumer group allows you to divide up the processing over the members of the consumer group. As with the publish-subscribe, it allows you to broadcast messages to multiple consumer groups.</p><h3>Key Concepts / Components of Kafka</h3><p>Kafka is a multi-producer, multi-consumer structure, and it looks something like below diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*MUquvKqRvD1r0jEsVigTfQ.png" /></figure><p>The Kafka architecture revolves around following core Components or Concepts:</p><ul><li>Broker,</li><li>Messages/Records,</li><li>Topic,</li><li>Producers,</li><li>Consumers,</li><li>Streams,</li><li>Connector</li></ul><h3>Broker</h3><p>One or more Kafka servers known as brokers as a part of Distributed messaging systems forms a cluster. Therefore, Broker is an instance or a single server of a Kafka cluster.</p><p>Within a cluster of brokers, a broker will be automatically elected as <em>the controller. </em>The controller is responsible for admin operations, such as partition assignment to broker, monitoring broker failures, etc.</p><h3>Controller election</h3><ol><li>The first server that is registered in the cluster creates a controller node in zookeeper- explained below in the document.</li><li>Other servers that are also being registered to the cluster try to create a controller node in zookeeper but they get the notification “controller exists”.</li><li>Other servers (brokers) then create a zookeeper watch to monitor the controller node.</li><li>If the controller broker goes down, other brokers are notified. Then each one tries to become a controller but only one wins the race.</li></ol><p>The Kafka cluster durably persists all published records/messages on the topic or topics — whether they have been consumed or not — using a configurable retention period or until a storage size is exceeded. These records then cannot be deleted or modify once they are sent to Kafka (this is known as “distributed commit log”).</p><p>Following diagram shows and Kafka cluster with three nodes i.e. Brokers. The diagram also captures the Zookeeper instances running on these servers which are described later in this paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*MXpAovqFssDXyMvHA7snqA.png" /></figure><h3>Messages / Records</h3><p>The smallest entity in Kafka’s ecosystem is called a message or record. A “message” is a key/value pair of data along with metadata such as a timestamp, headers and message key. Headers are pairs of key-value and we can have many of those in part of one message and it is common to set them in case we are trying to add metadata to the messages. Messages are stored inside topics within a log structured format. Log is a persistent ordered data structure which only supports appends. Messages can be in any format, but the most common are string, JSON, and Avro.</p><p>Message key is to ensure that messages are delivered to same partition of that key so ordering is guaranteed. This is achieved through a hash function, ensuring deterministic mapping of message keys to partitions. key can be whatever we want it could be a string, it could be a number whatever we wan If no key is provided then Kafka distributes messages to all partition of that topic in around robin fashion.</p><p>The record inside topic gets written sequentially with a sequential id (known as Offset) assigned for each message starting from 0. You cannot modify nor delete records from the topic. It is read from left to right and guarantees item ordering. Uniqueness of message is determined from a tuple of Partition, Topic and Offset.</p><p>Messages are stored as serialized bytes. By default, Kafka retains messages for seven days, but the retention setting is configured per topic. Following formats are used for serialization:</p><ul><li>String (Including JSON if your data is adjacent)</li><li>Integer, and Float for numbers</li><li>Avro, and Protobuf for advanced kind of data</li></ul><h3>Topics</h3><p>The topic is the structure that holds the messages, or the records published to the Kafka broker. Topics in Kafka are always multi-subscriber; that is, a topic can have zero, one, or many consumers that subscribe to the data written to it. Consumers can subscribe to a topic to get notified when new messages are added.</p><p>A topic can be divided into partitions, the place exactly where data is published. These partitions are distributed across the brokers in the cluster. Each partition is an ordered, immutable sequence of records that is continually appended to — a structured commit log. The records in the partitions are each assigned a sequential id number called the offset that uniquely identifies each record within the partition. A general formula to pick up the number of partitions is based on throughput needs. If partition keys are not used then Kafka assigns the keys in a default manner which makes the ordering of messaging unguaranteed.</p><p>Each partition has one server which acts as the <strong>“partition leader”</strong> and zero or more servers which act as <strong>“followers”</strong>. The leader handles all read and write requests for that partition while the followers passively replicate the leader. (update: from Kafka 2.4.0, consumers are allowed to read from replicas). Kafka guarantees that every partition replica resides on a different broker (whether if it’s the leader or a follower), so the maximum replication factor is the number of brokers in the cluster.</p><p>Every partition follower is reading messages from the partition leader (acts like a kind of consumer) and does not serve any consumers of that partition (only the partition leader serves read/writes).</p><p>If the leader fails, the Kafka controller will detect the failure and elect a new leader from the pool of followers. The Leader assignment process is mentioned further below.</p><p>Each server acts as a leader for some of its partitions and a follower for others so load is well balanced within the cluster. Partitions allow Kafka to parallelize a topic by splitting the data of a topic across multiple brokers, thus adding an essence of parallelism to the ecosystem. i.e. each partition can be placed on a separate machine to allow for multiple consumers to read from a topic in parallel. This is how Kafka delivers high throughput. On the other hand more partition sometime leads to low latency as in Kafka the message can be available to consumers until it is committed means until it is replicated.</p><p>In the following diagram a topic is partitioned on the 3 brokers. The Leader is depicted in Green whilst a Follower is in Grey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*YPkJ1qG_4bHKBRYvS8xTRw.png" /></figure><h3>Leader assignment</h3><p>The assignment of a leader for a particular partition happens during a process called <em>partition leader election</em>. This process happens when the topic/partition is created or when the partition leader (i.e. the broker) is unavailable for any reason.</p><ol><li>A broker X goes down. All partitions whose leader is broker X needs a reassignment.</li><li>Controller nodes select leaders and followers for those partitions.</li><li>Controller nodes send requests to each broker containing which either will be a new partition and followers.</li></ol><h3>Producers</h3><p>Producers through Producer APIs can connect to Kafka Brokers and publish a stream of records or messages to one or more Kafka topics irrespective of the desired partition. A producer can also write to a selected partition with the help of the message key and partition that will generate a hash of key and map it to the selected partition.</p><h3>Consumers</h3><p>Consumers are the subscribers of Kafka topics. Through Consumer APIs an application can connect to Kafka Brokers and consume a stream of records or messages from one or more Kafka topics. The data is extracted from a Kafka topic using a Consumer Instance which is encapsulated inside a Consumer Group. It is basically a collection of one or more consumers working collectively in parallel to consume messages from topic partitions. Consumer group is a multi-threaded or multi-machine consumption from Kafka topics.</p><p>Each consumer has a consumer group ID. Consumers registered with the same group-id would be part of one group. Kafka stores the current offset per Consumer Group / Topic / Partition, as it would for a single Consumer. Therefore, Consumers would be able to consume only from the partitions of the topic which are assigned to it by Kafka. No two consumers of the same group-id (i.e. same consumer groups) would be assigned to the same partition. <em>That means </em>each partition is tied to only one consumer process per consumer group, that way it avoids reading the same record twice- <em>Guaranteed each message is only processed once</em>.</p><p>Consumers send an acknowledgment to Kafka upon ingesting the message. Therefore, the responsibility of what has been consumed is the responsibility of the consumer and this is also one of the main reasons why Kafka has such great horizontal scalability.</p><p>By storing the offset of the last consumed record for each partition, either in Zookeeper or in Kafka itself to keep track of consumed messages, a consumer can stop and restart without losing its place.</p><p>If you have <strong>consumers &gt; partitions then some consumers will be idle</strong> because they have no partitions to read from. If you have <strong>partitions &gt; consumers then consumers will receive messages from multiple partitions</strong>. If you have <strong>consumers = partitions, each consumer reads messages in order from exactly one partition (i.e. </strong>the load is balanced across consumers as equally as possible). In the following diagram two consumers in a Consumer group are connected to three partition meaning one of the consumers is getting messages from two partition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*gzENTtxcqol5ZJYn0NxBWQ.png" /></figure><p>In another example below, Server 1 holds partitions 0 and 3 and server 2 holds partitions 1 and 2. We have two consumer groups, A and B. A is made up of two consumers and B is made up of four consumers. Consumer Group A has two consumers, so each consumer reads from two partitions. Consumer Group B, on the other hand, has the same number of consumers as partitions so each consumer reads from exactly one partition. In the example above, when multiple consumers are subscribing to a Topic under a common Consumer Group ID, in this case, Kafka switches from pub/sub mode to a queue messaging approach. However, when Kafka allows only one consumer per topic partition, there can multiple consumer groups read from the same partition, in this case Kafka is acting as a pub/sub system- <em>A Fan-out feature</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*BPsDWGU6w67hpwp7NL9thA.png" /></figure><p>Unlike message queues where messages are removed from the queue when they are consumed, consuming a message in Kafka doesn’t remove it from the partition. Instead each consumer maintains an offset of the messages it has already consumed. In case of failure, the subscriber can then restart processing from where it left off.</p><h3>Streams</h3><p>Streams consume an input stream from one or more topics and produce an output stream to one or more output topics, effectively transforming the input streams to output streams.</p><p>A use case of this could be where a stream processor through Streaming APIs read data from a topic, running some form of analysis or data transformation, and finally writing the data back to another topic or shipping it to an external source.</p><p>Although Kafka enables this activity with regular Producers, with Streams we can achieve real-time stream processing rather than batch processing. Stream processors are independent of Kafka Producers, Consumers, and Connectors.</p><p>Kafka offers a streaming SQL engine called KSQL for working with Kafka Streams in a SQL-like manner without having to write code like Java. KSQL allows you to transform data within Kafka streams such as preparing the data for processing, running analytics and monitoring, and detecting anomalies in real-time.</p><h3>Connector</h3><p>Kafka Connect is a framework for importing data into Kafka from external data sources or exporting data to external sources like databases and applications. Connectors are the reusable producers or consumers that allow you to move large amounts of data in and out of Kafka to many common external data sources and provides a framework for creating your own custom connectors. For example, a connector to a relational database might capture every change to a table. Following Diagram highlights some of the connectors (source and sink) used to move data from one end to another. Connector workers with required plugins are installed on a separate cluster to Kafka Cluster generally to avoid interference and performance challenges. Some commercial offering of Kafka ships with the ready-to-use connectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*mEvBXAMI5Q_cYshWM1Ob0g.png" /></figure><h3>Connectivity and Networking</h3><p>Kafka uses binary TCP protocol in its native Kafka Java Producer/Consumer API communications for producing or consuming messages that are in serialized bytes format. The native Kafka protocol client is implemented in Java which achieves better network utilization. Serialization/deserialization is required in Kafka as the hard disk or network infrastructure is a hardware component and we cannot send java objects because it understands just bytes and not java objects. Therefore Java object state of the messages needs to be serialized into bytes to send it over the network or store it in the hard disk. Avro is a popular serialization/deserialization framework for Kafka key/value. Kafka clients handle load balancing, failover, and cluster expansion or contraction automatically as opposed to REST clients which typically require a third-party load balancer to achieve the same functionality. This provides the benefit is greater parallelism where a Kafka client will typically open up TCP connections to multiple brokers in the cluster and send or fetch data in parallel across multiple partitions of the same topic. There is a REST APIs in Apache Kafka for configuring Kafka Connect.</p><p>There are a number of third party REST Proxy implementations (such as the Confluent Kafka REST Proxy) which allow pub/sub over a REST interface but these are separate open source projects outside of Apache Kafka</p><h3>What is the role of Zookeeper?</h3><p>To run Kafka, you need Zookeeper. It can be understood as a Resource Management part of the whole ecosystem. It keeps the metadata about the processes running in the system, performs health check and broker leader selection, etc. It is a distributed key-value store and used for distributed cluster management.</p><p>Producer and consumers don’t directly interact with Zookeeper to know about the leader of a partition and other metadata, instead, they do metadata requests to Kafka Broker which in turn interact with Zookeeper and give metadata response and then producer and consumer get informed to which partition they need to write and read form respectively.</p><p>Zookeeper for Kafka performs following:</p><ul><li><strong>Controller election</strong>: The controller is one of the brokers and is responsible for maintaining the leader/follower relationship for all the partitions. When a node shuts down, it is the controller that tells other replicas to become partition leaders to replace the partition leaders on the node that is going away. Zookeeper is used to elect a controller, make sure there is only one and elect a new one it if it crashes.</li><li><strong>Cluster membership: </strong>Zookeeper maintains a list of all the brokers that are functioning and are a part of the cluster at any given moment.</li><li><strong>Topic configuration:</strong> — which topics exist, how many partitions each has, where are the replicas, who is the preferred leader, what configuration overrides are set for each topic</li><li><strong>Quotas</strong>: How much data is each client allowed to read and write</li><li><strong>Access Control Lists (ACL)</strong>: Who is allowed to read and write to which topic (old high level consumer) — Which consumer groups exist, who are their members and what is the latest offset each group got from each partition.</li></ul><h3>Design Patterns</h3><p>When setting up Consumers and Consumer Groups, we have several options to suit the different business needs. A consumer can read only those messages that have been written to all the replicas.</p><h3>Single partition / Single consumer</h3><p>Producer publishes messages into the single partition topic and the consumer consumes the messages from the single partition.</p><p>Of course, as there is a single partition this solution doesn’t scale. However, if you don’t need scaling it provides a total ordering of the messages which might be really helpful depending on your use cases.</p><p>If there are multiple Kafka node the partition can be replicated providing fault-tolerance. However, we need to restart the consumer in case of failure of the master partition.</p><h3>Single partition + Multiple consumers (Fan-out)</h3><p>This is a simple variation of the above where multiple consumers consume from the partition. As messages are not removed from Kafka when they are consumed, it’s possible to add more than one consumer, each maintaining its own message offset. Of course, the consumers must be in different consumer groups to consume from the same partition. This pattern is also known as fan-out.</p><h3>Multiple partitions + Multiple consumers</h3><p><strong>At least-once delivery</strong></p><p>Assumes that the consumer fails in the middle of fetching the message from a topic or committing the offset to Kafka. When the consumer recovers it will start from the previous offset, which means reprocessing some messages that were already processed. This is at-least-once delivery.</p><p><strong>Exactly-once delivery</strong></p><p>To achieve exactly-once delivery, no two consumers in a consumer group can pull the messages from the same partition. This ensures all messages are read and avoid any duplication; however, it also reduces data throughput. Kafka maintains load balance between Consumers and Partitions by evenly distributing the load between Consumers. Application while processing the message, keeps a track of each message by committing the offset along with a message to a transactional system. In case of a consumer crash, it will read the last committed offset from the transactional system and start reading after that point. This leads to no data duplication and no data loss but can lead to decreasing throughput.</p><p><strong>At-most-once</strong></p><p>Whilst Kafka guarantees at-least-once delivery by default, it also allows users to implement at most once delivery by disabling retries on the producer and committing its offset prior to processing a batch of messages. In a scenario, where the consumer has still not completed the processing of messages (or last read offset has not been committed in Kafka by the consumer), but the and crashes in between. So, when the consumer restarts, it will receive messages from the last committed offset and may lose some messages.</p><h3>So …</h3><h3>When to use the same consumer group?</h3><p>Consumers should be part of the same group when the consumer performing an operation needs to be scaled up to process in parallel. Consumers part of the same group would be assigned with different partitions. As said before, no two consumers of the same group-id would get assigned to the same partition. Hence, each consumer part of a group would be processing different data than the other consumers within the same group. Leading to parallel processing. This is one of the ways suggested by Kafka to achieve <strong>parallel processing in consumers</strong>. Here Kafka is acting as a <strong>queue/messaging</strong> platform.</p><h3>When to use the different consumer group?</h3><p>Consumers should not be within the same group when the consumers are performing different operations. Some consumers might update the database, while other sets of consumers might do some computations with the consumed data. In this case, we would want all these different consumers to be reading all the data from all the partitions. Hence, in this kind of use case consumers to read data from all the partitions, we should register these consumers with different group-id. Here Kafka is acting as a<strong> pub/sub</strong> platform.</p><h3>How would the offsets be maintained for consumers of different groups?</h3><p>Offset, an indicator of how many messages has been read by a consumer, would be maintained per consumer group-id and partition. When there are two different consumer groups, 2 different offsets would be maintained per partition. Consumers of different consumer groups can resume/pause independent of the other consumer groups. Hence, leaving no dependency between the consumers of different groups.</p><h3>What are some of the use cases?</h3><ul><li>Event Stream Processing (Log data, Financial data, clickstreams, real-time processing)</li><li>Microservice designs (CQRS, Event Sourcing, Pub/Sub etc.)</li><li>Decoupling of the systems</li><li>IoT Edge processing (Sensor data etc)</li><li>Big data Ingestion -Data Pipelines</li><li>ML Pipelines (AI and Data Science)</li></ul><h3>Who are the other competitors?</h3><p>How is Kafka different than other Pub Subs</p><ul><li>Exactly once semantics</li><li>Guaranteed Delivery</li><li>Ordered Delivery</li><li>Persistence</li></ul><p>Kafka isn’t the only player in the game when it comes to messaging queues. There are plenty of stand-in alternatives to Kafka, many of which are easier to set up- especially if you’re locked into a particular cloud provider. Here are some choices:</p><p><strong>Amazon SQS</strong>: One of the oldest alternatives to Kafka. Runs into issues when throughput increases significantly.</p><p><strong>Amazon Kinesis:</strong> The closest thing AWS has to “Kafka as a service”. Kinesis supports partitions like Kafka, as well as replicas.</p><p><strong>Google PubSub:</strong> A highly convenient alternative to Kafka. Perhaps one of the best options for anybody looking to hit the ground running, as there is no configuration needed. Can scale to massive volumes.</p><p><strong>RabbitMQ</strong>: A popular message broker, written in Erlang and similarly open-source. RabbitMQ plays well with almost every programming language.</p><h3>What Kafka doesn’t do?</h3><ul><li>Kafka is not push-based</li><li>Kafka does not have individual message IDs. Messages are simply addressed by their offset in the log.</li><li>Kafka also does not track the consumers i.e. who has consumed what messages. All of that is left up to the consumers. This is why it is known as the Dumb broker / smart consumer model — does not try to track which messages are read by consumers.</li><li>Consumers can’t delete the message. Kafka keeps all messages for a set period of time.</li></ul><h3>Kafka AWS deployment options</h3><p><a href="https://aws.amazon.com/blogs/big-data/best-practices-for-running-apache-kafka-on-aws/">https://aws.amazon.com/blogs/big-data/best-practices-for-running-apache-kafka-on-aws/</a></p><h3>Commercial offerings</h3><p>There are some commercial players who also offer Kafka with some additional benefits such as support, management, and configuration components. Hortonworks, Cloudera, Confluent are some of the players in this space. The below section covers some useful info on the Kafka offered by Confluent.</p><p>Some of Confluent Kafka’s offerings are free under the Confluent Community License, and some are only available through Confluent’s enterprise license. The Confluent Kafka Platform is free to download and use under the Confluent Community License. Unlike Apache Kafka, which is available under the Apache 2.0 license, the Confluent Community License is not open source and has a few restrictions. it offers additional features not available with the core Apache Kafka product. Some of the features included in the Confluent Community License are pre-built connectors, REST Proxy, KSQLDB, and Schema Registry.</p><p>Beyond the free-to-use Confluent Community License technology, Confluent also has a fee-based enterprise license that includes additional <strong>pre-built connectors</strong> and other tools such as Schema registry (supports schema definition for various message serialization choices e.g. Avro, Protobuf and JSON) and control center. More information can be found here, <a href="https://www.confluent.io/confluent-community-license-faq/">https://www.confluent.io/confluent-community-license-faq/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=594d6ab2fb6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>