<?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 tuananhhedspibk on Medium]]></title>
        <description><![CDATA[Stories by tuananhhedspibk on Medium]]></description>
        <link>https://medium.com/@tuananhhedspibk?source=rss-6a68697251eb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*p2M9SB8eDyQWeGDzaH0eyQ.jpeg</url>
            <title>Stories by tuananhhedspibk on Medium</title>
            <link>https://medium.com/@tuananhhedspibk?source=rss-6a68697251eb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:11:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tuananhhedspibk/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[How did I build a simple NestJS app with k8s, ArgoCD, and terraform (Part 3)]]></title>
            <link>https://levelup.gitconnected.com/how-did-i-build-a-simple-nestjs-app-with-k8s-argocd-and-terraform-part-3-6d128e0dc784?source=rss-6a68697251eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d128e0dc784</guid>
            <category><![CDATA[argo-cd]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[tuananhhedspibk]]></dc:creator>
            <pubDate>Wed, 18 Jun 2025 03:49:53 GMT</pubDate>
            <atom:updated>2025-06-18T03:49:53.564Z</atom:updated>
            <content:encoded><![CDATA[<p>In this part, I’m gonna show you:</p><ul><li>How to create EKS.</li><li>How to deploy ArgoCD with EKS.</li><li>How to build a deployment flow of server-app and k8s.</li></ul><h3>Create EKS</h3><blockquote>EKS is a managed Kubernetes service provided by AWS that allows us to run Kubernetes without needing to install and operate our own Kubernetes control plane or nodes</blockquote><p>To create and use EKS we must create:</p><ul><li>An EKS cluster.</li><li>An EKS node group.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c2d36dfced8fce2917fe937f300577b/href">https://medium.com/media/7c2d36dfced8fce2917fe937f300577b/href</a></iframe><p>Pay attention that, for EKS cluster and node group we <strong>MUST PUT THEM IN PRIVATE SUBNETS.</strong></p><p>So the subnet_ids config for both must be <strong>private subnet ids</strong>.</p><p>The imagination will be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*wZqcb5OdbHFbDnZ65okS2w.png" /></figure><p>For the roles, we have to create:</p><ul><li>EKS cluster role.</li><li>EKS node group role.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d56b2b05401704697ee21b17f33a6e0/href">https://medium.com/media/2d56b2b05401704697ee21b17f33a6e0/href</a></iframe><p>We can see that the AssumeRole service for eks_node_role is EC2, so we can infer that the EKS node group is based on EC2.</p><p>Our EKS cluster will be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jd5T0lx69EAsdqSTveYYbQ.png" /></figure><p>By executing terraform apply , we can create the EKS cluster on the AWS like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQUqLWzI86n2B4gf3sRTyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T1BKBEyTdTN8BHGD2dr2TQ.png" /></figure><p>OK, that is for EKS. Let’s move to ArgoCD.</p><h3>Deploy ArgoCD with EKS</h3><p>By running the following command, we could connect to our Kubernetes cluster.</p><pre>$aws eks --region ap-northeast-1 update-kubeconfig --name restful-app-stg-eks-cluster</pre><p>After that, we can apply the ArgoCD config</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kY6yisHGBVxO8dNI3j7qBQ.png" /></figure><p>Open the load balancers tab, get the URL of the load balancer with “random name” and open the ArgoCD web UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GNBOnfHKIGA7kOuQmdNArw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YwNPBkL29HfB6nMuBBSXQA.png" /></figure><p>Use the “admin” username with the password that can be obtained by this command</p><pre>$kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath=&quot;{.data.password}&quot; | base64 -d</pre><p>And we got this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_yoNkt8M9kdYlmQaSG-OFw.png" /></figure><p>Before creating the application, I want you to attend that because we use the SecretManager to configure the environment variables, so we have to:</p><ol><li>Install the SecretManager Driver for our cluster.</li><li>Create the IAM role for Service Account to get the SecretManager value.</li></ol><blockquote>Service Account is a special type of account that provides the identity for processes that running in a Pod</blockquote><p>Put it simply:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mWTWYh5XFP2JLyx7DPjCCA.png" /></figure><p>First, run the following commands to install SecretManager Driver</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ea321a4f1f40409f0583b8349eb9726/href">https://medium.com/media/9ea321a4f1f40409f0583b8349eb9726/href</a></iframe><p>Second, run the following command to create the IAM role:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/946bcadc42a68bbce3eccd827db9e45a/href">https://medium.com/media/946bcadc42a68bbce3eccd827db9e45a/href</a></iframe><p>But remember the trust relationship of the IAM role should be this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2b8cb68528ebbf9d58f3e7c9e2486c5/href">https://medium.com/media/d2b8cb68528ebbf9d58f3e7c9e2486c5/href</a></iframe><p>And don’t forget to run the below command to associate OIDC Identity Provider with an EKS cluster.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c745d7651d07a92e81e1543f09a2e83a/href">https://medium.com/media/c745d7651d07a92e81e1543f09a2e83a/href</a></iframe><p>Now, it’s time to apply the ArgoCD configure</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40106bd871e07a65c45b25420e83ee55/href">https://medium.com/media/40106bd871e07a65c45b25420e83ee55/href</a></iframe><p>to get this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TBQ6wqyDU9JQ8A-v3IBbkA.png" /></figure><p>But, we still can not access to the swagger UI, so we need to create</p><ul><li>A Controller</li><li>A Router</li></ul><p>for accessing.</p><p>For controller, we use this command:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77cc1f258b54ab69f22585520abc1636/href">https://medium.com/media/77cc1f258b54ab69f22585520abc1636/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hhGRcTeef8vSikTbiA7HEw.png" /></figure><p>For router, I used Route53 to:</p><ul><li>Create a domain.</li><li>Connect with the controller.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*wICBUSWZdtwfIfEZNH9X7g.png" /></figure><p>For me, I can go to <a href="http://nestjs.restful-app.com/swagger">http://nestjs.restful-app.com/swagger</a> to get this UI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rKbSfJZb92Tjp5H2dJycEw.png" /></figure><p>Alright, that’s all for deploying ArgoCD with EKS. Let’s move to the last part of this article.</p><h3>Build a deployment flow of server-app and k8s</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pqsdnXsm8lkGih-Wl8ltkw.png" /></figure><p>Basically, it has two steps:</p><ol><li>Build &amp; Push image to ECR</li><li>Trigger restful-app-k8s repository github action to overwrite imageTag in kustomization.</li></ol><h4>Build &amp; Push image to ECR</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/085bae0345f22f89d9834e287692576d/href">https://medium.com/media/085bae0345f22f89d9834e287692576d/href</a></iframe><p>We have three main steps here:</p><ol><li>Extract github commit sha256 to use it as image_tag for identity purposes.</li><li>Build docker image.</li><li>Push built image to ecr.</li></ol><p>This is Dockerfile</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b836483d4624f4afbf5b14f392a1bd8a/href">https://medium.com/media/b836483d4624f4afbf5b14f392a1bd8a/href</a></iframe><p>In this Dockerfile I split into two phases</p><ol><li><strong>Builder</strong>: install needed packages.</li><li><strong>Runner</strong>: expose running port and startup the app.</li></ol><h4>Trigger restful-app-k8s repository github action to overwrite imageTag in kustomization</h4><p>In restful-app-k8s repository, I created the github action called kustomize , the flow of this action is:</p><ol><li>Install kustomize cli</li><li>Update image tag</li><li>Create PR automatically</li><li>Merge the PR to main branch</li></ol><p>You can see the below code for more detail about each steps.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a3250c6a083aae3d8285612d4c75190/href">https://medium.com/media/3a3250c6a083aae3d8285612d4c75190/href</a></iframe><p>This is the example pull request of updating image tag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XChiFSMxknrwxboUpFUjQA.png" /></figure><p>After image tag is updated, ArgoCD will sync it automatically to pull the newest ECR image and deploy the application again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LINYuk0GrEDtbUwLWW3hTw.png" /></figure><h3>Summary</h3><p>That’s all about how to build a simple NestJS app with k8s, ArgoCD and terraform.</p><p>I hope that via this series, you can:</p><ul><li>Know how to build a deployment flow with k8s, ArgoCD.</li><li>Know how to build an app with k8s, ArgoCD and EKS.</li></ul><p>Many thanks for reading and I’ll see you in the following articles.</p><p>Happy coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d128e0dc784" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-did-i-build-a-simple-nestjs-app-with-k8s-argocd-and-terraform-part-3-6d128e0dc784">How did I build a simple NestJS app with k8s, ArgoCD, and terraform (Part 3)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How did I build a simple NestJS app with k8s, ArgoCD, and terraform (Part 2)]]></title>
            <link>https://levelup.gitconnected.com/how-did-i-build-a-simple-nestjs-app-with-k8s-argocd-and-terraform-part-2-c8fbc7a3ff58?source=rss-6a68697251eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8fbc7a3ff58</guid>
            <category><![CDATA[argo-cd]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[gitops]]></category>
            <dc:creator><![CDATA[tuananhhedspibk]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 17:02:31 GMT</pubDate>
            <atom:updated>2025-06-09T17:02:31.793Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’ll describe how I configured K8s and ArgoCD for the local environment.</p><p>I split my project into “base” and “overlays” subfolders, the main reason for it is <strong>Kustomize</strong></p><blockquote>Kustomize is the tool for customizing and managing manifests without directly editing them.</blockquote><p>For details:</p><ul><li><strong>base/</strong> will be the place for the config foundation.</li><li><strong>overlays/</strong> will be the place for customizing base on environments (staging or production).</li></ul><h3>base/</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*CbAuXdDWlNOP87Fi9edN6w.png" /></figure><p>The base folder contains all the basic configures of</p><ul><li>Deployment</li><li>Service</li><li>Autoscaling</li><li>Migration Job</li></ul><p>Please pay attention to <strong>kustomization.yaml</strong> because we need this file for executing <strong>kustomize build</strong> to generate customized k8s manifests.</p><p>For deployment, why do we need that? We use deployment to manage pods where our server containers will be ran in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*P2D2w04iQrolVX36gaueYQ.png" /></figure><blockquote>In reality, we DO NOT CREATE pod directly; instead, deployment is the best choice.</blockquote><ol><li>Deployment will create ReplicaSet.</li><li>ReplicaSet wil create Pod.</li></ol><h3>Deployment</h3><p>Our config will be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5bd3aeb26c0ee35be2c5b66fef2b534/href">https://medium.com/media/e5bd3aeb26c0ee35be2c5b66fef2b534/href</a></iframe><h4>Selector</h4><p>First, let’s discuss about the <strong>selector</strong>. Put it simply</p><blockquote>Selector is the way to group the resources.</blockquote><p>Here selector.matchLabels will select the pods that have the label app:restful-app</p><h4>Template</h4><p>About the template, this is the configuration for the pod, and in this section, we have to specify a label for the pod, and that label <strong>MUST MATCH</strong> the label defined in the selector.matchLabels</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d7b9d4a0fa8b096348db2b3d06ace16/href">https://medium.com/media/8d7b9d4a0fa8b096348db2b3d06ace16/href</a></iframe><p>In this part, we specify:</p><ul><li><strong>container name</strong></li><li><strong>container image</strong></li><li><strong>resources</strong> that include memory and cpu.</li></ul><p>Pay attention that we should specify requests and limits resources.</p><p><strong>Requests resources</strong> is</p><blockquote>The minimum amount of resources Kubernetes will allocate to a container when the container is running.</blockquote><p><strong>Limits resources</strong> is</p><blockquote>The maximum amount of resources that the container can use.</blockquote><p>The unit of</p><ul><li>Memory is “Mi” equal to “MiB RAM”</li><li>CPU is “core”</li></ul><p>In my project, I specified</p><ul><li>memory: 256Mi ~ 256 MiB RAM</li><li>cpu: 250m ~ 250mili core ~ 0.25 core</li></ul><p>And I specified the <strong>container port</strong> is 3000 too.</p><h3>Service</h3><p>Why do we need Service here? The answer is really simple: Pod does not have any IP addresses to access, so <strong>Service will allocate an IP address for Pod to access</strong>.</p><p>Like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ElU6OCVPaohdYu9xgJSAWg.png" /></figure><blockquote>We will access to server via Service instead of connecting directly to Pod</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87c7e1e0d9f8bf5ee098b9c0e32a115e/href">https://medium.com/media/87c7e1e0d9f8bf5ee098b9c0e32a115e/href</a></iframe><p>Really simple, our service has:</p><ul><li><strong>Expose port 80</strong> to outside and <strong>Connect to port 3000</strong> of the Pod.</li><li><strong>Service type</strong> here is ClusterIP — Public service by IP address of the cluster.</li></ul><h3>HPA (Horizontal Pod Autoscaler)</h3><blockquote>With HPA we can automatically increase or decrease the number of pods.</blockquote><p>Basically, HPA will adjust the number of pods base on:</p><ul><li>CPU</li><li>Memory</li><li>Custom metric</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23bc1365340336cc8f9e2f8707e1fd66/href">https://medium.com/media/23bc1365340336cc8f9e2f8707e1fd66/href</a></iframe><p>With this setup, we will have:</p><ul><li>Minimum 2 Pods.</li><li>Maximum 5 Pods.</li><li>The number of pods will be changed based on CPU, when <strong>averageUtilization</strong> becomes 70%, HPA will increase the number of pods.</li></ul><h3>Migration</h3><p>Like I said in section <strong>k8s project structure</strong> of <a href="https://medium.com/gitconnected/how-did-i-build-a-simple-nestjs-app-with-k8s-argocd-and-terraform-part-1-afe871534acb">Part 1</a>, we have two flows:</p><ul><li>Server app flow</li><li>Migration flow</li></ul><p>In this section, I will tell you about the migration flow</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1c60915766553aeb6c1be9772bc1b88/href">https://medium.com/media/c1c60915766553aeb6c1be9772bc1b88/href</a></iframe><p>It’s just a job, <strong>ensures</strong> that one or more pods run to <strong>completion</strong>. Inside of it, we have a docker container to execute the job logic.</p><p>The backoffLimit: 1 specifies that, Job can be <strong>retried one time only</strong> if it failed.</p><p>OK, that’s all about the base, now let’s move to kustomize.</p><h3>Kustomize</h3><blockquote>Kustomize is the tool that allow us to custom the base Kubernetes manifiests</blockquote><p>For example, we have a <strong>base —</strong> fundamental configure, with kustomize we can create another “version”, maybe for <strong>staging</strong> environment or <strong>production</strong> environment.</p><p>For using kustomize, we must have the <strong>kustomization.yaml</strong> file for base and custom environment like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zgba5ASF4_pVYzF1vxWtVw.png" /></figure><p>Our base <strong>kustomization.yaml</strong> will be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c4d2f6743b1f7cb9a0b9cd971e0e2f1/href">https://medium.com/media/2c4d2f6743b1f7cb9a0b9cd971e0e2f1/href</a></iframe><p>For overlays environment, instead of resources, we will use the keyword “patches”, which means:</p><blockquote>We will overwrite the existing base configure</blockquote><p>Our staging <strong>kustomization.yaml</strong> will be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e35ef224c244dbe819b58a61b620bcb/href">https://medium.com/media/6e35ef224c244dbe819b58a61b620bcb/href</a></iframe><p>In this project, I have created three environments:</p><ul><li>dev (run at local PC)</li><li>stg</li><li>prod</li></ul><blockquote>stg and prod are basically the same, they just have different names only (lol)</blockquote><h3>Dev Environment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*O7touT8LToHgvnLUrPKmZw.png" /></figure><p>Let’s me introduce each file one by one</p><h4>patch-*</h4><p>We have:</p><ul><li>patch-deployment.yaml</li><li>patch-hpa.yaml</li><li>patch-migration.yaml</li></ul><p>They are the overwrite versions of</p><ul><li>base/deployment.yaml</li><li>base/hpa.yaml</li><li>base/migration.yaml</li></ul><p>This is the base/deployment.yaml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d7b9d4a0fa8b096348db2b3d06ace16/href">https://medium.com/media/8d7b9d4a0fa8b096348db2b3d06ace16/href</a></iframe><p>This is the patch-deployment.yaml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8219d767b92ca5b0a0ab0ff8f66b5596/href">https://medium.com/media/8219d767b92ca5b0a0ab0ff8f66b5596/href</a></iframe><p>But, what are the differences ?</p><p>In the “base version”, I specified:</p><ul><li>container name</li><li>container image</li><li>resources (request &amp; limit)</li></ul><p>But in the “patch-version”, I specified:</p><ul><li><strong>command to run the container.</strong></li><li>resources (request &amp; limit) but <strong>MORE THAN THE BASE VERSION</strong>.</li></ul><blockquote>So you can see that the “patch-version” provides the <strong>operation solution</strong> for us instead of <strong>the skeleton</strong> only like “base-version”</blockquote><p>The same with patch-migration.yaml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb079a5b9a596a29c2a91c57c2f49cc6/href">https://medium.com/media/fb079a5b9a596a29c2a91c57c2f49cc6/href</a></iframe><p>In here, I set the command [“npm”, “run”, “migration:run”] to run the migration job.</p><h4>db-*</h4><p>This is for our database, I use StatefulSet &amp; PersistentVolumeClaim for the database.</p><p>The PersistentVolumeClaim:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e815d098d086fa882fd886475fa37b1/href">https://medium.com/media/0e815d098d086fa882fd886475fa37b1/href</a></iframe><p>The main purpose of PersistentVolumeClaim is requires a portion of memory to store the data.</p><p>In my configure, I required “256Mi” of memory.</p><p>The StatefulSet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/404e75b3e88361aba4e9cf64e70f38fc/href">https://medium.com/media/404e75b3e88361aba4e9cf64e70f38fc/href</a></iframe><p>StatefulSet is</p><blockquote>Workload API object that can be used for stable storage</blockquote><p>In here, I specified the image name postgres:17.4 and</p><ul><li>Database name</li><li>Database user</li><li>Database password</li></ul><p>and <strong>we have to mount our StatefulSet with the PersistentVolumeClaim</strong> that is created before. You can imagine like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_KVMDjNroZrezsU5NB0E6w.png" /></figure><h4>kustomization.yaml</h4><p>In kustomization.yaml file, we do not set resource or patches only, but also we can set configMapGenerator like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09290e05fe559b84a8c096b317774b3a/href">https://medium.com/media/09290e05fe559b84a8c096b317774b3a/href</a></iframe><p>Put it simply, configMapGenerator is:</p><blockquote>Used to generate ConfigMap from literal key-value pairs or from file</blockquote><p>In my project, I have created a config.env file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ce0cc4ca9077ab7eb4761d196400de7/href">https://medium.com/media/4ce0cc4ca9077ab7eb4761d196400de7/href</a></iframe><p>Our flow will be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RNNcn5gI-1b4pn5pvxJgbw.png" /></figure><p>And you can see in patch-migration, we can use configMap <strong>for setting environment variables for application</strong> with envFrom &amp; configMapRef</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb079a5b9a596a29c2a91c57c2f49cc6/href">https://medium.com/media/fb079a5b9a596a29c2a91c57c2f49cc6/href</a></iframe><h4>argocd.yaml</h4><p>What is ArgoCD ?</p><blockquote>GitOps, continuous delivery tool for Kubernetes</blockquote><p>With ArgoCD, we could <strong>use Github repository</strong> like <strong>the source of truth</strong> for <strong>defining desired application state.</strong></p><p>Application deployment can be tracked by:</p><ul><li>Branches update.</li><li>Tags update</li><li>Git commit</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*HLCFTXD5HESekKWbrW9NEg.png" /></figure><p>For someone who doesn’t know about GitOps</p><blockquote>GitOps is the DevOps practice that uses Git as the single source of truth to manage infrastructure and application configuration.</blockquote><p>Our argocd.yaml will be</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c32c010d7fc0c2fddd71208f3dd3a034/href">https://medium.com/media/c32c010d7fc0c2fddd71208f3dd3a034/href</a></iframe><p>The most important thing here is the source and repoURL because with those keywords we can specify the <strong>single source of truth</strong> for ArgoCD to define the desired state of the application.</p><p>Alright, let’s run our infrastructure in the local environment.</p><p>Requirement before running, your PC must have:</p><ul><li>kubectl (k8s command)</li><li>argocd</li></ul><p><strong>Step 1</strong>: We run the below command to get argocd password.</p><pre>$kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath=&quot;{.data.password}&quot; | base64 -d</pre><p><strong>Step 2</strong>: Login to ArgoCD by cli with the password that got in step 1.</p><pre>$argocd login localhost:8080 - username admin - password &lt;password&gt;</pre><p><strong>Step 3</strong>: Create the app by the below command</p><pre>$argocd app create restful-app \<br>--repo &lt;your_github_repo_url&gt;\<br>--path &lt;path_to_overlays&gt; \<br>--dest-server https://kubernetes.default.svc \<br>--dest-namespace default</pre><p><strong>Step 4</strong>: Don’t forget to forward ports of</p><ul><li>ArgoCD Service</li><li>Database Service</li><li>Application Service</li></ul><p>to host port</p><pre># App Service<br>$kubectl port-forward svc/restful-app &lt;host_port&gt;:&lt;svc_port&gt;<br><br># StatefulSet (DB) Service<br>$kubectl port-forward svc/postgres &lt;host_port&gt;:&lt;svc_port&gt;<br><br># ArgoCD Service<br>$kubectl port-forward svc/argocd-server -n argocd &lt;host_port&gt;:443</pre><p>Finally we can get:</p><ul><li>ArgoCD UI</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*03JTQxVFAW73Fv9XVamvpQ.png" /></figure><ul><li>Application</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GO81FZ5J_L9SoNNMp1aq_Q.png" /></figure><h3>Summary</h3><p>Alright, that is for part 2. In this part, I have shown you:</p><ul><li>The folder structure includes <strong>base</strong> and <strong>overlays</strong></li><li>The fundamental configurations include <strong>deployment</strong>, <strong>service</strong>, <strong>hpa</strong>, <strong>job</strong></li><li>The <strong>development overlays</strong> and how to run it.</li></ul><p>I hope that this part will give you a basic understanding of the k8s (how to configure and how to run it with ArgoCD) in the local environment.</p><p>Bye for now, and I’ll see you in the next article.</p><p>Happy coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8fbc7a3ff58" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-did-i-build-a-simple-nestjs-app-with-k8s-argocd-and-terraform-part-2-c8fbc7a3ff58">How did I build a simple NestJS app with k8s, ArgoCD, and terraform (Part 2)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How did I build a simple NestJS app with k8s, ArgoCD, and terraform (Part 1)]]></title>
            <link>https://levelup.gitconnected.com/how-did-i-build-a-simple-nestjs-app-with-k8s-argocd-and-terraform-part-1-afe871534acb?source=rss-6a68697251eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/afe871534acb</guid>
            <category><![CDATA[argo-cd]]></category>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[tuananhhedspibk]]></dc:creator>
            <pubDate>Sun, 01 Jun 2025 22:36:51 GMT</pubDate>
            <atom:updated>2025-06-01T22:36:51.089Z</atom:updated>
            <content:encoded><![CDATA[<p>I have recently had a chance to delve into k8s in my work, so today, I will share some of my knowledge and experiences with k8s by building a simple web application through this series of articles.</p><h3>App Overview</h3><p>It&#39;s just a simple server application with Swagger UI like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fWEHLyWOkVcp_YaxnlnAOg.png" /></figure><p>With:</p><ul><li>Authentication (sign-up, sign-in) APIs.</li><li>GET user data API.</li><li>UPDATE user data API.</li><li>DELETE user data API.</li></ul><p>You can access it via this link: <a href="http://nestjs.restful-app.com/swagger">http://nestjs.restful-app.com/swagger</a> (Sorry, I don’t have enough time to set up HTTPS 😂).</p><p>The architecture of this project will be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vlg8fXbWmSWwWvaJD_LfAg.png" /></figure><p>Putting it simply:</p><ul><li>Using <strong>GitHub actions</strong> and <strong>ArgoCD</strong> for <strong>GitOps</strong>.</li><li>Using <strong>NestJS</strong> to build the <strong>server application</strong>.</li><li>Using <strong>Terraform</strong> to make the <strong>AWS infrastructure resources</strong>.</li></ul><p>Alright, that’s the overview. Let’s dive into it in more detail.</p><h3>About the server app</h3><p>As I said before, I used <strong>NestJS to build the server application</strong>.</p><p>You can read the complete source code and its architecture here: <a href="https://github.com/tuananhhedspibk/restful-app">https://github.com/tuananhhedspibk/restful-app</a></p><p>In this article series, I want to focus on setting up ArgoCD with K8s so that I can simplify the server app.</p><p>I built it based on <strong>DDD (Domain Driven Design)</strong> principles (you can see the image below for more details)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*W27hoU2r-1JRyIpD6tI0Eg.png" /></figure><blockquote>If you want to know more about DDD, please visit <a href="https://medium.com/@tuananhhedspibk/how-did-i-build-an-api-with-ddd-part-1-c95e137ba147">this article</a>.</blockquote><p>The application has <strong>four layers</strong>:</p><ul><li><strong>Domain</strong> Layer.</li><li><strong>Application</strong> Layer.</li><li><strong>Presentation</strong> Layer.</li><li><strong>Infrastructure</strong> Layer.</li></ul><p>The red arrows show the <strong>layer dependencies</strong>:</p><blockquote>The <strong>outer layer</strong> must <strong>depend</strong> on the <strong>inner layer</strong>, but the <strong>opposite is false</strong>.</blockquote><p>With the core being <strong>User Domain </strong>in the<strong> </strong><strong>Domain Layer, </strong>you can see the User Aggregate:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/470a341fca76b2af18b1a9d839b5da8c/href">https://medium.com/media/470a341fca76b2af18b1a9d839b5da8c/href</a></iframe><p>The user aggregate (can be imagined like the person in real life) that has:</p><ul><li>Properties.</li><li>Actions (Methods).</li></ul><p>For the <strong>Application Layer, </strong>I split into two parts:</p><ol><li><strong>Command</strong>: for handling CRUD data, for example:</li></ol><ul><li>Create User (Signup).</li><li>Update User.</li><li>Delete User.</li></ul><p><strong>2. Query</strong>: for handling of getting data, for example:</p><ul><li>Get User Information.</li></ul><blockquote>This layer will <strong>handle the main logic for each API</strong> of the server app.</blockquote><p>You can see more details about it in</p><ul><li><strong>For command: </strong><a href="https://github.com/tuananhhedspibk/restful-app/tree/main/src/users/application/command">https://github.com/tuananhhedspibk/restful-app/tree/main/src/users/application/command</a></li><li><strong>For query: </strong><a href="https://github.com/tuananhhedspibk/restful-app/tree/main/src/users/application/query">https://github.com/tuananhhedspibk/restful-app/tree/main/src/users/application/query</a></li></ul><p>The <strong>Presentation layer</strong> will hold the <strong>API endpoints</strong>:</p><ul><li>/v1/user/signup</li><li>/v1/user/signin</li><li>…</li></ul><p>You can read <a href="https://github.com/tuananhhedspibk/restful-app/blob/main/src/users/presentation/index.controller.ts">here</a> for more details.</p><p>The last layer — <strong>Infrastructure Layer</strong></p><p>This is the layer that handles communication with external systems like:</p><ul><li>External API.</li><li>Database.</li><li>…</li></ul><p>For example — when finding user by id we must access to the database. The repository will:</p><ol><li>Access to the database to collect data.</li><li>Create an aggregate and return it.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce58f2de3863d64af7ed9446abf6a099/href">https://medium.com/media/ce58f2de3863d64af7ed9446abf6a099/href</a></iframe><p>OK, that’s overview about the server application, now let’s move to the infrastructure (AWS).</p><h3>About the infrastructure (AWS)</h3><h3>Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7RyBwwMalB7Rb1JE20sqdA.png" /></figure><p>The above image is an overview of the infrastructure. I’ll split it into three main parts:</p><ul><li><strong>Networking</strong>.</li><li><strong>RDB</strong>.</li><li><strong>Server App</strong>.</li></ul><p>In this article, instead of explaining the definitions of the AWS resources (VPC, subnets, …) in detail, I will show you how I am using them for my project.</p><h4>Networking</h4><p>This is the place for configuring:</p><ul><li>VPC.</li><li>Public / Private subnets.</li><li>Internet / NAT gateway.</li></ul><p>You can imagine these resources like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*xFvp85ohI8vS_tIAsdBaag.png" /></figure><p>The <strong>VPC</strong> is the place that we will place the whole app and resources.</p><p><strong>Public subnet</strong> — like its name, because it’s public so we’ll use this subnet for public connecting like:</p><ul><li>API connecting from client.</li><li>SSH connecting from developer to the database.</li></ul><p><strong>Private subnet</strong>, this subnet will be a place where to put:</p><ul><li>API instances</li><li>Database instances</li><li>…</li></ul><p>things that we <strong>don’t want to public</strong> to the global internet.</p><p>The <strong>NAT Gateway</strong> — this is the solution for:</p><blockquote>Private Subnet to connect to the global internet, while the global internet CAN NOT go inside the Private Subnet</blockquote><h3>RDB</h3><p>This is for our database, because I’m using the PostgreSQL for the database at the local environment so I’ll use <strong>aurora-postgresql</strong> of AWS for the database on the cloud environment.</p><p>Because this is the database so we <strong>HAVE TO PUT IT INTO THE PRIVATE SUBNET</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*StcB6k_12spPqvqRBNFtEA.png" /></figure><p>For the configuring, you can see <a href="https://github.com/tuananhhedspibk/restful-app-infra/blob/main/modules/database/main.tf">here</a> for more details.</p><p>But sometimes the developers need to go inside the database to see the data, so we must create a tunnel for them. My thinking is</p><ol><li>Create an SSH Proxy instance that stands in front of the database.</li><li>Create users inside the Proxy instance for developers.</li><li>The developers will use SSH to connect to the database via SSH Proxy.</li></ol><p>Like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZCReCzemh95i2bnvnKnOGQ.png" /></figure><p>I want you to look at the red-circled part in the above image.</p><ul><li>The Proxy is just an EC2 instance.</li><li>RDS Security group must accept SSH connection from the Proxy instance.</li></ul><p>The security group config will be like:</p><h4>For Proxy</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b4306a2457a20f4e9162193942702f5/href">https://medium.com/media/4b4306a2457a20f4e9162193942702f5/href</a></iframe><blockquote>The ingress setting with port 22 is for SSH connection</blockquote><h4>For RDS</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94173f7cdd02a2530cab80e88a5ce105/href">https://medium.com/media/94173f7cdd02a2530cab80e88a5ce105/href</a></iframe><h3>Server App</h3><p>The title is “Server App” but in this part I’m gonna show you the settings about:</p><ul><li>Load balancer.</li><li>EKS.</li><li>ECR.</li></ul><h4>About the <strong>Load balancer</strong></h4><p>This is the “Gate” for clients connecting to our server app. In this project, I’ll use an <strong>Application Load Balancer</strong> because I want the load balancer to <strong>not only receive the request</strong> but also <strong>act as a reverse proxy</strong> to distribute it, instead of forwarding it directly without any handling, like a <strong>Network Load Balancer</strong>.</p><p>You can see <a href="https://awstip.com/from-aws-alb-to-aws-nlb-1ef148001fa6">this article</a> for more details about the difference between <strong>Application Load Balancer</strong> and <strong>Network Load Balancer</strong></p><h4>The <strong>EKS</strong></h4><blockquote>The <strong>managed Kubernetes service</strong> that offered by AWS will manage our server instances as pods.</blockquote><p>I’ll put it simply like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SMfM6FVHgBvsotWy3rB8Fg.png" /></figure><p>The EKS manages 2 pods. Inside those pods will be the <strong>SERVER APP DOCKER CONTAINER</strong>, which will connect directly to the database.</p><p>In the next part, I’ll tell you how to configure those pods in more detail in the k8s and ArgoCD config.</p><p>You can see the EKS terraform setting <a href="https://github.com/tuananhhedspibk/restful-app-infra/blob/main/modules/eks/main.tf">here</a>.</p><h4><strong>The ECR</strong></h4><blockquote>ECR is just a <strong>container managed service</strong> offered by AWS.</blockquote><p>I’m using it to manage my app docker image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ynraSaAJ43nySxyT6yoT-g.png" /></figure><h3>Source code</h3><p>The full source code can be seen <a href="https://github.com/tuananhhedspibk/restful-app-infra/tree/main">here</a></p><p>Put it simply about the source code folders:</p><ul><li><strong>modules</strong>: This is where I’ll put the AWS resources (VPC, subnet, RDS, EKS, …) configured. It can be compared to the base environment.</li><li><strong>environments</strong>: Like its name, this is the folder where I’ll create the separate environments (staging, production).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*dskM3CEh3anrxY4t8XBH-g.png" /></figure><p>For more details about the way to execute and apply the code, please read the <a href="https://github.com/tuananhhedspibk/restful-app-infra/blob/main/README.md">README</a> file.</p><h3>About the k8s + ArgoCD</h3><p>This is the main of this series. In this part, I’ll tell you about:</p><ul><li>The k8s project structure.</li><li>How did I use ArgoCD.</li></ul><h3>k8s project structure</h3><p>In this article, I won’t explain the definition of Pods or Replica… instead, I’m going to show you how I used them to set up my project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vr2j-sQXgAUJ7ueSq9-osg.png" /></figure><p>Look at the above image, you can see two flows:</p><ul><li>Server App flow.</li><li>Migration flow.</li></ul><h4>Server App flow</h4><p>For this flow, I used a <strong>Deployment</strong> to manage the <strong>ReplicaSet</strong> that has two <strong>Pods</strong> with one docker container for the server app in each.</p><blockquote>Because the Deployment does not have any IPs address so for Pod accessing I have to use the Service.</blockquote><p>With Service instead of accessing directly to Pods (Pods’ IP address will be changed when Pods change), accessing the Service is enough.</p><h4>Migration Flow</h4><p>For this flow, I used a Job — with job we can execute a task (start -&gt; end) like database migration.</p><h3>ArgoCD</h3><h4>GitOps</h4><p>According to <a href="https://www.google.co.jp/books/edition/GitOps_Cookbook/TOqiEAAAQBAJ?hl=en&amp;gbpv=1&amp;printsec=frontcover">GitOps CookBook</a></p><blockquote>Is a methodology that uses Git repository will be considered as a Single Source Of Truth for delivering infrastructure as code (IaC).</blockquote><p>In my application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ahH4Zk1OaPVIQ9ShZ7CTxw.png" /></figure><p><strong>ArgoCD</strong> will track the newest state of the k8s project and sync (automatically or manually) the IaC, like the above image.</p><p>I&#39;ll tell you more about it in the next article.</p><h3>Summary</h3><p>Alright, that’s all about the overview. In the next part of this series, I’m gonna show you more details about how I set up and configured the k8s and ArgoCD for my application.</p><p>Bye for now and happing coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afe871534acb" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-did-i-build-a-simple-nestjs-app-with-k8s-argocd-and-terraform-part-1-afe871534acb">How did I build a simple NestJS app with k8s, ArgoCD, and terraform (Part 1)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design And Building A Logging System]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://levelup.gitconnected.com/design-and-building-a-logging-system-fd5dcad110ed?source=rss-6a68697251eb------2"><img src="https://cdn-images-1.medium.com/max/600/1*l101EItRXguolpzSq8kM5Q.jpeg" width="600"></a></p><p class="medium-feed-snippet">If you are a programmer, checking logs when debugging is not strange. We can not identify the file facing an error without logs</p><p class="medium-feed-link"><a href="https://levelup.gitconnected.com/design-and-building-a-logging-system-fd5dcad110ed?source=rss-6a68697251eb------2">Continue reading on Level Up Coding »</a></p></div>]]></description>
            <link>https://levelup.gitconnected.com/design-and-building-a-logging-system-fd5dcad110ed?source=rss-6a68697251eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd5dcad110ed</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[logging]]></category>
            <dc:creator><![CDATA[tuananhhedspibk]]></dc:creator>
            <pubDate>Thu, 19 Sep 2024 21:02:16 GMT</pubDate>
            <atom:updated>2024-09-19T21:02:16.297Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Build error-handling classes for DDD and Clean Architecture with Typescript]]></title>
            <link>https://levelup.gitconnected.com/build-error-handling-classes-for-ddd-and-clean-architecture-with-typescript-2cbea1fb8893?source=rss-6a68697251eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cbea1fb8893</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[tuananhhedspibk]]></dc:creator>
            <pubDate>Sun, 18 Aug 2024 16:51:23 GMT</pubDate>
            <atom:updated>2024-08-18T16:51:23.021Z</atom:updated>
            <content:encoded><![CDATA[<h3>The need to have error-handling classes</h3><p>Besides ensuring that the business logic is executed correctly, we must ensure that our code covers as many errors as possible when building software or web applications. Let’s talk about the error. Usually, we have two types of errors:</p><ul><li>Errors that occur by user actions (<strong>4xx</strong> error)</li><li>Errors that occur by framework or our “bad logic code” (<strong>5xx</strong> error)</li></ul><p>Our ultimate aim is to create software that can serve users anytime, anyplace, and provide them with the best experiences. To achieve this, we must handle the two types of errors that can occur, ensuring that our users’ experience is always our top priority.</p><p>In this article, I will show how it designed and built error-handling classes for a DDD project. Let’s dive in.</p><h3>Build error-handling classes for DDD and Clean Architecture</h3><h4>Design and coding</h4><h4>A little bit about DDD</h4><p>Let’s talk about DDD and Clean Architecture. Unlike traditional architecture like MVC or MVVM, DDD &amp; Clean Architecture make the business logic the center of the entire application. We will separate our application into layers, each with its mission. Here, we will have four layers:</p><ol><li><strong>Domain layer</strong>: this is the heart of the entire application; it includes the central business logic.</li><li><strong>Use-case layer</strong>: this layer includes services and features.</li><li><strong>Presentation layer</strong>: this layer is the same as the controller layer of MVC architecture.</li><li><strong>Infrastructure layer</strong>: this outage layer has the responsibility to contact external API or database.</li></ol><p>And pay attention that the inside layer can not be dependent on the outer layer — we call this the <strong><em>Dependencies Rules .</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*W27hoU2r-1JRyIpD6tI0Eg.png" /></figure><p>In the above picture, three red arrows illustrate the <strong><em>Dependencies Rules:</em></strong> The use-case layer must depend on the domain layer, and the Presentation layer must depend on the Use-case layer.</p><h4>Base classes</h4><p>OK, that is enough for DDD. Now, we will move on to our main topic <strong>Error-Handling Classes</strong>. I separate my application into four layers:</p><ul><li>Domain layer</li><li>Use-case layer</li><li>Presentation layer</li><li>Infrastructure layer</li></ul><p>As a result of this division, I’ve created four error classes, each corresponding to one of the four layers. This is to ensure that we have a structured approach to handling errors across the application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb00122b1daaa2e9fcb28f2fd5eb8af2/href">https://medium.com/media/bb00122b1daaa2e9fcb28f2fd5eb8af2/href</a></iframe><p>Let’s break down the above code snippet. First, I have defined the base class <strong>BaseError</strong> — it is just an abstract class that extends from the <strong>Error</strong> interface of Typescript.</p><p>Like I said above</p><blockquote>I will define four error classes correspond to four layers</blockquote><p>I have defined four error class:</p><ul><li><strong>DomainError</strong> for the <strong>Domain layer</strong>.</li><li><strong>UsecaseError</strong> for the <strong>Use-case layer</strong>.</li><li><strong>PresentationError</strong> for the <strong>Presentation layer</strong>.</li><li><strong>InfrastructureError</strong> for the <strong>I</strong><strong>nfrastructure layer</strong>.</li></ul><p>When checking log or reading errors, we usually care about the following:</p><ul><li>Error code</li><li>Error message</li></ul><p>So I’ve decided to define two properties, <strong>code</strong> and <strong>message</strong>, for each of the error classes, but the error classes I’ve created above are extended from the <strong>Error</strong> interface of Typescript.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f514d0f2c560490d098c3cc4a2534ad/href">https://medium.com/media/2f514d0f2c560490d098c3cc4a2534ad/href</a></iframe><p>Because my four classes have a <strong>message</strong> property, I don’t need to define it inside the class. But I want my error object to provide more information than only <strong>code</strong> and <strong>message</strong>, so I decided to add the <strong>info</strong> property to each class like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2956f9a15e11fbd6534e24db95b054f/href">https://medium.com/media/b2956f9a15e11fbd6534e24db95b054f/href</a></iframe><p>Because I want the info property to store various information types, I have defined it in a free style — just an object with a string key and a value that can be any data type.</p><h4>Error code</h4><p>Now is <strong>Error Code</strong>. I want to tell you the property <strong>code</strong> of the above error classes.</p><p>Well, we can use the type <strong>string</strong>, but I want to have something fixed, something more structured, so I’ve decided to define <strong>Error Enum</strong>. With typescript, you can define <strong>enum</strong> like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73b687d7a5987dab5edfdfb74e6478e2/href">https://medium.com/media/73b687d7a5987dab5edfdfb74e6478e2/href</a></iframe><p>However, have some reasons for not choosing <strong>Enum</strong>. Instead of that, I am going to define a constant like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c087058070bb2a74691423d3f729d4b5/href">https://medium.com/media/c087058070bb2a74691423d3f729d4b5/href</a></iframe><p>The main reason is that I want to have an immutable literal error code. Another article will explain the difference between <strong>as const</strong> and <strong>enum</strong> in more detail.</p><p>Back to error classes, I am going to define error code constants like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/927078051f0c2195f44d1442b566c3bb/href">https://medium.com/media/927078051f0c2195f44d1442b566c3bb/href</a></iframe><p>By doing this I’ll have a type <strong>DomainErrorCode</strong> like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/695ea094d41e91036e70642212d72ec8/href">https://medium.com/media/695ea094d41e91036e70642212d72ec8/href</a></iframe><p>I will do the same thing with the <strong>UsecaseErrorCode</strong>, <strong>PresentationErrorCode</strong>, and <strong>InfrastructureErrorCode</strong> data types which correspond to the <strong>Usecase layer</strong>, <strong>Presentation layer</strong>, and <strong>Infrastructure layer</strong>.</p><p>Now I want to show you one more thing: <strong>ErrorDetailCode</strong>. You can ask: “What is this?” simply it’s just an</p><blockquote>Error code that gives you more detail about where the error is occurring or what business logic or what API is getting an error</blockquote><p>The reason I want to define it is that <strong>ErrorCode</strong> is just a common code for <strong>Bad Request Error — 400</strong>, <strong>Not Found Error — 404</strong>, or <strong>Internal Server Error — 500</strong>. With <strong>ErrorCode</strong> only, we can not know exactly where the error is occurring, what API is involved, or what business logic is facing the error.</p><p>I’ll do the same thing to define the <strong>ErrorDetailCode</strong> type as I did with <strong>ErrorCode</strong>, for example, for the domain layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c973521114017ac824a1653b94d4974/href">https://medium.com/media/6c973521114017ac824a1653b94d4974/href</a></iframe><p>And of course, I’ll have the same thing for <strong>UsecaseErrorDetailCode</strong>, <strong>PresentationErrorDetailCode</strong>, <strong>InfrastructureErrorDetailCode</strong>.</p><p>Finally, we will have the entire ErrorCode class like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f113b05e80146bcbc83c78022de99ce/href">https://medium.com/media/7f113b05e80146bcbc83c78022de99ce/href</a></iframe><p>OK, that is something about designing and some snippet codes about the <strong>ErrorCode</strong> class. In the next section, I’ll show you how to use it.</p><h3>Applying</h3><p>Let’s take an example of a web application’s signup feature. I’ve used the DDD for my web application so the signup logic will go to the use-case layer.</p><p>You can see more details <a href="https://github.com/tuananhhedspibk/NewAnigram-BE-DDD/blob/main/src/usecase/authentication/signup/index.ts#L78">here</a>.</p><p>I’ll take a code snippet to explain.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e246dc23136402e92d1d795721d62f45/href">https://medium.com/media/e246dc23136402e92d1d795721d62f45/href</a></iframe><p>You can see that after receiving the email and password parameters, I will check their lengths; if one of those is equal to 0, I’m going to throw a <strong>UsecaseError</strong> to notice that the email or password has a problem, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMfvXBcUhlKUGmefafa13w.png" /></figure><p>In the above picture, all of this information:</p><ul><li>Error Type</li><li>Error Message</li><li>Error Code</li><li>Error Detail Code</li></ul><p>are shown.</p><p>Just throwing an error with an error message is enough. Exactly, I felt the same thing before, but it has some cons as the following:</p><ul><li>The <strong>Error Message</strong> can be too long for the client’s screen size, so the user can not read the entire message; instead of using <strong>Error Message</strong>, the client can use <strong>Error Code</strong> or <strong>Error Detail Code</strong> to map with the <strong>Error Message</strong> that fits the user’s screen size.</li><li><strong>Error Code</strong> and <strong>Error Detail Code</strong> make our error more specific, making our debugging process easier.</li></ul><p>That is, you can think that defining an error class system is too “engineering” and does not provide any pros to the business. OK, you are not wrong, but if you want your system to become <strong><em>maintainable and easy to recover</em></strong>, I highly recommend defining your system’s own error classes.</p><p>Thanks for reading; I’ll see you in the next blog.</p><p>Happy coding =)))</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cbea1fb8893" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/build-error-handling-classes-for-ddd-and-clean-architecture-with-typescript-2cbea1fb8893">Build error-handling classes for DDD and Clean Architecture with Typescript</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How did I get the Terraform Associate 003 Certificate]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">What is terraform-associate 003 ceritificate&#xA0;?</p><p class="medium-feed-link"><a href="https://medium.com/@tuananhhedspibk/how-did-i-get-the-terraform-associate-003-certificate-dfb1c3c2c6ec?source=rss-6a68697251eb------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@tuananhhedspibk/how-did-i-get-the-terraform-associate-003-certificate-dfb1c3c2c6ec?source=rss-6a68697251eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfb1c3c2c6ec</guid>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[tuananhhedspibk]]></dc:creator>
            <pubDate>Wed, 14 Aug 2024 10:15:27 GMT</pubDate>
            <atom:updated>2024-08-14T10:15:54.720Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[The interaction between micro-services using AWS ECS Run Task]]></title>
            <link>https://awstip.com/the-interaction-between-micro-services-using-aws-ecs-run-task-606740b7eb10?source=rss-6a68697251eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/606740b7eb10</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[ecs-fargate]]></category>
            <dc:creator><![CDATA[tuananhhedspibk]]></dc:creator>
            <pubDate>Sat, 16 Mar 2024 08:04:03 GMT</pubDate>
            <atom:updated>2024-05-19T13:25:23.765Z</atom:updated>
            <content:encoded><![CDATA[<h3>The interaction between micro-services</h3><p>The interactions between services occur frequently in a system that has multiple services. Those interactions can be executed by:</p><ul><li>API calling: this is how we call API by HTTP or RPC.</li><li>Event trigger: Service A will “trigger” service B by emitting one or more events.</li></ul><p>About API calls, this is the popular method, so I’ll not write about it in this article. Instead, I want to dive deep into the second method, event trigger.</p><h3>SAGA pattern</h3><p>Since each service has its database, when service A “calls” service B, it leads to executing transactions on different databases (note that we CANNOT implement ACID transactions across multiple databases).</p><p>This necessitates a solution to ensure “consistency” among “the databases.”</p><p>The solution here is SAGA, which can be understood simply as a sequence of local transactions (transactions belonging to a single database).</p><blockquote>Each local transaction will update the database it belongs to, while also publishing a message or event to trigger the local transaction of the next service in the business logic chain.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yAAnuq-Xt_K881ewwGTzsA.png" /></figure><p>There are 2 ways to implement SAGA:</p><ol><li>Choreography: Each local transaction will publish a domain event, which will trigger local transactions in other services (these services themselves will determine whether processing is needed or not).</li><li>Orchestration: Each orchestrator (object) will specifically designate which local transactions will be executed.</li></ol><h3>Choreography-based SAGA</h3><p>I’ll give an example of an e-commerce website with 2 main domains: Order and Customer respectively:</p><ul><li>Business occurs every time a user makes a purchase.</li><li>Business related to customers (users).</li></ul><p>The implementation of the order on the EC website using choreography would be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Px2tLCLTKUtM-TOZQtaiLQ.png" /></figure><p>The implementation of the order on the EC website using choreography would proceed as follows:</p><ol><li>The <strong>Order Service</strong> receives a <strong>POST /orders</strong> request, creating an order with the status <strong>PENDING</strong>.</li><li>Subsequently, it emits an <strong>Order Created event</strong>.</li><li>The <strong>Customer Service</strong> listens to this event and triggers the <strong>reserve credit handler</strong>.</li><li>Then, the <strong>Customer Service</strong> also emits a <strong>Credit Reserved</strong> event.</li><li>The <strong>Order Service</strong> listens to the <strong>Credit Reserved</strong> event and updates the order&#39;s status to either <strong>COMPLETE</strong> or <strong>REJECT</strong>.</li></ol><h3>Orchestration-based SAGA</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmfeVJdTseXelEepMYPeoA.png" /></figure><p>Let me introduce Orchestration-based:</p><ol><li><strong>Order Service</strong> receives <strong>POST /orders</strong> requests and creates a <strong>Create Order</strong> saga orchestration.</li><li>The Saga orchestrator will create an Order that has <strong>PENDING</strong> status.</li><li>After that, send the <strong>Reserver Credit command</strong> to <strong>Customer Service.</strong></li><li>Customer Service will possess the order credit of the user.</li><li>Then, return a. message and specify which saga will be executed on the Order Service side.</li><li>The Saga orchestrator will approve or reject the <strong>Order.</strong></li></ol><h3>Trigger Event</h3><p>After the definitions of the c<strong>horeograph-based saga</strong> and <strong>orchestration-based saga, </strong>despite the way implementing SAGA, we have to think about “Event”.</p><p>The emitted event will be the trigger of everything such as:</p><ul><li>Executing a use-case of the specific service.</li><li>Signaling for another service to execute a specific business task autonomously.</li></ul><p>I’ll tell you more details about SAGA in another article.</p><h3>Design the interacting mechanism</h3><p>Back to the topic “Implementing the interacting mechanism.”</p><p>Firstly I want to talk quickly about “ECS,” basically it’s</p><blockquote>An orchestration service allow us to deploy, manage and scale the containerized apps</blockquote><p>About the life cycle of the ECS application, we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*njZVoHsD4_20PB6jBCAtsA.png" /></figure><ol><li>ECR will store the app&#39;s Docker Image.</li><li>The Task Definition will be built based on the ECR Docker Image. Here, the task definition is the JSON file that includes params and the containers that make up the app. You can understand that task definition just like the app&#39;s blueprint.</li><li>ECS app will be started up based on Task Definition.</li></ol><p>With ECS, we can deploy a server and execute “a task”.</p><p>A task here may be a use case or a batch job.</p><p>Instead of running “permanently” like a server, a task is shut down immediately after it’s completed. This can save us a lot of operating fees.</p><h4>Using Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m3ZoMSD0bUwCfuWNX_U_8Q.png" /></figure><p>Let&#39;s talk about the main components in the image.</p><p>For each service, I’ll create an aws-event-bus for them. aws-event-bus is the service of AWS that allows the client to use tools like:</p><ul><li>aws-cli</li><li>aws-sdk</li></ul><p>to emit one or more events, those events will be received by aws-event-bus</p><p>Of course, each event will have its own “unique characteristic”, which AWS will consider as a “Rule”, leading to the concept associated with that event bus, known as <strong>Event Rule</strong>.</p><p>Each bus will have one or more rules associated with it. When a service emits an event, the service needs to specify clearly which rule this event belongs to.</p><p>Here is the code snippet for using aws-sdk to emit an event to event-bus</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/863e253a7439ffb7d62a50d4ae99701c/href">https://medium.com/media/863e253a7439ffb7d62a50d4ae99701c/href</a></iframe><h3>Implementing</h3><p>In summary, my micro-services in the system interconnect by “emitting events,” as mentioned above.</p><p>However, if we just stop at this general overview, it will be challenging for readers to visualize the mechanism in a specific manner. Therefore, I’d like to delve deeper into the coding aspect in this section.</p><h4>event-bus &amp;&amp; event-rules</h4><p>To implement the event bus and event rules, I’m using aws-cdk (briefly, it’s also an Infrastructure as Code tool provided by AWS).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ASMB1TuUrnFGe16xdU1jrQ.png" /></figure><p>About the structure of event-bus and event-rules, you can see that:</p><ul><li>1 event-bus — n event-rules</li><li>1 stack — n event-buses (Stacks here can be understood as units used to deploy resources defined by aws-cdk)</li></ul><p>Using stacks here helps us group resources into logical units, making resource management clearer and more organized than managing resources in a flat structure.</p><p>With stack, we have:</p><blockquote>stack1<br> → resource[1–1]<br> → resource[1–2]</blockquote><blockquote>stack2<br> → resource[2–1]<br> → resource[2–2]</blockquote><p>Without stack:</p><blockquote>resource[1]<br>resource[2]<br>…<br>resource[n]</blockquote><p>Can you see the “neatness” of using stacks?</p><h4>Coding for stack</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d61e91be70e14598b81eb663542589e/href">https://medium.com/media/1d61e91be70e14598b81eb663542589e/href</a></iframe><h4>Coding for event-bus</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8399931803116eff51225d5b035fb2aa/href">https://medium.com/media/8399931803116eff51225d5b035fb2aa/href</a></iframe><h4>Coding for event-rule</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/736237618f66f8f74b6244ada8f150f9/href">https://medium.com/media/736237618f66f8f74b6244ada8f150f9/href</a></iframe><p>In the code snippet above, readers can observe two additional concepts being used:</p><p>1. State machine<br>2. Step function</p><p>In brief, a state machine is a “workflow” comprising multiple “states” within it.</p><p>Regarding the relationship between event-rule, state-machine, and step-function, you can refer to the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*3TyTZ7cOvnzAnni-NFiUng.png" /></figure><p>As mentioned, the step function will implement (deploy) the state machine.</p><p>The state machine will be attached to the event rule and serve as a processing mechanism triggered when an event is received.</p><p>This is a somewhat complex part, and I hope readers will carefully study the illustrated code snippet above to understand the issue thoroughly.</p><h4>Emit Event</h4><p>In essence, this is the process of a service generating and sending an event.</p><p>Very done using the AWS SDK as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/863e253a7439ffb7d62a50d4ae99701c/href">https://medium.com/media/863e253a7439ffb7d62a50d4ae99701c/href</a></iframe><p>There’s a case study where each service will have its event bus, which makes a lot of sense because</p><blockquote>Services DON’T NEED TO CONCERN THEMSELVES WITH WHERE THE GENERATED EVENT WILL BE SENT. The task of “transporting” this event will be determined by an external library; the service just needs to ensure that it performs its business logic correctly, and that’s enough.</blockquote><h4>Trigger Task</h4><p>This is the main part of this article, following up on the definition of event rule from the previous section. You can see that the event rule is attached to the state machine, which is the processing mechanism triggered when an event is received.</p><blockquote>The task triggering will be handled by the state machine.</blockquote><p>The code snippet for the state machine will be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c838c80dc0eff56ac6e2cd21c9cf1bc/href">https://medium.com/media/9c838c80dc0eff56ac6e2cd21c9cf1bc/href</a></iframe><p>With just 7 lines, the most complex part lies within the setupStateMachineDefinition function. For more details, please proceed to the next section.</p><h4>Local Environment</h4><p>I divided it into two sections, Local Environment and Cloud Environment, because the Cloud environment has already been set up using Terraform.</p><p>This is the local environment structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AmERkoAVVJn7l2SzCDrG-w.png" /></figure><p>As I mentioned in the previous section, after the event is forwarded to the event rule, the processing within the state machine will be triggered (referring to Figure 8 above, processing from step 2 onwards will take effect).</p><p>In step 2, I will create a task definition (which will serve as the blueprint for launching the ECS task).</p><p>This task definition will mount to the source code of the other service (referred to here as service B). This mounting is necessary because later, when the ECS task of service B is activated, it will run as a Docker container, so we need to mount it to the source code of service B.</p><p>After the task definition mounting process is complete, my task definition will be fully defined. At this point, I will proceed to “launch” an ECS task (step 4).</p><p>Once the ECS task is launched, a command will be applied (or in other words, it’s essentially just running a command on the ECS task) to trigger a specific use case on the side of service B.</p><p>The source code is</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a83c4cfe54cbd4a9dbc739def6f0c3ea/href">https://medium.com/media/a83c4cfe54cbd4a9dbc739def6f0c3ea/href</a></iframe><h4>Cloud environment</h4><p>There will be some differences between the AWS Cloud environment and the local environment. The reason is that instead of building a complete flow from scratch using AWS CDK, I use pre-existing resources (VPC, ECS cluster, etc.) in the AWS Cloud environment.</p><p>However, whether in the local environment or the AWS Cloud environment, we still need a task definition. Of course, the task definition has already been predefined in the AWS Cloud environment.</p><p>Naturally, one might think that we can retrieve the pre-defined task definition using AWS CDK and then simply run <strong><em>new EcsRunTask()</em></strong> similar to under the local environment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2500b4aab5bc77259ef33aa0f18fc7b/href">https://medium.com/media/f2500b4aab5bc77259ef33aa0f18fc7b/href</a></iframe><p>Indeed, there’s a “type conflict” here. The <strong><em>fromTaskDefinitionArn</em></strong> method returns an <strong><em>ITaskDefinition</em></strong> type, while <strong><em>EcsRunTask</em></strong> requires a <strong><em>TaskDefinition</em></strong> type.</p><p>Therefore, here we have to use a <strong>CustomState</strong> — <a href="https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_stepfunctions.CustomState.html">https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_stepfunctions.CustomState.html</a></p><p>This is a way for us to “redefine” the State within the state machine, in other words, it’s essentially us redefining this follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*Wk0KF5tJKuXQ_3zgxUeKFg.png" /></figure><p>by ASL (Amazon State Language) is a JSON-based language for defining states within a state machine. In short, it’s a language used to define the structure and behavior of states in a state machine. More details can be found at: <a href="https://docs.aws.amazon.com/step-functions/latest/dg/concepts-amazon-states-language.html">https://docs.aws.amazon.com/step-functions/latest/dg/concepts-amazon-states-language.html</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2545a0fc451617930a3fd014fcfa0ee8/href">https://medium.com/media/2545a0fc451617930a3fd014fcfa0ee8/href</a></iframe><p>And this is the moment when an event is emitted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y4JXncDXWtyILIT5_RAr9Q.png" /></figure><p>You can see that tasks will be created and will also automatically shut down when they have completed a task.</p><h3>Wrap up</h3><p>The article is quite long and challenging, but I hope that for those who intend to deploy microservices, this will be a useful reference if you’re still unsure about communication between services and how to deploy transactions across multiple services.</p><p>Thank you for your support, and see you in the next articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=606740b7eb10" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/the-interaction-between-micro-services-using-aws-ecs-run-task-606740b7eb10">The interaction between micro-services using AWS ECS Run Task</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building infrastructure (AWS) for micro-service by Terraform]]></title>
            <link>https://awstip.com/building-infrastructure-aws-for-micro-service-by-terraform-bd44118bbac0?source=rss-6a68697251eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd44118bbac0</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[tuananhhedspibk]]></dc:creator>
            <pubDate>Thu, 07 Mar 2024 14:44:43 GMT</pubDate>
            <atom:updated>2024-03-12T17:45:03.665Z</atom:updated>
            <content:encoded><![CDATA[<h3>Quick introduce about Terraform</h3><p>Terraform is an Infrastructure As Code (IaC) tool that allows you to create and manage infrastructure resources using code.</p><p>In Terraform, there are several fundamental concepts that need to be mastered:</p><ul><li>Terraform state</li><li>Terraform resource</li><li>Terraform variable</li><li>Terraform data source</li></ul><h4>Terraform state</h4><p>This can be understood as a tool for Terraform to track metadata as well as references between infrastructure resources in reality and your current configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*Dw7H8JD7LcmOXfzFWStfnA.png" /></figure><p>Moreover, Terraform state also demonstrates its power when working in a team. Put simply, based on Terraform state, team members can know:</p><ul><li>How their configuration differs from the resources in reality ?</li><li>How their configuration conflicts with the resources in reality ?</li></ul><p>The Terraform state is stored in the terraform.tfstate file in JSON format. However, it’s advisable to store it in a cloud environment and encrypt it carefully.</p><h4>Terraform resource</h4><p>A resource is a fundamental element in the Terraform language. Each resource block describes one or more infrastructure objects such as virtual networks, compute instances.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f0b95f91835ae10bc16ad611440970f/href">https://medium.com/media/7f0b95f91835ae10bc16ad611440970f/href</a></iframe><p>As in the example provided, I have an AWS VPC named “main,” where I would include information like:</p><ul><li>cidr_block</li><li>tags</li><li>dns_hostnames</li><li>…</li></ul><p>Each resource also has outputs (which can be understood as their own public properties).</p><p>For example:</p><p>With an AWS EC2 instance resource, after creation, it will have basic attributes such as:</p><ul><li>arn</li><li>public_ip</li><li>…</li></ul><p>You can read here for more details: <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance#attribute-reference">https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance#attribute-reference</a></p><h4>Terraform variable</h4><p>Similar to other programming languages, Terraform language also has its own definitions for variables.</p><p>In Terraform, there are two basic types of variables:</p><ul><li>Input Variables</li><li>Local Variables</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2a4bae6f0a30bca0fde899ec3420571/href">https://medium.com/media/b2a4bae6f0a30bca0fde899ec3420571/href</a></iframe><p>Input variables are declared in the format shown above (using the keyword ‘variable’ and specifying the variable type), and these variables define the ‘input parameters’ of a module. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e9942886ab39ffd54cc52c13ca3ffb7/href">https://medium.com/media/4e9942886ab39ffd54cc52c13ca3ffb7/href</a></iframe><p>In the code snippet above, I define a Module A, which requires an input parameter named ‘app_name.’ Other modules wishing to use this Module A would implement the configuration as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f06c9389eec6d2c1edc401457f253081/href">https://medium.com/media/f06c9389eec6d2c1edc401457f253081/href</a></iframe><p>Local variables are declared in the following format:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/435ea9a62d36a7ed887f5b00e30dacfc/href">https://medium.com/media/435ea9a62d36a7ed887f5b00e30dacfc/href</a></iframe><p>These local variables will only have an effect within the scope of the module in which they are defined.</p><h4>Terraform data source</h4><p>Data sources allow us to use resources <strong>NOT DEFINED BY TERRAFORM</strong>, such as referencing existing infrastructure resources in the system.</p><p>In my personal experience, I find data sources quite useful, especially with systems where setting up infrastructure used to be done manually rather than organized by code. Data sources allow us to reference these “legacy resources.”</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76acf17fc88a9720e15a0cdd05b76986/href">https://medium.com/media/76acf17fc88a9720e15a0cdd05b76986/href</a></iframe><h3>Infrastructure (AWS) architecture for micro-service</h3><p>In this deployment, I will proceed to deploy 3 micro-services: A, B, C.</p><p>For each micro-service, I will execute according to the following basic architecture:</p><p><strong>Network architecture </strong>(vpc, public_subnet, private_subnet)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-kwtLHFURSe28vjSXi0CA.png" /></figure><p>Analyze each component in the diagram above. Here, for each service, I will create a separate VPC.</p><p>In each VPC, of course, there will be a <strong>public_subnet</strong> and a <strong>private_subnet</strong>. And naturally, to allow resources within the private_subnet to access the outside internet, I will set up a <strong>nat_gateway</strong> and <strong>place it inside the public_subnet</strong>.</p><p>The database (here is AWS RDS) will be placed inside the private_subnet and will only accept two types of inputs:</p><ul><li>From within the VPC itself.</li><li>From a Proxy if coming from the internet.</li></ul><p>AWS ECS, to run the server code of the service, will be placed inside the private_subnet.</p><h4>Application architecture (ECS, Load Balancer)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lWgzmO6X9yJwUpKJVrr_VA.png" /></figure><p>Here, I simply place an <strong>Application Load Balancer</strong> in front of the ECS. Inside the ECS, I also place an <strong>nginx load balancer </strong>acting as a <strong>reverse proxy</strong> to protect the server code running inside the ECS service.</p><h3>Code referencing</h3><p>You can reference full source code in here: <a href="https://github.com/tuananhhedspibk/NewAnigram-Infrastructure">https://github.com/tuananhhedspibk/NewAnigram-Infrastructure</a></p><h4>Folder structuring</h4><p>I divide the resources according to module units:</p><ul><li><strong>network</strong>: vpc, public_subnet, private_subnet</li><li><strong>ecs_api</strong>: ecs_task_definition, ecs_service</li><li><strong>ecs_cluster</strong>: cluster</li><li><strong>proxy</strong>: database proxy</li><li><strong>rds</strong>: database</li></ul><p>The most outside <strong>main.tf</strong> will be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71226c86d0ede75827f4c4769c7d0b19/href">https://medium.com/media/71226c86d0ede75827f4c4769c7d0b19/href</a></iframe><h4>Network module</h4><p>In this module I’ll define:</p><ul><li>vpc</li><li>public_subnet</li><li>private_subnet</li><li>nat_gateway</li></ul><p>For vpc:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a871620d77e14b7fe54dd2091f5f3de/href">https://medium.com/media/8a871620d77e14b7fe54dd2091f5f3de/href</a></iframe><p>The most important thing here is the specification of <strong>cidr_block, </strong>basically cidr_block is virtual network address of vpc.</p><p>For public_subnet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1536a63c4f706032d69b20c0faaf6b00/href">https://medium.com/media/1536a63c4f706032d69b20c0faaf6b00/href</a></iframe><p>because this is a “public” subnet so I’ll set the value of <strong>map_public_ip_on_launch </strong>to be <strong>true </strong>for the purpose that can view it from the outside internet.</p><p>For private_subnet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90dd9c559e14a2b0f22561116c18c018/href">https://medium.com/media/90dd9c559e14a2b0f22561116c18c018/href</a></iframe><p>because this is the private_subnet — which means it cannot be seen from the global internet, so we need to set the <strong>map_public_ip_on_launch</strong> attribute to <strong>false</strong> so that this subnet DOES NOT HAVE a public IP from the global internet and therefore CANNOT be seen by it.</p><p>For <strong>nat_gateway</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ecd877cb113c8d1ddf5b0893cd08e8a/href">https://medium.com/media/9ecd877cb113c8d1ddf5b0893cd08e8a/href</a></iframe><p>In explanation, nat_gateway is a service that allows instances within a private_subnet to connect to the global internet and DOES NOT ALLOW the global internet to access instances inside the private_subnet.</p><p>You can reference here for more details: <a href="https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html">https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html</a></p><p>Back to the code snippet for setting up the nat_gateway mentioned earlier, I would configure it as follows:</p><ul><li>Assign an ElasticIP to the nat_gateway.</li><li>Place the nat_gateway in the public_subnet so that instances in the private_subnet can access the global internet from there.</li></ul><h4>Proxy Module</h4><p>The proxy here essentially is just an EC2 instance. My main purpose in setting up a proxy “blocking” in front of that RDS is to create an “entry point” as well as to “restrict” access (excluding access from the server code) to the RDS.</p><p>Specifically, as seen in the diagram above, the RDS is placed within a private_subnet, so it’s certain that access to the RDS from the global internet is NOT POSSIBLE. Therefore, the proxy here will act as an “entry point” when developers want to access the RDS for querying and editing data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bl96wzzyBBRMEnKMEXEouA.png" /></figure><p>You can see from the above image, developer will access to RDS via SSH tunel, with this we can limit the number of the accessor to RDS.</p><p>So proxy will act as “the shield” for our database. I’ll setup proxy like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26414329cc878ab2af9fa7331e5629ad/href">https://medium.com/media/26414329cc878ab2af9fa7331e5629ad/href</a></iframe><p>Like the code snippet above, to limit access only to allow SSH access to the proxy, I set the <strong>inbound rule</strong> for the proxy’s <strong>security_group</strong> to only port 22.</p><p>Since the proxy only serves as a “buffer zone” in front of the RDS, a <strong>micro</strong> instance is sufficient. And of course, we <strong>MUST</strong> place the proxy in the public_subnet to be able to access it from the global internet.</p><h4>RDS module</h4><p>In this module, I proceed to define an RDS instance and a cluster containing that instance. The main purpose is to store data (in other words, this is the database for the service).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcc9d3f1c31cfbd2afba6f12c5e69c08/href">https://medium.com/media/bcc9d3f1c31cfbd2afba6f12c5e69c08/href</a></iframe><p>Defining RDS is not so complicated, for more details you can read from here: <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/rds_cluster_instance">https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/rds_cluster_instance</a></p><p>The only note here is that the master_username and master_password will <strong>NOT BE USED</strong> in actual operation. It’s not necessarily prohibited, but rather <strong>NOT RECOMMENDED</strong>. Instead:</p><ul><li>Each developer accessing the database will have their own account with specific assigned privileges.</li><li>The service itself accessing the database will also be assigned its own account.</li></ul><p>All of the above actions are aimed at managing access and tracing to see which SQL queries are executed at what time when the system encounters issues or failures.</p><h4>ecs_cluster &amp; ecs_api modules</h4><p>I will merge these two modules into one because they are both related to ECS. The main purpose of splitting them into two sub-modules, cluster, and API, is simply to separate the definition of the ECS cluster from the ECS service.</p><p>For ecs_cluster:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f96b152af3813e64f74a66a01eab0c2f/href">https://medium.com/media/f96b152af3813e64f74a66a01eab0c2f/href</a></iframe><p>specify clusters name is enough.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9eb77af269f2dd59fc18b5be51aef1cb/href">https://medium.com/media/9eb77af269f2dd59fc18b5be51aef1cb/href</a></iframe><p>For the convenience, I will repost the illustration for the architecture of the ecs_service here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lWgzmO6X9yJwUpKJVrr_VA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/709e74b84aba14c57d202a5ca0531a27/href">https://medium.com/media/709e74b84aba14c57d202a5ca0531a27/href</a></iframe><p>This code snippet will create an nginx reverse proxy. At this point, all requests to the service will go through nginx before entering our service.</p><p>About ecs, you can see the under image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*njZVoHsD4_20PB6jBCAtsA.png" /></figure><p>In here:</p><ul><li>ECR (Amazon Elastic Container Registry) will store the DockerImage corresponding to the app.</li><li>Task Definition serves as the blueprint of the app (a JSON file with parameters, containers constituting the app).</li></ul><p>When operating a service with ECS, you need to:</p><ol><li>Dockerize the service into a Docker image.</li><li>Upload this Docker image to a registry (here, it’s ECR).</li><li>From the registry, you will build a task definition.</li><li>Using the task definition, you will create a service to run within ECS.</li></ol><p>In my case, I’ll setup task definition like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd08b3e9d183a676525884d7a81e3026/href">https://medium.com/media/cd08b3e9d183a676525884d7a81e3026/href</a></iframe><p>The content of task_definition in the JSON file will be like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/206af0dfb1727344adcd9bc79d601cd9/href">https://medium.com/media/206af0dfb1727344adcd9bc79d601cd9/href</a></iframe><h3>Executing</h3><p>To deploy Terraform code, I execute the command <strong>terraform apply</strong>. Before execution, Terraform will provide us with a preview of the resources that will be created, as shown in the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nyrCirBpkI6OS0mUqkAUCQ.png" /></figure><p>Due to the large number of resources created, I’ll only quote a small portion of them. Here are the results we’ll see upon confirmation on the AWS console.</p><p>VPC:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3gAZsTQc-KC19Sj34YnGNQ.png" /></figure><p>RDS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ku8McRYjMi1xmWaAN5uzKg.png" /></figure><p>Proxy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*51yIFCq9z1_tEDEJwnuVGA.png" /></figure><p>ECS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jGNAP3wGO54PR_o-43LxzA.png" /></figure><p>All configurations set up using Terraform code are accurately reflected on the AWS console (you can refer to the highlighted sections in the images above for more details).</p><h3>Summary</h3><p>OK, so I’ve briefly explained to readers how I built the infrastructure on AWS for a micro-service using Terraform from scratch.</p><p>I hope readers will gain the most visual understanding of the infrastructure architecture for a basic micro-service as well as how to use Terraform to deploy infrastructure.</p><p>See you in the next articles, thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd44118bbac0" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/building-infrastructure-aws-for-micro-service-by-terraform-bd44118bbac0">Building infrastructure (AWS) for micro-service by Terraform</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How did I build an API with DDD ? — Part 4]]></title>
            <link>https://medium.com/@tuananhhedspibk/how-did-i-build-an-api-with-ddd-part-4-c2864572f736?source=rss-6a68697251eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2864572f736</guid>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[tuananhhedspibk]]></dc:creator>
            <pubDate>Sat, 24 Feb 2024 13:32:57 GMT</pubDate>
            <atom:updated>2024-02-24T13:32:57.936Z</atom:updated>
            <content:encoded><![CDATA[<h3>How did I build an API with DDD ? — Part 4</h3><p>Welcome back to part 4 of series about DDD, you can read more detail about:</p><ul><li>Part 1 <a href="https://medium.com/@tuananhhedspibk/how-did-i-build-an-api-with-ddd-part-1-c95e137ba147">here</a></li><li>Part 2 <a href="https://medium.com/@tuananhhedspibk/how-did-i-build-an-api-with-ddd-part-2-33d07c4be635">here</a></li><li>Part 3 <a href="https://medium.com/@tuananhhedspibk/how-did-i-build-an-api-with-ddd-part-3-aeb39b6a3580">here</a></li></ul><p>In this article, I’m gonna show you about:</p><ol><li>How to implement <strong>presentation layer ?</strong></li><li>How to implement <strong>infrastructure layer ?</strong></li></ol><p>and hope that those sharing will be helpful for you.</p><h3>How to implement presentation layer ?</h3><h4>The handling of the Presentation Layer</h4><p>This will be the layer directly interacting with the client, so data conversion needs to be performed between the presentation layer and the use case layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aucSoHtn8Njs7qW_m8spzQ.png" /></figure><p>In application, we will have:</p><ul><li>JSON Controller: receives and returns result in JSON format</li><li>HTML Controller: receives submitted data from HTML form via <strong>application/x-www-form-urlencoded </strong>format</li></ul><p>Typically, the presentation layer will contain classes like <strong>XXXController</strong>, as it handles direct interaction with the client. Therefore, besides controllers, routing files can also be placed here.</p><p>For my API, I allocate a separate folder for the presentation layer, where controllers like:</p><ul><li>authentication</li><li>user</li><li>post</li><li>…</li></ul><p>are stored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*44gAVoYWbbpJnBwuqegdhA.png" /></figure><p>You can reference <a href="https://github.com/tuananhhedspibk/NewAnigram-BE-DDD-Public/tree/main/src/presentation/internal">here</a> for more details.</p><p>And depending on the framework, this layer can contain middleware such as <strong>logging</strong> or <strong>authentication</strong>. I won’t delve into these middlewares as they are outside the scope of this article.</p><p>In a controller, each route corresponds to a use case responsible for handling the business logic related to that route. For example, consider the API for updating a post.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a010272bf6e26710b5aa9b70151e35a/href">https://medium.com/media/4a010272bf6e26710b5aa9b70151e35a/href</a></iframe><p>Here, I have a feature where the API for posting/updating will be handled by the <strong>updatePostUsecase</strong>. This use case will receive input parameters including:</p><ul><li><strong>userId</strong>: is get from request that is sent from client.</li><li><strong>payload: </strong>have pre-defined <strong>UpdatePostUsecaseInput</strong> data type.</li></ul><h4>Define response structure</h4><p>The presentation layer will also be concerned with the format of the response returned to the client side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*3j_P_uMOxobQ-z_v9tlRNg.png" /></figure><p>As shown in the example, if the client wants to display “1,000” instead of “1000”, the task of converting the format for the returned data will be the responsibility of the presentation layer.</p><h3>How to implement infrastructure layer ?</h3><p>This layer is the outermost layer in the “onion architecture” I presented in <a href="https://medium.com/@tuananhhedspibk/how-did-i-build-an-api-with-ddd-part-2-33d07c4be635">part 2</a>. I will also illustrate it again in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDLTWNItDNUoXmidch1kAQ.png" /></figure><p>As depicted in the diagram, the infrastructure layer will perform the following tasks:</p><ul><li>Interacting with external systems or APIs.</li><li>Direct interaction with the database.</li></ul><p>So the question here is why do we have to implement interactions with external systems at the infrastructure layer. It’s quite simple: in DDD, we always want the domain layer (the core of the system) to depend on the least amount of technology possible.</p><p>Because each time we change the technology stack (for example, switching from PostgreSQL to MySQL), the impact on the system is significant. Therefore, the domain layer or even the use-case layer will need to be shielded from such “technology-driven impacts” as mentioned above. Furthermore, every time business logic or rules change, it’s highly likely that the entire system will be affected as well.</p><p>So in here we will:</p><ul><li>Define repository interfaces at the domain layer.</li><li>Implement those repository interfaces at the infrastructure layer.</li><li>Instead of using <strong>instance methods of implementing class, </strong>we will use <strong>method signatures of interface. </strong>Because a use-case only needs to focus on the input and output of a method <strong>WITHOUT NEEDING TO CONCERN</strong> itself with the implementation details or the content inside the method. This approach helps increase the independence of the use-case layer and reduces the coupling between layers.</li></ul><p>With my API, for the user domain, I define the UserRepository interface in the domain layer as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bcd1e4732bed166f619e0905ba58c43/href">https://medium.com/media/4bcd1e4732bed166f619e0905ba58c43/href</a></iframe><p>Full source code: <a href="https://github.com/tuananhhedspibk/NewAnigram-BE-DDD-Public/blob/main/src/domain/repository/user.ts">https://github.com/tuananhhedspibk/NewAnigram-BE-DDD-Public/blob/main/src/domain/repository/user.ts</a></p><p>And the use case layer will utilize these methods as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6265bf6c8d68a449a9acfb3774475623/href">https://medium.com/media/6265bf6c8d68a449a9acfb3774475623/href</a></iframe><p>We can see that the use case layer only needs to “inject” the UserRepository Interface and then use its method signatures such as getById or update.</p><p>You can observe that all methods belonging to the UserRepository interface will return UserDomainEntity. Therefore, besides fetching “raw data” from the database, the implementing classes in the infrastructure layer also need to “convert” it into the DomainEntity format. Here, we will use a factory (as discussed in <a href="https://medium.com/@tuananhhedspibk/how-did-i-build-an-api-with-ddd-part-1-c95e137ba147">part 1</a>) to perform the conversion.</p><p>The implementation in the infrastructure layer will be as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88e1539e7a6ad7e90db4d8f4019c5577/href">https://medium.com/media/88e1539e7a6ad7e90db4d8f4019c5577/href</a></iframe><p>We will first retrieve data from the database using the Repository provided by TypeORM.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2edcbc2c8f3b95a3d64c160791770dd/href">https://medium.com/media/c2edcbc2c8f3b95a3d64c160791770dd/href</a></iframe><p>At this point, the user object will contain pure “raw data”. To obtain a UserDomainEntity, we will need to use a factory as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/913a25852027dadc67003f9ec9101ea8/href">https://medium.com/media/913a25852027dadc67003f9ec9101ea8/href</a></iframe><h3>Summary</h3><p>So, in this article, I’ve presented to you the main points regarding:</p><ul><li>Implementation of the presentation layer.</li><li>Implementation of the infrastructure layer.</li></ul><p>And this marks the end of my series on DDD. Due to limitations in knowledge, the articles may have some shortcomings. I hope to receive feedback and criticism from readers to continuously update and refresh the articles in this DDD series.</p><p>Sincerely thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2864572f736" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How did I build an API with DDD ? — Part 3]]></title>
            <link>https://medium.com/@tuananhhedspibk/how-did-i-build-an-api-with-ddd-part-3-aeb39b6a3580?source=rss-6a68697251eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/aeb39b6a3580</guid>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[tuananhhedspibk]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 12:58:08 GMT</pubDate>
            <atom:updated>2024-02-23T12:58:08.959Z</atom:updated>
            <content:encoded><![CDATA[<h3>How did I build an API with DDD ? — Part 3</h3><p>Welcome back to part 3 of my DDD series. You can review:</p><ul><li>Part 1 in <a href="https://medium.com/@tuananhhedspibk/how-did-i-build-an-api-with-ddd-part-1-c95e137ba147">here</a></li><li>Part 2 in <a href="https://medium.com/@tuananhhedspibk/how-did-i-build-an-api-with-ddd-part-2-33d07c4be635">here</a></li></ul><p>In this part, I would like to present two main contents as follows:</p><ol><li>Context division</li><li>The architecture of the usecase layer</li></ol><h3>Context Division</h3><p>About context division, a very simple idea that anyone can think of is one context — one application, which implies implementing micro-service.</p><p>This approach has scalability advantages as the system grows larger. However, it also incurs higher costs and can be challenging to deploy.</p><h4>1 context — 1 application</h4><p>Let’s consider an e-commerce application. Essentially, we can divide this application into 2 contexts:</p><ol><li>Seller: serving the sales process.</li><li>Logistics: serving inventory management as well as goods handling.</li></ol><p>With these two contexts, we can see that for the same product, each context will be concerned with different aspects.</p><p>For the <strong>Seller</strong>, it would be the <em>price</em> and the <em>stock count</em> of the items in the warehouse.</p><p>For <strong>Logistics</strong>, it would be the <em>shipping status</em> and the <em>shipping address</em>.</p><p>The system architecture with 2 contexts can be described simply as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D_c7nJQY9XT43x-KKo04UA.png" /></figure><p>Basically, the interaction between the two contexts here is:</p><ul><li><strong>Synchronous</strong>: through direct calls like REST API calls.</li><li><strong>Asynchronous</strong>: through sending events such as AWS SQS.</li></ul><h4>n context — 1 application</h4><p>We will proceed to divide the folders corresponding to the contexts as shown in the example below:</p><pre>app<br>--- delivery<br>------- domain<br>------- infra<br>------- repo<br><br>--- sale<br>------- domain<br>------- infra<br>------- repo</pre><blockquote>One thing to note here is that it’s essential to carefully divide the folders from the beginning to facilitate easy splitting of the app later when it grows larger.</blockquote><h3>The architecture of the use-case layer</h3><h4>The main purpose of the use-case layer</h4><p>As its name suggests, the use-case layer itself is responsible for executing the core business functionalities of the system. I’ll give an example with my API, specifically the main functionalities on the user side, including:</p><ul><li>Follow</li><li>Unfollow</li><li>Update Password</li><li>Update Profile</li></ul><p>In that case, my use-case layer will include the main use cases as depicted below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*jKwnb9BFnI6cwbuOzGoMhg.png" /></figure><p>You can reference <a href="https://github.com/tuananhhedspibk/NewAnigram-BE-DDD-Public/tree/main/src/usecase/user">here</a></p><p>Let’s analyze the specific use case “UpdateProfile” — <a href="https://github.com/tuananhhedspibk/NewAnigram-BE-DDD-Public/blob/main/src/usecase/user/update-profile/index.ts">source code</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0f0638a24ce09e25bfcc8a7050913e0/href">https://medium.com/media/b0f0638a24ce09e25bfcc8a7050913e0/href</a></iframe><p>This is a small snippet of code within the UpdateProfile use-case. We can see that the use-case is where we utilize domain entities, which can interact with each other, but it can also involve using predefined public methods (these methods will accurately reflect the business logic that the User Domain is responsible for) to execute a feature within the system — in this case, the UpdateProfile feature or updating user information.</p><blockquote>Using methods of domain entities will increase the abstraction level for the domain layer since the use-case layer only cares about using methods without needing to concern itself with how they are implemented or what their internal contents are.</blockquote><h4>The return value from the use-case layer</h4><p>As analyzed in <a href="https://medium.com/@tuananhhedspibk/how-did-i-build-an-api-with-ddd-part-2-33d07c4be635">part 2</a>, if we use the <strong>Onion Architecture</strong>, our system can be diagrammed as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZFcj1Zi0gbigoIG9rP9Sw.png" /></figure><p>We can see that the presentation layer will wrap around the use-case layer, so it will receive the return value from the use-case layer.</p><p>When it comes to passing the return value from the use-case layer down to the presentation layer, we have two approaches:</p><ol><li>Creating a dedicated class to hold this return data type.</li><li>Passing the entire domain object down to the presentation layer.</li></ol><p>Let’s analyze the advantages and disadvantages of these two approaches. For <strong>approach 1</strong>, its advantages can be listed as follows:</p><ul><li>The presentation layer will not be able to see the domain business methods of the domain layer.</li><li>Avoiding modifications to the domain layer that could affect the presentation layer.</li></ul><p>In my API, I use this approach. Returning to the example of the <strong>UpdateProfile</strong> use case above, I define a separate output class for this use case as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e50378c82ce0b929f3a2320499b4c8c/href">https://medium.com/media/0e50378c82ce0b929f3a2320499b4c8c/href</a></iframe><p>You can reference <a href="https://github.com/tuananhhedspibk/NewAnigram-BE-DDD-Public/blob/main/src/usecase/user/update-profile/index.ts#L68">here</a> for more details.</p><p>The output in this use case will simply be to return the result of executing the use case, either success or failure, through the attribute <strong>code: ApiResultCode</strong>, very simply as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fc702f7ea7301971f4667d4018a57b2/href">https://medium.com/media/9fc702f7ea7301971f4667d4018a57b2/href</a></iframe><p>The advantage is as stated, but the disadvantage of this approach is that the cost of data type conversion will increase.</p><p>With approach 2, its pros and cons are exactly opposite to those of approach 1.</p><p>If we execute approach 2, the domain object needs to have methods to serve the presentation, which will make the domain object bloated and difficult to maintain. Therefore, if we apply approach 2, instead of spending effort on data conversion, the price to pay will be equally high.</p><h4>Assign name for Return Value Class</h4><p>Bạn có thể đặt tên theo format XXXDTO — DTO là Data Transfer Object</p><p>You can assign in format <strong>XXXDTO</strong> — <strong>DTO </strong>is the short form of<strong> “</strong>Data Transfer Object<strong>”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i9vS3FKoOsq6F_WDvBSASg.png" /></figure><h4>Some other considerations when implementing the use-case layer</h4><p><strong>Dividing classes in the use-case layer</strong></p><p>Usually, it’s one class per public method. In my API, I typically structure my use-case classes as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0534140cd0bda75f7cafd5c8759bdd59/href">https://medium.com/media/0534140cd0bda75f7cafd5c8759bdd59/href</a></iframe><p>You can reference <a href="https://github.com/tuananhhedspibk/NewAnigram-BE-DDD-Public/blob/main/src/usecase/user/update-profile/index.ts">here</a> for more details.</p><p><strong>Naming conventions for use-case classes</strong></p><ol><li>For classes with only one method, we keep the verb intact — e.g., <strong>CreateTaskUseCase</strong>.</li><li>For classes with multiple methods, we omit the verb from the class name — e.g., <strong>TaskUseCase</strong>.</li></ol><p>In essence, naming use-case classes will depend on the content and business of each individual project. However, one thing to note here is that we should think of names for use-case classes from the stage of designing the use-case diagram.</p><h3>Summary</h3><p>So, part 3 of my DDD series has come to a close. In this part, I’ve shared with you about:</p><ol><li>Diving context</li><li>The architecture of use-case layer</li></ol><p>Thanks for reading and see you again in the next part of series about DDD.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aeb39b6a3580" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>