<?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 Kawthar Asma Mahboubi on Medium]]></title>
        <description><![CDATA[Stories by Kawthar Asma Mahboubi on Medium]]></description>
        <link>https://medium.com/@kawther-asma?source=rss-f2d9c9e88609------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7wDDZnf42TepIGxJ2ZT56g.jpeg</url>
            <title>Stories by Kawthar Asma Mahboubi on Medium</title>
            <link>https://medium.com/@kawther-asma?source=rss-f2d9c9e88609------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 02:11:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kawther-asma/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[Implementing Keycloak Custom Event Listener for Sending Tracking Events to Segment]]></title>
            <link>https://kawther-asma.medium.com/implementing-keycloak-custom-event-listener-for-sending-tracking-events-to-segment-4bf384c474ee?source=rss-f2d9c9e88609------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bf384c474ee</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[segment]]></category>
            <category><![CDATA[keycloak-spi]]></category>
            <dc:creator><![CDATA[Kawthar Asma Mahboubi]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 16:27:54 GMT</pubDate>
            <atom:updated>2024-01-09T19:31:58.732Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This tutorial assumes you already know what <a href="https://www.keycloak.org/">keycloak</a> and <a href="https://segment.com/">segment</a> are.</blockquote><p>In this tutorial, we will create a basic SPI (Service Provider Interfaces) event listener to monitor user behavior when they sign in using Segment.</p><h3>Set up</h3><p>In this tutorial, we will use Maven as our package manager. So, let’s arrange our pom.xml file first.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;<br>         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>         xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;<br>    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br><br>    &lt;groupId&gt;com.asma.keycloak&lt;/groupId&gt;<br>    &lt;artifactId&gt;spi-after-user-login-segment-event-listener&lt;/artifactId&gt;<br>    &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;<br><br>    &lt;name&gt;After User Login Segment Event Listner&lt;/name&gt;<br>    &lt;description&gt;This event listener will send a segment event after user sign in&lt;/description&gt;<br><br>    &lt;properties&gt;<br>        &lt;java.version&gt;11&lt;/java.version&gt;<br>        &lt;keycloak.version&gt;23.0.0&lt;/keycloak.version&gt;<br><br>        &lt;maven.compiler.target&gt;${java.version}&lt;/maven.compiler.target&gt;<br>        &lt;maven.compiler.source&gt;${java.version}&lt;/maven.compiler.source&gt;<br>        &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;<br>        &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt;<br><br>        &lt;maven-compiler-plugin.version&gt;3.8.1&lt;/maven-compiler-plugin.version&gt;<br>    &lt;/properties&gt;<br><br>    &lt;dependencies&gt;<br>    &lt;!--   Keycloak  Dependencies  --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.keycloak&lt;/groupId&gt;<br>            &lt;artifactId&gt;keycloak-server-spi&lt;/artifactId&gt;<br>            &lt;version&gt;${keycloak.version}&lt;/version&gt;<br>            &lt;scope&gt;provided&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.keycloak&lt;/groupId&gt;<br>            &lt;artifactId&gt;keycloak-server-spi-private&lt;/artifactId&gt;<br>            &lt;version&gt;${keycloak.version}&lt;/version&gt;<br>            &lt;scope&gt;provided&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.keycloak&lt;/groupId&gt;<br>            &lt;artifactId&gt;keycloak-services&lt;/artifactId&gt;<br>            &lt;version&gt;${keycloak.version}&lt;/version&gt;<br>            &lt;scope&gt;provided&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;!-- Keycloak Dependencies END --&gt;<br>    <br>    &lt;build&gt;<br>        &lt;plugins&gt;<br>            &lt;plugin&gt;<br>            &lt;artifactId&gt;maven-assembly-plugin&lt;/artifactId&gt;<br>            &lt;configuration&gt;<br>                &lt;descriptorRefs&gt;<br>                &lt;descriptorRef&gt;jar-with-dependencies&lt;/descriptorRef&gt;<br>                &lt;/descriptorRefs&gt;<br>            &lt;/configuration&gt;<br>            &lt;executions&gt;<br>                &lt;execution&gt;<br>                &lt;id&gt;make-assembly&lt;/id&gt;<br>                &lt;phase&gt;package&lt;/phase&gt; <br>                &lt;goals&gt;<br>                    &lt;goal&gt;single&lt;/goal&gt;<br>                &lt;/goals&gt;<br>                &lt;/execution&gt;<br>            &lt;/executions&gt;<br>            &lt;/plugin&gt;<br>        &lt;/plugins&gt;<br>    &lt;/build&gt;<br>&lt;/project&gt;</pre><p>Next, we will create a class that implements the <a href="https://www.keycloak.org/docs-api/21.0.1/javadocs/org/keycloak/events/EventListenerProvider.html">EventListenerProvider</a> interface.</p><p><em>and its factory that implements </em><em>EventListenerProviderFactory </em>interface.</p><pre>package com.asma.keycloak.providers.aftersignin;<br><br>import org.keycloak.Config;<br>import org.keycloak.events.EventListenerProvider;<br>import org.keycloak.events.EventListenerProviderFactory;<br>import org.keycloak.models.KeycloakSession;<br>import org.keycloak.models.KeycloakSessionFactory;<br><br>public class AfterUserSignInSegmentEventListenerProviderFactory implements EventListenerProviderFactory {<br>    @Override<br>    public EventListenerProvider create(KeycloakSession keycloakSession) {<br>        return new AfterUserSignInSegmentEventListenerProvider(keycloakSession);<br>    }<br><br>    @Override<br>    public void init(Config.Scope scope) {<br><br>    }<br><br>    @Override<br>    public void postInit(KeycloakSessionFactory keycloakSessionFactory) {<br><br>    }<br><br>    @Override<br>    public void close() {<br><br>    }<br><br>    @Override<br>    public String getId() {<br>        // This the name of the spi , we are going to see this name shortly<br>        return &quot;after-user-login-segment-event-listener&quot;;<br>    }<br>}</pre><p>So this is the empty skelton that we are going to use to implement our logic.</p><p>Now let’s set up segment.</p><p>You need to have an account registered first ( else create one , it is pretty straightforward ).</p><p>Go to my sources and click on add source</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t-3wRxNIMosdDZNQL1Vxhg.png" /></figure><p>Choose Java and give it a name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*NkcYe10E-8JUmSo7F6B37A.png" /></figure><p>You get now your key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*JQcJcJoN5Y160d1CsNCV0w.png" /></figure><p>Let’s go back to code.</p><p>We need to add this dependency to our pom.xml file.</p><pre>&lt;!--  Segment  Dependecy   --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;com.segment.analytics.java&lt;/groupId&gt;<br>            &lt;artifactId&gt;analytics&lt;/artifactId&gt;<br>            &lt;version&gt;3.4.0&lt;/version&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br>&lt;!-- Segment Dependecy END --&gt;</pre><p>Now we are ready to write our code.</p><p>Inside the AfterUserSignInSegmentEventListenerProvider we are going to add this piece of code</p><pre>import com.segment.analytics.Analytics;<br>import com.segment.analytics.messages.TrackMessage;<br><br>...<br> <br> @Override<br>    public void onEvent(Event event) {<br><br>        if (event.getType().equals(EventType.LOGIN)) {<br>            Analytics analytics = Analytics.builder(System.getenv(&quot;SEGMENT_KEY&quot;)).build();<br>            analytics.enqueue(<br>                    TrackMessage.builder(&quot;User Signed In&quot;)<br>                            .userId(event.getUserId()));<br>        }<br><br>    }</pre><p>Now our event is ready let’s build our project</p><p>for that I am going to use docker to simplify the set up</p><pre>FROM maven:3.8.6-jdk-11-slim AS dependencies<br><br>COPY pom.xml /tmp/<br><br>COPY src /tmp/src<br><br>WORKDIR /tmp/<br><br>RUN mvn clean package<br><br>FROM quay.io/keycloak/keycloak:23.0.0 AS development<br><br>USER root<br><br>COPY --from=dependencies  /tmp/target/*.jar /opt/keycloak/providers/<br></pre><p>we build our image</p><pre>docker build . -t keycloak-segment --target development   </pre><p>Then we run it</p><pre>docker run --rm -p 8080:8080 -e SEGMENT_KEY=${SEGMENT_KEY}  -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin --name keycloak-segment keycloak-segment start-dev</pre><p>Don’t forget to substitute the SEGMENT_KEY with your segment key.</p><p>Now we need to configure the keycloak to add the event listner.</p><p>go to keycloak dashboard on localhost:8080 .</p><p>go to Realm Settings &gt; Events , if everything works just fine , you will be able to see the name of your spi in the list. Add the spi and then save.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*g8RIM_Z69Mumocg_CKhveA.png" /></figure><p>Now let’s test our setup , sign out and then sign in.</p><p>Go to segment , in the debugger tab and you will get your event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*WiWSg2BVGz5k9E6fzp4PTQ.png" /></figure><p>As simple as that.</p><p>The final code can be found <a href="https://github.com/KaoutharAsma/keycloak-segment">here</a>.</p><p>Thank you for reading !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bf384c474ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Saga Orchestration with NestJS and Kafka]]></title>
            <link>https://kawther-asma.medium.com/implementing-saga-orchestration-with-nestjs-and-kafka-129dac1fca98?source=rss-f2d9c9e88609------2</link>
            <guid isPermaLink="false">https://medium.com/p/129dac1fca98</guid>
            <category><![CDATA[nestjs-tutorial]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[microservices-pattern]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[saga-pattern]]></category>
            <dc:creator><![CDATA[Kawthar Asma Mahboubi]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 12:28:21 GMT</pubDate>
            <atom:updated>2024-01-07T12:28:21.673Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Before the advent of distributed systems, executing an atomic business transaction was relatively simpler and less complex. However, with the rise of distributed systems and micro-services architecture, the execution of <em>ACID</em> transactions has become increasingly complex. This complexity is due to the fact that a transaction can span various services. The success of a transaction require a cross-service transaction management strategy of the involved services.</p><p>One of the most famous solutions proposed is the SAGA pattern, so what is it ?</p><h3>What’s the Saga Pattern</h3><p>The Saga pattern is a strategic failure management approach within distributed applications. It coordinates transactions between microservices by organizing them into a sequence. Each transaction updates a microservice’s data and triggers the next step. In case of success or failure, compensating transactions are used to undo changes if needed.</p><p>There are two common saga implementation approaches, <em>choreography</em> and <em>orchestration</em>.</p><ul><li><strong>Choreography</strong> ( non centralized approach )— each local transaction publishes domain events that trigger local transactions in other services.</li><li><strong>Orchestration</strong> ( centralized approach )— an orchestrator (it can be a delegated service or one of the services concerned in the transaction ) tells the participants what local transactions to execute.</li></ul><p>In this article we will focus on implementing The <strong>Orchestration Approach</strong>.</p><h3>Implementation</h3><p>We are going to build the order management saga that we can sum up in the following steps:</p><ol><li><strong>Order Placement: </strong>The Order Service receives a request to create a new order, including details such as the list of products, quantities, customer information, and shipping details.</li><li><strong>Inventory Check: </strong>The Order Service communicates with the Inventory Service to check if the requested products are in stock. If there is sufficient inventory, the order can proceed; otherwise, the order is rejected.</li><li><strong>Payment Authorization: </strong>Once the order is confirmed, the Order Service contacts the Payment Service to authorize the payment. This step ensures that the customer has sufficient funds or credit to cover the order amount.</li><li><strong>Order Fulfillment: </strong>If payment is authorized, the Order Service updates the order status to “confirmed” and triggers any necessary processes for order fulfillment, such as packaging and shipping.</li><li><strong>Inventory Update:</strong>The Inventory Service updates the stock levels based on the products included in the order.</li></ol><p>This logic would be disturbed among three services:</p><ol><li>The Order Service</li><li>The Inventory Service</li><li>The Payment Service</li></ol><p>Where the <strong>order service<em> </em></strong>is going to play the <strong><em>orchestrator</em> </strong>role of this transaction and it will orchestrate the transaction through the broker ( Apache Kafka )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k2-KDB6yoY1jwoPdVnroYw.png" /></figure><p>Each step above should have its compensation logic to handle potential failures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhP0MHk1OTOqyXQqrxltOw.png" /></figure><p>Now we understands what we can implement, we can jump into code.</p><h3>Set up</h3><p><em>You need to have both </em><a href="https://docs.nestjs.com/first-steps"><em>nestjs</em></a><em> and </em><a href="https://docs.docker.com/engine/install/"><em>docker</em></a><em> installed.</em></p><p>We will start by creating three microservices ( order , inventory , payment ) using the nestjs cli :</p><pre>nest new order<br>nest new inventory<br>nest new payment</pre><p>Then in each of this services we are going to install the following packages:</p><pre>yarn add kafkajs @nestjs/microservices @nestjs/config</pre><ol><li><a href="https://docs.nestjs.com/techniques/configuration">@nestjs/config</a> to set up configuration and to be able to use (.env file)</li><li><a href="https://docs.nestjs.com/microservices/kafka">kafkajs</a> and <a href="https://docs.nestjs.com/microservices/basics">@nestjs/microservices </a>to be able to use async communication between microservices using kafka</li></ol><p>Now we can dockerize our apps to help us manage our services. For each service, we will create a Dockerfile with the following content:</p><pre>ARG NODEJS_DOCKER_IMAGE<br><br>FROM ${NODEJS_DOCKER_IMAGE} <br><br>WORKDIR /app<br><br>COPY --chown=node:node package.json yarn.lock ./<br><br>RUN yarn install<br><br>COPY --chown=node:node . .<br><br>CMD [ &quot;yarn&quot;, &quot;start&quot; ]</pre><p>And we can consolidate the configuration of all services in a single docker-compose file:</p><pre>version: &quot;3.8&quot;<br><br>services:<br>  order:<br>    restart: always<br>    build:<br>      context: order<br>      args:<br>        NODEJS_DOCKER_IMAGE: ${NODEJS_DOCKER_IMAGE}<br>    volumes:<br>      - ./order:/app<br>      - /app/node_modules<br>    command: [yarn, start:debug]<br><br>  inventory:<br>    build:<br>      context: inventory<br>      args:<br>        NODEJS_DOCKER_IMAGE: ${NODEJS_DOCKER_IMAGE}<br>    restart: always<br>    volumes:<br>      - ./inventory:/app<br>      - /app/node_modules<br>    command: [yarn, start:debug]<br><br>  payment:<br>    build:<br>      context: payment<br>      args:<br>        NODEJS_DOCKER_IMAGE: ${NODEJS_DOCKER_IMAGE}<br>    restart: always<br>    volumes:<br>      - ./payment:/app<br>      - /app/node_modules<br>    command: [yarn, start:debug]<br><br>  broker:<br>    image: bitnami/kafka:3.3.1<br>    volumes:<br>      - kafka_data:/var/lib/kafka/data<br>    user: root<br>    ports:<br>      - 9092<br>    environment:<br>      - KAFKA_ENABLE_KRAFT=yes<br>      - KAFKA_CFG_PROCESS_ROLES=broker,controller<br>      - KAFKA_CFG_CONTROLLER_LISTENER_NAMES=CONTROLLER<br>      - KAFKA_CFG_LISTENERS=PLAINTEXT://:9092,CONTROLLER://:9093<br>      - KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP=CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT<br>      - KAFKA_CFG_ADVERTISED_LISTENERS=PLAINTEXT://broker:9092<br>      - KAFKA_BROKER_ID=1<br>      - KAFKA_KRAFT_CLUSTER_ID=LelM2dIFQkiUFvXCEcqRWA<br>      - KAFKA_CFG_CONTROLLER_QUORUM_VOTERS=1@broker:9093<br>      - ALLOW_PLAINTEXT_LISTENER=yes<br><br>volumes:<br>  kafka_data:</pre><p>You might have noticed that we’ve added Kafka without Zookeeper. Great news! This change was introduced for the first time as a <a href="https://cwiki.apache.org/confluence/display/KAFKA/KIP-500%3A+Replace+ZooKeeper+with+a+Self-Managed+Metadata+Quorum">KIP-500</a> and has been provided as an early access version with the 2.8.0 release.</p><p>The good news is that Docker Compose, by default, creates a default network for the services within the Docker Compose, simplifying our setup. Another thing you may have noticed is that we are only exposing the order service to our host network, as the other services will be accessed solely through the internal docker network , all managed by the order service ( the orchestrator ).</p><p>Now we can proceed to run our project:</p><pre>docker compose up -d</pre><h3>Set up Kafka inside the services</h3><p>Inside the main.tsfile of payment service we need to expose communication through kafka with the code bellow:</p><pre>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br><br>  app.connectMicroservice&lt;MicroserviceOptions&gt;({<br>    transport: Transport.KAFKA,<br>    options: {<br>      client: {<br>        clientId: config().services.payment.clientId,<br>        brokers: [config().broker],<br>      },<br>      consumer: {<br>        groupId: config().services.payment.groupId,<br>      },<br>    },<br>  });<br><br>  await app.startAllMicroservices();<br>}<br>bootstrap();</pre><pre>export default () =&gt; ({<br>  broker: process.env.BROKER ?? &#39;broker:9092&#39;,<br>  services: {<br>    payment: {<br>      clientId: &#39;payment&#39;,<br>      groupId: &#39;payment&#39;,<br>      name: &#39;payment-kafka-client&#39;,<br>    },<br>  },<br>});</pre><p>Similarly for the inventory service:</p><pre>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br><br>  app.connectMicroservice&lt;MicroserviceOptions&gt;({<br>    transport: Transport.KAFKA,<br>    options: {<br>      client: {<br>        clientId: config().services.inventory.clientId,<br>        brokers: [config().broker],<br>      },<br>      consumer: {<br>        groupId: config().services.inventory.groupId,<br>      },<br>    },<br>  });<br><br>  await app.startAllMicroservices();<br>}<br>bootstrap();</pre><pre>export default () =&gt; ({<br>  broker: process.env.BROKER ?? &#39;broker:9092&#39;,<br>  services: {<br>    inventory: {<br>      clientId: &#39;inventory&#39;,<br>      groupId: &#39;inventory&#39;,<br>      name: &#39;inventory-kafka-client&#39;,<br>    },<br>  },<br>});</pre><p>For the <strong>order service</strong>, we are going to instantiate the clients that are going to communicate with the <strong>payment</strong> and the <strong>inventory</strong> service inside the app.module through the following code :</p><pre>@Module({<br>  imports: [<br>    ClientsModule.register([<br>      {<br>        name: config().services.inventory.name,<br>        transport: Transport.KAFKA,<br>        options: {<br>          client: {<br>            clientId: config().services.order.clientId,<br>            brokers: [config().broker],<br>          },<br>          consumer: {<br>            groupId: config().services.inventory.groupId,<br>          },<br>        },<br>      },<br>      {<br>        name: config().services.payment.name,<br>        transport: Transport.KAFKA,<br>        options: {<br>          client: {<br>            clientId: config().services.order.clientId,<br>            brokers: [config().broker],<br>          },<br>          consumer: {<br>            groupId: config().services.payment.groupId,<br>          },<br>        },<br>      },<br>    ]),<br>  ],<br>  controllers: [],<br>  providers: [],<br>})</pre><pre>export default () =&gt; ({<br>  broker: process.env.BROKER ?? &#39;broker:9092&#39;,<br>  services: {<br>    order: {<br>      clientId: &#39;order&#39;,<br>      groupId: &#39;order&#39;,<br>      name: &#39;order-kafka-client&#39;,<br>    },<br>    payment: {<br>      clientId: &#39;payment&#39;,<br>      groupId: &#39;payment&#39;,<br>      name: &#39;payment-kafka-client&#39;,<br>    },<br>    inventory: {<br>      clientId: &#39;inventory&#39;,<br>      groupId: &#39;inventory&#39;,<br>      name: &#39;inventory-kafka-client&#39;,<br>    },<br>  },<br>});</pre><p>Now that we have successfully set up the means of asynchronous communication through Kafka, we can now delve into the Saga part.</p><h3>Set up the Saga Pattern</h3><p>To be concise and avoid unnecessary details, I’m going to skip the internal logic of each step and consider each one as a black box with clear inputs and outputs. If you want to get an idea about that, you can take a look into the <a href="https://github.com/KaoutharAsma/nestjs-kafka-saga-pattern">repo</a>.</p><p>Now, we are going to introduce two entities that will encapsulate our Saga logic — two entities named CreateOrderSaga and Step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QgIenG31o5osapX5ip1RCA.png" /></figure><p>Where each Step extends this class:</p><pre>export abstract class Step&lt;T, R&gt; {<br>  name: string;<br>  abstract invoke(params: T): Promise&lt;R&gt;;<br>  abstract withCompenstation(params: T): Promise&lt;R&gt;;<br>}</pre><p>Therefore, each step is responsible for defining its internal logic and its corresponding compensation logic.</p><p>Let’s walk through each step individually to understand what’s going on</p><ol><li><strong>Place Order</strong>:</li></ol><pre><br>@Injectable()<br>export class PlaceOrderStep extends Step&lt;Order, void&gt; {<br>  constructor(<br>    @Inject(&#39;order-repository&#39;)<br>    private orderRepository: OrderRepositoryInterface,<br>  ) {<br>    super();<br>    this.name = &#39;Place Order Step&#39;;<br>  }<br><br>  invoke(order: Order): Promise&lt;void&gt; {<br>    /* Save the order into the repository (the default stat of the order is pending). */<br>    this.orderRepository.save(order);<br>    return Promise.resolve();<br>  }<br><br>  withCompenstation(order: Order): Promise&lt;void&gt; {<br>    /* If the Saga has failed, we need to cancel the order to undo this step. */<br>    order.cancel();<br>    this.orderRepository.update(order);<br>    return Promise.resolve();<br>  }<br>}</pre><p>2. <strong>Check Product Availability</strong></p><pre>@Injectable()<br>export class CheckProductsAvailibityStep extends Step&lt;Order, void&gt; {<br>  constructor(<br>    @Inject(config().services.inventory.name)<br>    private inventoryClient: ClientKafka,<br>  ) {<br>    super();<br>    this.name = &#39;Check Products Availbility Step&#39;;<br>  }<br><br>  async invoke(order: Order): Promise&lt;void&gt; {<br>    const availbleProducts = await lastValueFrom(<br>      /* Call the inventory service ( through kafka ) to check for availibity. */<br>      this.inventoryClient.send(&#39;inventory.products.get&#39;, {<br>        products: order.orderItems.map((item) =&gt; ({<br>          id: item.productId,<br>          quantity: item.quantity,<br>        })),<br>      }),<br>    );<br><br>    if (!availbleProducts.availible) {<br>      /* If the products in the order are not available then we throw outOfStock Error*/<br>      throw new OutOfStockError(<br>        `${order.orderItems.map((item) =&gt; item.productId)} is not available`,<br>      );<br>    }<br>  }<br><br>  withCompenstation(params: Order): Promise&lt;any&gt; {<br>    /* We haven&#39;t performed any writing, so we don&#39;t need to take any action to undo this step. */<br>    return Promise.resolve();<br>  }<br><br>  async onModuleInit() {<br>    /* <br>    IMPORTANT:<br>      This instructs the client to subscribe to the response of the call above.<br>      It creates a new topic inventory.products.get.reply to listen to the responses. <br>      Without this piece of code, we cannot retrieve the response from the Kafka service.<br>    */<br>    this.inventoryClient.subscribeToResponseOf(&#39;inventory.products.get&#39;);<br>    await this.inventoryClient.connect();<br>  }<br>}</pre><p>3. <strong>Authorize Payment</strong>:</p><p>In real life set up , payment is more sophisticated step , but for simplicity purposes and to not get lost in this step , we choose a very simplified version ( that doesn’t refelect the real life set up ).</p><pre>@Injectable()<br>export class AuthorizePaymentStep extends Step&lt;Order, void&gt; {<br>  constructor(<br>    @Inject(config().services.payment.name) private paymentClient: ClientKafka,<br>  ) {<br>    super();<br>    this.name = &#39;Authorize Payment Step&#39;;<br>  }<br><br>  async invoke(order: Order): Promise&lt;any&gt; {<br>    const paymnetAuthorization = await lastValueFrom(<br>    /* Call the payment service ( through kafka ) to authorize payment */<br>      this.paymentClient.send(&#39;payment.payment.authorize&#39;, {<br>        orderId: order.id,<br>        amount: order.orderItems.reduce((accumulator: number, item) =&gt; {<br>          return accumulator + item.totalPrice;<br>        }, 0),<br>      }),<br>    );<br><br>    if (!paymnetAuthorization.authorized) {<br>     /* If the payment is not authorized than throw an error */<br>      throw new PaymentNotSuccessfulError(&#39;The payment unsuccessful&#39;);<br>    }<br>  }<br><br>  async withCompenstation(order: Order): Promise&lt;any&gt; {<br>   /*To compensate this step , we need to trigger the refund */<br>    await lastValueFrom(<br>      this.paymentClient.send(&#39;payment.payment.refund&#39;, {<br>        orderId: order.id,<br>        amount: order.orderItems.reduce((accumulator: number, item) =&gt; {<br>          return accumulator + item.totalPrice;<br>        }, 0),<br>      }),<br>    );<br>  }<br><br>  async onModuleInit() {<br>    /* We subscribe for both calls responses to be able to receive the reponses*/<br>    this.paymentClient.subscribeToResponseOf(&#39;payment.payment.authorize&#39;);<br>    this.paymentClient.subscribeToResponseOf(&#39;payment.payment.refund&#39;);<br><br>    await this.paymentClient.connect();<br>  }<br>}</pre><p>4. <strong>Confirm Order</strong></p><pre>@Injectable()<br>export class ConfirmOrderStep extends Step&lt;Order, void&gt; {<br>  constructor(<br>    @Inject(&#39;order-repository&#39;)<br>    private orderRepository: OrderRepositoryInterface,<br>  ) {<br>    super();<br>    this.name = &#39;Confirm Order Step&#39;;<br>  }<br><br>  invoke(order: Order): Promise&lt;void&gt; {<br>    order.confirm();<br>    this.orderRepository.update(order);<br>    return Promise.resolve();<br>  }<br><br>  withCompenstation(order: Order): Promise&lt;void&gt; {<br>    /* To undo this step , we need to cancel the order */<br>    order.cancel();<br>    this.orderRepository.update(order);<br>    return Promise.resolve();<br>  }<br>}</pre><p>5. <strong>Update Stock</strong></p><pre>@Injectable()<br>export class UpdateStockStep extends Step&lt;Order, void&gt; {<br>  constructor(<br>    @Inject(config().services.inventory.name)<br>    private inventoryClient: ClientKafka,<br>  ) {<br>    super();<br>    this.name = &#39;Update Stock Step&#39;;<br>  }<br><br>  async invoke(order: Order): Promise&lt;void&gt; {<br>    /* Call the inventory service ( through kafka ) to update the new stock. */<br>    const stockUpdate = await lastValueFrom(<br>      this.inventoryClient.send(&#39;inventory.stock.reduce&#39;, {<br>        products: order.orderItems.map((item) =&gt; ({<br>          id: item.productId,<br>          quantity: item.quantity,<br>        })),<br>      }),<br>    );<br>    if (!stockUpdate.success) {<br>     /* If an error has happened through this step throw an error. */<br>      throw new Error(&quot;Couldn&#39;t update stock&quot;);<br>    }<br>  }<br><br>  async withCompenstation(order: Order): Promise&lt;void&gt; {<br>   /* As a compensation we are going to ask for restock with the same amount. */<br>    const stockUpdate = await lastValueFrom(<br>      this.inventoryClient.send(&#39;inventory.stock.restock&#39;, {<br>        products: order.orderItems.map((item) =&gt; ({<br>          id: item.productId,<br>          quantity: item.quantity,<br>        })),<br>      }),<br>    );<br>  }<br><br>  async onModuleInit() {<br>    /* We subscribe for both calls responses to be able to receive the reponses*/<br>    this.inventoryClient.subscribeToResponseOf(&#39;inventory.stock.reduce&#39;);<br>    this.inventoryClient.subscribeToResponseOf(&#39;inventory.stock.restock&#39;);<br>    await this.inventoryClient.connect();<br>  }<br>}</pre><p>Now we have the details of each step we are going to sum them up inside the CreateOrderSaga</p><pre>@Injectable()<br>export class CreateOrderSaga {<br>  private steps: Step&lt;Order, void&gt;[] = [];<br><br>  /* To keep track of the already successful steps, we will need this information to undo them in case of an error. */<br>  private successfulSteps: Step&lt;Order, void&gt;[] = [];<br><br>  constructor(<br>    /*<br>      We introduce the steps that compose this Saga.<br>    */<br>    @Inject(&#39;place-order-step&#39;) step1: PlaceOrderStep,<br>    @Inject(&#39;check-products-availibity&#39;) step2: CheckProductsAvailibityStep,<br>    @Inject(&#39;authorize-payment&#39;) step3: AuthorizePaymentStep,<br>    @Inject(&#39;confirm-order&#39;) step4: ConfirmOrderStep,<br>    @Inject(&#39;update-stock&#39;) step5: UpdateStockStep,<br>  ) {<br>    this.steps = [step1, step2, step3, step4, step5];<br>  }<br><br>  async execute(order: Order) {<br>    /* We loop through each step */<br>    for (let step of this.steps) {<br>      try {<br>        console.info(`Invoking: ${step.name} ...`);<br>        /* We Invoke each step */<br>        await step.invoke(order);  <br>        /* and keep track of each succeful step */<br>        this.successfulSteps.unshift(step);<br>      } catch (error) {<br>        console.error(`Failed Step: ${step.name} !!`);<br>        /* If an error has occurred, undo the previous successful steps. */<br>        this.successfulSteps.forEach(async (s) =&gt; {<br>          console.info(`Rollbacking: ${s.name} ...`);<br>          await s.withCompenstation(order);<br>        });<br>        throw error;<br>      }<br>    }<br>    console.info(&#39;Order Creation Transaction ended successfuly&#39;);<br>  }<br>}</pre><p>Now that we have everything in place, let’s test it out:</p><p>Inside the inventory service, I’ve set up some test data for use in our tests.</p><pre>  private products: Product[] = [<br>    new Product(<br>      {<br>        name: &#39;Laptop&#39;,<br>        price: 999.99,<br>        quantity: 1,<br>      },<br>      &#39;P001&#39;,<br>    ),<br>    new Product(<br>      {<br>        name: &#39;Smartphone&#39;,<br>        price: 599.99,<br>        quantity: 100,<br>      },<br>      &#39;P002&#39;,<br>    ),<br>    new Product(<br>      {<br>        name: &#39;Wireless Headphones&#39;,<br>        price: 89.99,<br>        quantity: 75,<br>      },<br>      &#39;P003&#39;,<br>    ),<br>    new Product(<br>      {<br>        name: &#39;Smartwatch&#39;,<br>        price: 129.99,<br>        quantity: 30,<br>      },<br>      &#39;P004&#39;,<br>    ),<br>    new Product(<br>      {<br>        name: &#39;4K Smart TV&#39;,<br>        price: 799.99,<br>        quantity: 20,<br>      },<br>      &#39;P005&#39;,<br>    ),<br>    new Product(<br>      {<br>        name: &#39;Gaming Console&#39;,<br>        price: 299.99,<br>        quantity: 40,<br>      },<br>      &#39;P006&#39;,<br>    ),<br>    new Product(<br>      {<br>        name: &#39;Coffee Maker&#39;,<br>        price: 49.99,<br>        quantity: 60,<br>      },<br>      &#39;P007&#39;,<br>    ),<br>    new Product(<br>      {<br>        name: &#39;Bluetooth Speaker&#39;,<br>        price: 69.99,<br>        quantity: 80,<br>      },<br>      &#39;P008&#39;,<br>    ),<br>    new Product(<br>      {<br>        name: &#39;Digital Camera&#39;,<br>        price: 449.99,<br>        quantity: 25,<br>      },<br>      &#39;P009&#39;,<br>    ),<br>    new Product(<br>      {<br>        name: &#39;Fitness Tracker&#39;,<br>        price: 79.99,<br>        quantity: 55,<br>      },<br>      &#39;P010&#39;,<br>    ),<br>  ];</pre><p>Let’s call the order service</p><pre>curl -X &#39;POST&#39; \<br>  &#39;http://localhost:3000/orders&#39; \<br>  -H &#39;accept: */*&#39; \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{<br>  &quot;customerId&quot;: &quot;averrhoes&quot;,<br>  &quot;orderItems&quot;: [<br>    {<br>      &quot;productId&quot;: &quot;P001&quot;,<br>      &quot;quantity&quot;: 1,<br>      &quot;totalPrice&quot;: 999.99<br>    }<br>  ]<br>}&#39;</pre><p>This will result in successful transaction. If we check the logs of order service we will get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*W2G3WCBzmFTfw_9LfCm6lg.png" /></figure><p>The product P001 contains only one item in stock, and it has been consumed by this client, Averrhoes.</p><p>Now, let’s perform the same request again. We will get…</p><pre>{&quot;message&quot;:&quot;P001 is not availbe&quot;}</pre><p>If we check the logs we will find this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*cEEpwlV509IGMv4HzbqhcA.png" /></figure><h3>Wrap up</h3><p>Of course, in real-life setups, the Saga Pattern can be more sophisticated and may need to be coupled with other patterns to ensure consistency despite all types of failures (for instance, the <a href="https://microservices.io/patterns/data/transactional-outbox.html">outbox pattern</a>). However, the outline idea and skeleton remain relatively the same.</p><p>The final code can be found here <a href="https://emojipedia.org/backhand-index-pointing-right">👉</a> <a href="https://github.com/KaoutharAsma/nestjs-kafka-saga-pattern">https://github.com/KaoutharAsma/nestjs-kafka-saga-pattern</a></p><p>Thank you for reading!</p><h3>References</h3><ul><li><a href="https://docs.nestjs.com/">Documentation | NestJS - A progressive Node.js framework</a></li><li><a href="https://learn.microsoft.com/en-us/azure/architecture/reference-architectures/saga/saga">Saga pattern - Azure Design Patterns</a></li><li><a href="https://microservices.io/patterns/data/saga.html">Microservices Pattern: Pattern: Saga</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=129dac1fca98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Dockerfiles Made Easy for NestJS Applications]]></title>
            <link>https://kawther-asma.medium.com/optimizing-dockerfiles-made-easy-for-nestjs-applications-01bf2f2565c2?source=rss-f2d9c9e88609------2</link>
            <guid isPermaLink="false">https://medium.com/p/01bf2f2565c2</guid>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[nestjs-tutorial]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <dc:creator><![CDATA[Kawthar Asma Mahboubi]]></dc:creator>
            <pubDate>Sat, 06 Jan 2024 12:14:37 GMT</pubDate>
            <atom:updated>2024-01-06T12:14:37.489Z</atom:updated>
            <content:encoded><![CDATA[<p>The power of docker is undeniable; it is such a powerful tool that help us put our application code inside a small boxes and easily ship them into different environments.</p><p>In this article we are going to walk through a simple step by step process to optimize your Nestjs’ Dockerfile for multiple environments.</p><h4>Installation</h4><p>Ensure you have both <a href="https://docs.docker.com/engine/install/">Docker</a> and <a href="https://docs.nestjs.com/first-steps">NestJS</a> installed for this tutorial.</p><p>First things first: Let’s create our NestJS application.</p><pre>nest new docker-file-optimization  </pre><h4>Set up Dockerfile</h4><p>Let’s create now our Dockerfile</p><pre>cd docker-file-optimization &amp;&amp; touch Dockerfile</pre><p>Let’s start simple , let’s create a simple Dockerfile :</p><pre>FROM node:18.19.0-slim<br><br>WORKDIR /app<br><br>COPY package.json yarn.lock ./<br><br>RUN yarn install --immutable<br><br>COPY . .<br><br>CMD [ &quot;yarn&quot;, &quot;start&quot; ]</pre><p>Now, let’s break it down:</p><pre>FROM node:18.19.0-slim</pre><p>I am going to use node:18.19.0-slim For the time writing this article (18.19.0 is the LTS version)</p><p>I choose the slim version to obtain a smaller image size, which not only saves disk space but also reduces the vulnerability surface by having a smaller software footprint.</p><p>I also opt for the slim version over Alpine versions because of its stability. You can refer to this <a href="https://snyk.io/blog/choosing-the-best-node-js-docker-image/">article</a> to get more details.</p><pre>COPY package.json yarn.lock ./<br><br>RUN yarn install --immutable<br><br>COPY . .</pre><p>You’ve probably noticed that I first installed the packages before copying the remaining code. This is to leverage Docker cache layers. This way, we only need to reinstall if and only if the package.json or yarn.lock has changed.</p><p>Now let’s build our image</p><pre>docker build . -t dev-image</pre><p>Next, let’s check the size of this image:</p><pre>docker image ls dev-image</pre><p>If everything goes as expected, the size should be 700MB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*oloJiSQAJzkUjM9YWkhR5A.png" /></figure><p>Now let’s see how we can optimize it .</p><pre><br>FROM node:18.19.0-slim as build<br><br>WORKDIR /app<br><br>ENV NODE_ENV production<br><br>COPY --chown=node:node package.json yarn.lock ./<br><br>RUN yarn install --frozen-lockfile --production<br><br>COPY --chown=node:node . .<br><br>RUN yarn build<br><br>CMD [ &quot;yarn&quot;, &quot;start:prod&quot; ]</pre><p>What have we introduced?</p><p>We added the following steps:</p><pre>RUN yarn install --frozen-lockfile --production</pre><p>This step installs only the dependencies necessary for running the application and ignores all the devDependencies.</p><pre>RUN yarn build</pre><p>This will compile the app into an output folder ( dist ).</p><p>Now, let’s build the image</p><pre>docker build . -t build-image --target build  </pre><p>if we check the size now we get 557MB</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*k5OgBRdSAeIoaQmFjVoJPQ.png" /></figure><p>We’ve reduced the image size by approximately 20%.</p><p>However, We can do better!</p><p>Notice that we are still copying the entire folder into our final image, which is unnecessary since we only need the compiled folders. Let’s optimize our Dockerfile accordingly.</p><pre>FROM node:18.19.0-slim as production<br><br>WORKDIR /app<br><br>ENV NODE_ENV production<br><br>COPY --chown=node:node --from=build /app/dist ./dist<br>COPY --chown=node:node --from=build /app/node_modules ./node_modules<br><br>CMD [&quot;node&quot;, &quot;dist/main.js&quot;]</pre><p>What we’ve actually done is copy only the necessary files from the previous stage (build) and skip every other unnecessary file. Now, let’s check the size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*7pSiGC7DFdZfFmd5tmqOTw.png" /></figure><p>We have successfully reduced the image size by 50%.</p><h3>Wrap up</h3><p>In summary, we optimized our NestJS Dockerfile by:</p><ol><li>Using a multistage build.</li><li>Installing only production dependencies.</li><li>Selectively copying essential files.</li></ol><p><strong>Result</strong>: Achieved a 50% reduction in image size for a more efficient deployment.</p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01bf2f2565c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>