<?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 Jawad Ahmad on Medium]]></title>
        <description><![CDATA[Stories by Jawad Ahmad on Medium]]></description>
        <link>https://medium.com/@jawadahmadd?source=rss-aeea6cde08ef------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bc4BoLwXgBGlcuyzRX1IRw.jpeg</url>
            <title>Stories by Jawad Ahmad on Medium</title>
            <link>https://medium.com/@jawadahmadd?source=rss-aeea6cde08ef------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:03:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jawadahmadd/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[Authenticate Google Workspace users without involving the browser]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@jawadahmadd/authenticate-google-workspace-users-without-involving-the-browser-85bc9952e4c4?source=rss-aeea6cde08ef------2"><img src="https://cdn-images-1.medium.com/max/600/0*XttgoYPlsm8PWEb-.jpg" width="600"></a></p><p class="medium-feed-snippet">I was recently working on a project when I came across a problem of authenticating Google Workspace users without involving the browser.</p><p class="medium-feed-link"><a href="https://medium.com/@jawadahmadd/authenticate-google-workspace-users-without-involving-the-browser-85bc9952e4c4?source=rss-aeea6cde08ef------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@jawadahmadd/authenticate-google-workspace-users-without-involving-the-browser-85bc9952e4c4?source=rss-aeea6cde08ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/85bc9952e4c4</guid>
            <category><![CDATA[ldapsearch]]></category>
            <category><![CDATA[ldap-authentication]]></category>
            <category><![CDATA[google-authentication]]></category>
            <dc:creator><![CDATA[Jawad Ahmad]]></dc:creator>
            <pubDate>Wed, 27 Sep 2023 19:44:31 GMT</pubDate>
            <atom:updated>2023-09-27T19:44:31.731Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[High Availability in Modern Applications]]></title>
            <link>https://medium.com/@jawadahmadd/high-availability-in-modern-applications-3be18e5c06b8?source=rss-aeea6cde08ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/3be18e5c06b8</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Jawad Ahmad]]></dc:creator>
            <pubDate>Thu, 22 Jun 2023 12:08:31 GMT</pubDate>
            <atom:updated>2023-06-22T12:11:04.407Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the fundamental pillars of Modern Applications is high availability. No matter how exceptional or feature-rich your application may be, if it is inaccessible when customers need it, it essentially becomes a dead piece of code.</p><p>People often confuse system availability with the term reliability but these two are really different things.</p><h4><strong>Reliability</strong></h4><p>The ability of your system to perform the operations it is intended to perform without making a mistake.</p><h4><strong>Availability</strong></h4><p>The ability of your system to be operational when needed in order to perform those operations.</p><p><em>A system that adds 10 + 20 and gets 40 has poor reliability. A system that adds 10 + 20 and never returns a result at all has poor availability.</em></p><p>Reliability can often be fixed through testing. Availability is usually much harder to solve as no one can anticipate when a system becomes unavailable.</p><h3><strong>But what are the few primary reasons for the poor availability of your system?</strong></h3><h4><strong>Resource exhaustion</strong></h4><p>With time, the number of users of your system will increase which directly increases the amount of data in use in your system and your application may fall victim to resource exhaustion, resulting in a slower and unresponsive application.</p><h4><strong><em>Unplanned load-based changes</em></strong></h4><p>If your application gains more popularity, it may be necessary to make adjustments to the code and application to accommodate the increased workload. These adjustments are typically made hastily and without proper forethought or planning, thereby raising the chances of encountering issues.</p><h4><strong><em>Outside dependencies</em></strong></h4><p>As your application becomes more reliant on external resources, such as SaaS services, infrastructure, or cloud-based services, it becomes increasingly susceptible to availability issues arising from these resources.</p><h3>Alright, but how do I measure the availability of my system?</h3><p>The most widely held mechanism for measuring the availability of a web application is calculating the percentage of time it’s accessible for use by customers. We can describe this by using the following formula for a given period:</p><p><em>Site availability percentage = total_seconds_in_period − seconds_system_is_down / total_seconds_in_period</em></p><p>Let’s consider an example. Suppose that over the month of April, your website was down twice; the first time it was down for 37 minutes, and the second time it was down for 15 minutes. What is the availability of your website?</p><p>You can see from the following example that it takes only a small amount of outage to have an impact on your availability percentage:</p><p>Total number of seconds down = (37 + 15) × 60 = 3,120s<br>Total number of seconds in month = 30 days × 86,400 s/day = 2,592,000s</p><p>Site availability percentage = 2,592,000s − 3,120 s / 2,592,000s</p><p>Site Availability percentage = 99.8795</p><p><strong>Your site availability is 99.8795%.</strong></p><h4>The Nines of availability</h4><figure><img alt="The nines of a system" src="https://cdn-images-1.medium.com/max/492/1*Wui4tMNsPqvm_QHPQh7y4g.png" /></figure><p>In the example mentioned earlier, we observe that the website falls slightly below the 3 nines metric (99.8795% instead of 99.9%). To achieve 5 nines of availability, a website can afford only 26 seconds of downtime per month.</p><p>Determining a specific threshold for considering your system as high availability is not possible with a single answer, as it greatly depends on various factors such as your website, customer expectations, business needs, and overall business goals. It is essential for you to assess and establish the desired availability number that aligns with your specific business requirements.</p><h3><strong>All that is good, but how do I know if my system has availability issues?</strong></h3><p>No one can anticipate where and when availability issues will occur. But you can assume that they will occur, especially as your system scales to larger customer demands and more complex applications. Being prepared in advance to handle availability concerns is the best way to reduce the likelihood and severity of problems.</p><p>The reliability of the system can be measured using unit or integration testing but not system availability. we don’t have any tool that we can run on top of our system which can say “<em>I have spotted availability issue no. XYZ”.</em></p><h3>It all makes sense, but how do I get prepared in advance?</h3><p>Keeping your system highly available is a daunting task. When architecting your system, you must always focus on a few things and continue to do so for the lifetime of your application.</p><h4><strong>Architect your system with failure in mind because what can fail will eventually fail</strong></h4><p>Werner Vogels, CTO of Amazon, says, “Everything fails all the time.” Plan on your applications and services failing. It will for sure happen, and probably on the days when your team least expects it.</p><p>When considering the potential failure of your application, it is crucial to consider the specific ways in which it might fail. Throughout the process of building your system, it is important to incorporate availability considerations into every aspect of its design and construction.</p><h4><strong>Some design constructs can help in improving the system’s availability</strong></h4><p>While designing your system, you must be aware of the design constructs and patterns you are using and how would they help in improving your system availability.</p><p>Using design constructs and patterns such as</p><ol><li>Simple error-catching deep within your application</li><li>Timeouts</li><li>Retry logic</li><li>Circuit breakers</li></ol><p>These allow you to catch errors when they have affected the smallest available subset of functionality. This allows you to limit the scope of a problem and have your application still provide useful capabilities even if part of the application is failing.</p><h4><strong>Dependencies inside your applications can fail and can impact your system’s availability</strong></h4><p>When a component you rely on experiences failure, what actions should be taken? How should you approach the retry mechanism? Moreover, how do you handle situations where the failure is unrecoverable (hard failure) rather than recoverable (soft failure)?</p><p>The circuit breaker pattern proves to be highly valuable in managing dependency failures as it minimizes the impact of such failures on your system. By lacking a circuit breaker, your application’s performance can suffer due to a dependency failure, such as experiencing excessively long timeouts to detect the failure. However, by employing a circuit breaker, you can gracefully handle the situation by temporarily halting the usage of a dependency until you are confident that it has fully recovered. This prevents unnecessary strain on your application and ensures more efficient operation.</p><h4><strong>Customers of your application can cause your availability to slip</strong></h4><p>How should you respond when a component, which is a consumer of your system, exhibits poor behavior? Are you equipped to handle an overwhelming influx of requests on your system? Can you effectively regulate excessive traffic? What measures are in place to handle invalid or unreliable data being passed into your system? Moreover, how do you manage an excessive volume of data being processed?</p><p>Occasionally, denial-of-service attacks can originate from unexpected sources, even those considered “friendly.” For instance, a sudden increase in activity from a customer of your application may necessitate a substantial increase in request volume directed toward your application. Similarly, a bug in your customer’s application might cause them to excessively call your application. How should you respond in such situations? Does the sudden influx of traffic overwhelm your application, leading to downtime? Alternatively, are you able to identify and address this issue by throttling the request rate, thereby mitigating or eliminating the impact on your application?</p><h4>Always think About Scaling as your life depended on it</h4><p>The fact that your application is functioning properly at present does not guarantee its smooth operation in the future. Web applications often experience a growth in traffic over time. The amount of traffic your website generates today could significantly increase sooner than expected. Therefore, when developing your system, it is crucial to avoid solely accommodating current traffic levels and instead focus on designing it to handle the anticipated traffic of the future.</p><ul><li>Architect in a way so that you can easily scale out and scale in your applications and databases as per needs.</li><li>Actively monitor the traffic patterns of each service so that you can put proactive scaling of your system ahead of time.</li><li>Make your services stateless so that you can scale them up to 1000s of instances behind a load balancer when needed.</li><li>The database is much harder to scale than your normal business services. Ample time must be allocated to determining what database suits the application and what its scalability limits or tradeoffs are. Don’t hesitate to use multiple databases for your applications as different databases can handle different kinds of workloads better than the other.</li><li>Think about what logical limits exist to your data scaling. What happens when your database tops out in its capabilities? Identify and remove these limits before your usage approaches them.</li><li>Redirect static traffic to offline providers. This allows your system to deal only with the dynamic traffic that it is designed to deal with. Using external content delivery networks (CDNs) not only can reduce the traffic your network has to handle but also allows the efficiencies of scale that CDNs provide to get that static content to your customers more quickly.</li><li>Think about whether specific pieces of dynamic content can actually be generated statically. Often, content that appears dynamic is actually mostly static, and the scalability of your application can be increased by making this content static. This “dynamic that can be static” data is sometimes hidden where you don’t expect it.</li></ul><h4>Mitigate Risks in your application</h4><p>Maintaining high system availability necessitates the mitigation of risks within the system. In many cases, the causes of system failures could have been recognized as risks prior to their actual occurrence. The identification of risks plays a crucial role in enhancing availability. It is important to acknowledge that all systems inherently contain certain risks.</p><ul><li>An application server will crash and can cause the upstream services to fail as well (cascading failures)</li><li>A database will go down or become corrupted</li><li>The database backup will also becomes corrupted</li><li>The whole data center in which your application is running can fail</li><li>A network connection will fail</li><li>A newly deployed piece of software will fail</li><li>The service responsible for upgrading the service might fail</li></ul><p>Keeping a system available requires removing risk. But as systems become more and more complicated, this becomes less and less possible. Keeping a large system available is more about managing what your risk is, how much risk is acceptable, and what you can do to mitigate that risk.</p><h4><strong>Monitor Availability</strong></h4><p>You can’t know if there is a problem in your application unless you can see a problem. Make sure your application is properly instrumented so that you can see how the application is performing from an external perspective as well as by way of internal monitoring.</p><p>Proper monitoring depends on the specifics of your application and needs, but it usually entails some of the following capabilities:</p><p><strong><em>Server monitoring</em></strong></p><p>To monitor the health of your servers and make sure they keep operating efficiently.</p><p><strong><em>Configuration change monitoring</em></strong></p><p>To monitor your system configuration and identify if and when changes to your infrastructure impact your application.</p><p><strong><em>Application performance monitoring</em></strong></p><p>To look inside your application and services to make sure they are operating as expected.</p><p><strong><em>Synthetic testing</em></strong></p><p>To examine in real time how your application is functioning from the perspective of your users, in order to catch problems customers might see before they actually see them.</p><p><strong><em>Alerting</em></strong></p><p>To inform appropriate personnel when a problem occurs so that it can be quickly and efficiently resolved, minimizing the impact on your customers.</p><h4>Respond to Availability Issues in a Predictable and Defined Way</h4><p>Monitoring systems serve no purpose unless you are ready to respond to the problems they detect. This entails receiving timely alerts when issues arise, enabling you to take appropriate action. Additionally, it is essential to establish processes and procedures that your team can follow to effectively diagnose issues and readily resolve common failure situations.</p><p>For example, if a service becomes unresponsive, you might have a set of remedies to try to make the service responsive. This might include tasks such as running a test to help diagnose where the problem is, restarting a daemon that is known to cause the service to become unresponsive, or rebooting a server if all else fails. Having standard processes in place for handling common failure scenarios will decrease the amount of time your system is unavailable. Additionally, these processes can provide useful follow-up diagnostic information to your engineering teams to help them deduce the root cause of common ailments.</p><h4>Conclusion</h4><p>Throughout the lifespan of your application, it is crucial to consider and prioritize these precautionary measures. Creating a highly available system is considerably more challenging than establishing a reliable one. Therefore, if you have experienced any instances of downtime, it is essential to pause and reassess how you are addressing availability concerns and incorporating some of the aspects mentioned in this article within your application.</p><p><strong>References</strong></p><p><a href="https://www.amazon.com/Architecting-Scale-Maintain-Availability-Manage/dp/1492057177/ref=sr_1_1?keywords=architecting+for+scale&amp;qid=1687433441&amp;sprefix=architecting+for+scale%2Caps%2C787&amp;sr=8-1">https://www.amazon.com/Architecting-Scale-Maintain-Availability-Manage/dp/1492057177/ref=sr_1_1?keywords=architecting+for+scale&amp;qid=1687433441&amp;sprefix=architecting+for+scale%2Caps%2C787&amp;sr=8-1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3be18e5c06b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cadence — The only workflow orchestrator you will ever need]]></title>
            <link>https://medium.com/@jawadahmadd/cadence-the-only-workflow-orchestrator-you-will-ever-need-ea8f74ed5563?source=rss-aeea6cde08ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea8f74ed5563</guid>
            <category><![CDATA[cadence]]></category>
            <category><![CDATA[uber]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[workflow]]></category>
            <dc:creator><![CDATA[Jawad Ahmad]]></dc:creator>
            <pubDate>Sun, 23 Feb 2020 17:12:23 GMT</pubDate>
            <atom:updated>2020-02-26T01:54:33.410Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cadence — The only workflow <strong>orchestrator</strong> you will ever need</h3><p>I have been recently working on a system that involves various microservices. One of the challenges in such a system is to have fault-tolerant communication between the services. Let us just discuss what it really means.</p><h3>Use case</h3><p>Let us say we have a <strong>Travel app</strong> that book a trip. It passes its request to the <strong>Travel Agent Service</strong> with booking information. <strong>Travel Agent Service</strong> then talks to 3 different services that may be in parallel. <strong>Car Rental Service</strong> (which will book a car), <strong>Hostel Reservation service </strong>(which will book a hotel) and then <strong>Airline Reservation service</strong> (which will book an airplane ticket).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aN9lZmikcUyuR_hJ.png" /></figure><p>In an ideal or happy world, whenever someone books a trip, all of the services are up and working perfectly fine and they just respond to whatever request comes in. But in reality, we all know, this isn’t true. Any of the services could go down for an unexpectedly amount of time. You might be able to book a hotel but not the Car or Airline ticket because the services gets crash for some reason.</p><p>You either want to book all or none. You could argue our <strong>Travel Agent service</strong> is up so we could just catch the error of service there and could roll back the previous transaction. But what if your <strong>Travel Agent Service</strong> itself goes down. So there could be so many possible cases that can happen while booking a trip but you either want 1 or 0 (transaction) not in between. How would you make that happen?</p><p>There could be many different ways to solve this. One of the patterns that is often used to solve these use cases in microservices is the <strong>Saga pattern</strong>.</p><h3>Saga</h3><p><em>The </em><strong><em>Saga Pattern</em></strong><em> is a microservices architectural pattern to implement a transaction that spans multiple services. A saga is a sequence of local transactions. Each service in a saga performs its own transaction and publishes an event. The other services listen to that event and perform the next local transaction.</em></p><p>Since this article is not about the Saga pattern, I will leave up to you guys to read about it and understand it. I am here to talk about the <strong>Cadence. </strong>So let us begin<strong>.</strong></p><h3>Cadence</h3><p><strong>Cadence</strong> is a workflow orchestrator. It is open-source, developed by Uber and written in Go language. The simplest definition I have come up with is, you define your workflows in your code and <strong>Cadence</strong> will make sure that the whole workflow code will execute <strong>no matter what!</strong> It is a very powerful thing if you just step back and think about it. Your workflow code might involve talking to 100s of different services and <strong>Cadence</strong> will make sure your workflow does that. The official definition goes like this.</p><h4>Official definition</h4><p><strong><em>Cadence</em></strong><em> fault-oblivious stateful code platform preserves a complete multithreaded application state including thread stacks with local variables across hardware and software failures. It greatly simplifies the coding of complex stateful distributed applications. At the same time, it is scalable and robust enough to power hundreds of critical use cases at Uber and outside.</em></p><p>Given the above definition, it has many use cases in production. Cadence website also mentions a few use cases where it perfectly makes sense to use Cadence. <strong>Saga </strong>is just one of the use case, there are plenty of more. Check it out!</p><p><a href="https://cadenceworkflow.io/docs/02_use_cases/">Use Cases</a></p><h3>Cadence components</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9S2EB4yigUAJbs-snF-hQQ.jpeg" /><figcaption>Cadence components architecture</figcaption></figure><h4><strong>Cadence service</strong></h4><p>At the core of the entire system, there is a cadence service that is basically the brain. It uses persistence layer to store workflow state. For now, Cadence supports Cassandra or MySQL out of the box for storage. There is also a <strong>task list</strong> that is basically a FIFO queue. Workers listen to these task lists and get the task.</p><h4><strong>Task lists</strong></h4><p>Task lists are basically the lists through which the worker gets their task either workflow worker or an activity worker. There are basically two kinds of task lists, one is <strong>decision task list</strong> and the other is <strong>activity task list</strong>. A task list can be both, <strong>a decision task list </strong>and<strong> an activity task list</strong>.</p><h4><strong>Workers</strong></h4><p>Workers are basically the component that hosts your code. You write workflow and activity code in your workers. They are simple processes that use Cadence APIs. They listen to the tasks list using a long poll request. When they receive a task from the task list they execute appropriate code and communicates task execution results back to the Cadence service. A worker can host both the workflow or activity code. This means a worker can receive <strong>decision tasks</strong> as well as <strong>activity tasks</strong>. In the picture, they are two separate workers. It is just a matter of scalability how you divide your code.</p><h4><strong>Workflow starter</strong></h4><p>These are considered as the external client that actually trigger the workflows by workflow name (there are other ways as well). You can provide input to the workflow. The one must have a parameter is the workflow ID and it has to be unique across all your workflows. Workflow can be trigger synchronously as well as asynchronously.</p><h4><strong>Workflow</strong></h4><p>Workflow basically a fault-oblivious stateful function that orchestrates activities. A Workflow has full control over which activities are executed, and in which order. A Workflow must not affect the external world directly, only through activities. What makes workflow code a Workflow is that its state is preserved by Cadence. Therefore any failure of a worker process that hosts the workflow code does not affect the workflow execution. The Workflow continues as if these failures did not happen. At the same time, activities can fail any moment for any reason. Because workflow code is fully fault-oblivious, it is guaranteed to get notifications about activity failures or timeouts and act accordingly. There is no limit on potential workflow duration.</p><h4><strong>Activity</strong></h4><p>A business-level function that implements your application logic such as calling a service or performing any external world task. An activity usually implements a single well-defined action; it can be short or long-running. An activity can be implemented as a synchronous method or fully asynchronously involving multiple processes. An activity can be retried indefinitely according to the provided exponential retry policy. If for any reason an activity is not completed within the specified timeout, an error is reported to the workflow and the workflow decides how to handle it. There is no limit on potential activity duration.</p><p>You might be wondering and saying it all sounds cool, but how does everything fit into one picture. Let us just cover our Travel App use case and try to implement it in cadence components and see what fits where.</p><p><strong>Travel App use case</strong></p><p>For our convenience, let us just paste the above picture here so we don’t have to go up to see the picture to relate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*aN9lZmikcUyuR_hJ.png" /></figure><p>The very first thing that we need to identify is what would be our workflow and activity code. From the picture above. <strong>Travel Agent Service </strong>is the perfect candidate for our workflow code because this is the service that must be fault-oblivious. This will decide either the booking is successful or not.</p><p>For the activities, Car, Hotel and Airline service seems to be perfect candidate because they are kind of external world to the Travel Agent service. Their APIs might not be in our control so they could fail at any time.</p><p>So far so good, we have identified the workflow and activities. What will be the workflow starter? Any guess?<br>Yes, it is the <strong>Travel App</strong> itself that triggers the workflow with the booking information (remember workflow could take input as well). Let us just try to write a sequence of requests.</p><ol><li>User wants to book a trip so Travel app handles that request with the booking information.</li><li>Travel App triggers a workflow that may be named as <strong>BookTripWorkFlow </strong>synchronously or asynchronously. If it is synchronous, then Travel app waits (block) for the workflow to complete. If it is asynchronous then Travel app gets a <strong>Future </strong>in return<strong> </strong>and workflow execution information such as workflowID, RunID. It really depends on the business case how would you want to trigger a workflow.</li><li>Workflow triggered request goes to the cadence service which then puts a task to the task list.</li><li>The workers listen to those tasks from task lists and perform execution of the code you have written and upon completion, respond back to the cadence service.</li><li>This process goes on and on until the workflow code completes.</li><li>Remember, only the workflow code is fault-oblivious. If your request to Car service completed successfully but failed for the Hotel or Airline service. You have to write the compensation logic that will undo the previous completed request or you could retry indefinitely times for the Hotel or Airline service to complete the request. This again depends on the use case or business decision. Since these requests will be triggering from your workflow, you will have a guarantee that they will execute however you want to, no matter what.</li><li>And eventually when the workflow code completes. The Future in Travel App has the result or the code gets unblock if the workflow started synchronously.</li></ol><p><strong>Summary</strong></p><p>This was a very high-level introduction to Cadence. You can read the documentation on the official docs. It is a very powerful tool. It is a little hard to get started with but once you do, you will see how powerful it is and can think of plenty of use cases where you can fit this awesome thing.</p><p><strong>References</strong></p><p><a href="https://cadenceworkflow.io/docs/">https://cadenceworkflow.io/docs/</a></p><p>Thank you and feel free to ask any questions.</p><p>📝 Save this story in <a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_read_later_text">Journal</a>.</p><p>👩‍💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. <a href="https://usejournal.com/newsletter/noteworthy-in-tech/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_text">Read the Noteworthy in Tech newsletter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea8f74ed5563" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enable only TLS 1.2 in Node JS]]></title>
            <link>https://medium.com/@jawadahmadd/enable-only-tls-1-2-in-node-js-118687fb3746?source=rss-aeea6cde08ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/118687fb3746</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[cipher]]></category>
            <category><![CDATA[ssl]]></category>
            <category><![CDATA[tls]]></category>
            <dc:creator><![CDATA[Jawad Ahmad]]></dc:creator>
            <pubDate>Tue, 15 Oct 2019 07:41:10 GMT</pubDate>
            <atom:updated>2019-10-15T07:41:10.725Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey all, in this article I won’t try to explain the TLS itself, I assume if you are here, you already know the TLS. This article is specific to enabling TLS 1.2 only in Node JS. If you really don’t know what is TLS so please watch the video below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FcuR05y_2Gxc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DcuR05y_2Gxc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FcuR05y_2Gxc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1e316ffdb130edfd6a7c85795f63f9f/href">https://medium.com/media/f1e316ffdb130edfd6a7c85795f63f9f/href</a></iframe><p>I also assume you already have obtained the certificates (private key and public key). If you don’t you can google how to create certificates for your web server and you will find plenty of ways to do that. You could use <strong>let’s encrypt </strong>to create certificates as it is a very popular tool.</p><p>After obtaining the certificates you need to use HTTPS package to create a web server. It requires a configuration object that will contain the certificates and other configuration as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P6yXVCtlfvY_3BgwK7cPRw.png" /></figure><p>So options object take <strong>key, cert</strong> properties, you will provide generated certificates files here.</p><p>secureOptions property decides which protocols to support either tls 1.0, tls 1.1 or tls 1.2.</p><p>By default, Node JS support all the TLS protocols and if you need to exclude the particular protocol, we need to mention the protocol in the sercureOptions, separated by the bitwise OR. In our case I have excluded SSL 2, SSL 3, TLS 1.0, TLS 1.1 and that leads us to only support the TLS 1.2.</p><p>Moreover, you can also provide specific ciphers as well. You can find the cipher suites for each protocol here:</p><p><a href="https://www.openssl.org/docs/man1.1.1/man1/ciphers.html#CIPHER-LIST-FORMAT">/docs/man1.1.1/man1/ciphers.html</a></p><p>Ciphers are provided in the format of String separated by ‘:’ i.e. “TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384”.</p><p>In the end, you will just start your server on a specific port.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZcJmnDRYuuV_5HeeG1Eq1A.png" /></figure><p>In order to test if all of this really has worked, you could use nmap utility available in linux.</p><blockquote>sudo apt install nmap</blockquote><p>and in your shell run a command</p><blockquote>nmap — script ssl-enum-ciphers -p 5000 localhost</blockquote><p>5000 is the port and localhost is the host on which the server is running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*D39bS50S3iwjkWu2mNe9yQ.png" /></figure><p>You could see the output that it is only accepting tls 1.2 and specific active ciphers.</p><p>Thank you for reading the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=118687fb3746" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NSQ with Go]]></title>
            <link>https://medium.com/@jawadahmadd/nsq-with-go-77ca1b69c4ec?source=rss-aeea6cde08ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/77ca1b69c4ec</guid>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[nsq]]></category>
            <dc:creator><![CDATA[Jawad Ahmad]]></dc:creator>
            <pubDate>Sun, 16 Dec 2018 15:33:46 GMT</pubDate>
            <atom:updated>2018-12-16T15:47:58.548Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://nsq.io/">NSQ</a> (New simple queue) is a realtime distributed messaging platform written in Go. It was created at <a href="https://bitly.com/">Bitly</a> a very popular URL shortening service and a link management platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UpRoHyKKeaHycys0ajBvXQ.png" /><figcaption>Home page of NSQ</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*58LWPVP5SGrPAxwwffhufw.gif" /><figcaption>NSQ data flow</figcaption></figure><p>This article is not about NSQ and its features but its usage. NSQ has pretty great documentation about its features and guarantees it provides as a messaging system. It is a rival of Apache Kafka but it is different in terms of the underlying architect and working. It is pretty simple to use and scale in production and it is one of the biggest advantage of it over Kafka as Kafka is hard to manage and scale in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*d2ZeJAwIrxGiRdiIzO9Nww.png" /></figure><p>A comparison of pros and cons of different messaging platform.</p><p><a href="https://stackshare.io/stackups/kafka-vs-nsq-vs-rabbitmq">RabbitMQ vs Kafka vs NSQ 2018 Comparison</a></p><p>Clients for NSQ is available in many languages. We are using the go-nsq which is official client for Go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNd_-RZJmhzo3MYy4NCAbA.png" /><figcaption><a href="https://nsq.io/clients/client_libraries.html">https://nsq.io/clients/client_libraries.html</a></figcaption></figure><p><strong>Producing messages in NSQ topic</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F0S9dLyaQ6eoCxWCWoqTzw.png" /><figcaption>nsqadmin</figcaption></figure><p>You can use nsqadmin utility to browse topics and see the number of messages in the specific topic. As you can see there is no topic currently in the nsq. Let us just create one and start pushing messages.</p><pre><strong>package </strong>main<br><br><strong>import </strong>(<br>   <strong>&quot;github.com/nsqio/go-nsq&quot;<br>   &quot;log&quot;<br>   &quot;strconv&quot;<br></strong>)<br><br><strong>func </strong>main() {<br>   config := nsq.NewConfig()<br>   w, _ := nsq.NewProducer(<strong>&quot;127.0.0.1:4150&quot;</strong>, config)<br>   <strong>for </strong>i:= 0; i &lt; 1000; i++ {<br>      err := w.Publish(<strong>&quot;eMumba&quot;</strong>, []byte(<strong>&quot;test&quot; </strong>+ strconv.Itoa(i)))<br>      <strong>if </strong>err != nil {<br>         log.Panic(<strong>&quot;Could not connect&quot;</strong>)<br>      }<br>   }<br>   w.Stop()<br>}</pre><p>Yes it is that simple. You just need to tell which topic and provide data and there you go. It will automatically create topic eMumba for you and start pushing messages into the topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UfUUpV-goD5EoII6X-UNgQ.png" /></figure><p>You can see there are 1000 messages in the eMumba topic. Let us consume them.</p><p><strong>Consuming messages from NSQ topic</strong></p><pre><strong>package </strong>main<br><br><strong>import </strong>(<br>   <strong>&quot;github.com/nsqio/go-nsq&quot;<br>   &quot;log&quot;<br>   &quot;sync&quot;<br></strong>)<br><br><strong>func </strong>main(){<br><br>   wg := &amp;sync.WaitGroup{}<br>   wg.Add(1)<br><br>   config := nsq.NewConfig()<br>   q, _ := nsq.NewConsumer(<strong>&quot;eMumba&quot;</strong>, <strong>&quot;ch&quot;</strong>, config)<br>   q.AddHandler(nsq.HandlerFunc(<strong>func</strong>(message *nsq.Message) error {<br>      log.Println(string(message.Body))<br>      <strong>return </strong>nil<br>   }))<br>   err := q.ConnectToNSQD(<strong>&quot;127.0.0.1:4150&quot;</strong>)<br>   <strong>if </strong>err != nil {<br>      log.Panic(<strong>&quot;Could not connect&quot;</strong>)<br>   }<br>   wg.Wait()<br><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V9JerhD-2meQJFsjSaQFtQ.png" /><figcaption>Consumed messages from NSQ topic eMumba</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tAPsCEP7nDZBKXXZGSmetg.png" /></figure><p>nsqadmin also provides a Counter tab where it says how many messages has been consumed or processed till now.</p><p>The code for producing and consuming messages is pretty straight forward as you would expect. There are many concepts of NSQ that I didn’t cover in this article. You might want to go to nsq home page and check them out. I am providing few references and links to understand the concepts of NSQ.</p><p><a href="https://nsq.io/overview/design.html">Design</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FCL_SUzXIUuI%3Fstart%3D1187%26feature%3Doembed%26start%3D1187&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DCL_SUzXIUuI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FCL_SUzXIUuI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc71041bd8caf9a8343ae42467e1533a/href">https://medium.com/media/cc71041bd8caf9a8343ae42467e1533a/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FOwD-W7uU2zU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DOwD-W7uU2zU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FOwD-W7uU2zU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a95fcfe5871e1f56fe1656a43a0e3bcd/href">https://medium.com/media/a95fcfe5871e1f56fe1656a43a0e3bcd/href</a></iframe><p>I hope this article is useful to you. Please let me know if you have any comments or suggestions. Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77ca1b69c4ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Kafka with Go]]></title>
            <link>https://medium.com/@jawadahmadd/apache-kafka-with-go-f67986afb9a9?source=rss-aeea6cde08ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/f67986afb9a9</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[sarama]]></category>
            <category><![CDATA[consumer]]></category>
            <category><![CDATA[producer]]></category>
            <dc:creator><![CDATA[Jawad Ahmad]]></dc:creator>
            <pubDate>Sun, 16 Dec 2018 14:11:52 GMT</pubDate>
            <atom:updated>2018-12-17T04:48:00.283Z</atom:updated>
            <content:encoded><![CDATA[<p>Go is becoming very popular for the backend development. Many enterprises now using Go for their different services. Apache Kafka is a very popular distributed messaging system or streaming platform and almost every enterprise use it for async communication between their difference services.</p><p>In this article we are going to have a look at how Go uses Kafka Producer API and Consumer API to produce and consume messages respectively.</p><p>There are several packages available in Go. One can use to produce and consume messages to and from Kafka. I am going to use Sarama, because it has most stars on github :P. Just kidding. Sarama provides both sync producer and async producer. You might want to check out all of them and use the one which feels right to you.</p><p><strong>Go packages for Kafka</strong></p><ol><li><a href="https://github.com/Shopify/sarama">https://github.com/Shopify/sarama</a></li><li><a href="https://github.com/bsm/sarama-cluster">https://github.com/bsm/sarama-cluster</a></li><li><a href="https://github.com/confluentinc/confluent-kafka-go">https://github.com/confluentinc/confluent-kafka-go</a></li><li><a href="https://github.com/segmentio/kafka-go">https://github.com/segmentio/kafka-go</a></li><li>… and there are more!</li></ol><p><strong>Producing messages in Kafka using </strong><a href="https://github.com/Shopify/sarama">sarama</a></p><pre><strong>package </strong>main<br><br><strong>import </strong>(<br>   <strong>&quot;fmt&quot;<br>   &quot;github.com/Shopify/sarama&quot;<br>   &quot;log&quot;<br>   &quot;time&quot;<br></strong>)<br><br><strong>func </strong>main(){<br>   brokerList := []string{<strong>&quot;localhost:9092&quot;</strong>}<br>   topic := <strong>&quot;jawad&quot; </strong><em>// any topic you want<br>   </em>producer := &amp;Producer{<br>      SyncProducer:  GetSyncProducer(brokerList),<br>      AsyncProducer: GetAsyncProducer(brokerList),<br>   }<br>   ProduceMessageAsync(producer, topic)<br>   ProduceMessageSync(producer, topic)<br><br>   producer.SyncProducer.Close() <em>// handle error yourself<br>   </em>producer.AsyncProducer.Close() <em>// // handle error yourself<br></em>}<br><br><br><strong>type </strong>Producer <strong>struct </strong>{<br>   SyncProducer     sarama.SyncProducer<br>   AsyncProducer sarama.AsyncProducer<br>}<br><br><strong>func </strong>ProduceMessageAsync(producer *Producer, topic string){<br>   <em>// We are not setting a message key, which means that all messages will<br>   // be distributed randomly over the different partitions.<br>   </em>message := &amp;sarama.ProducerMessage{<br>      Topic: topic,<br>      Value: sarama.StringEncoder(<strong>&quot;Hello Go! Async Message&quot;</strong>),<br>   }<br>   producer.AsyncProducer.Input() &lt;- message<br>}<br><br><br><strong>func </strong>ProduceMessageSync(producer *Producer, topic string){<br>   <em>// We are not setting a message key, which means that all messages will<br>   // be distributed randomly over the different partitions.<br>   </em>message := &amp;sarama.ProducerMessage{<br>      Topic: topic,<br>      Value: sarama.StringEncoder(<strong>&quot;Hello Go! Sync Message&quot;</strong>),<br>   }<br>   partition, offset, err:= producer.SyncProducer.SendMessage(message)<br><br>   <strong>if </strong>err != nil {<br>      fmt.Println( <strong>&quot;Failed to store your data:, %s&quot;</strong>, err)<br>   } <strong>else </strong>{<br>      <em>// The tuple (topic, partition, offset) can be used as a unique identifier<br>      // for a message in a Kafka cluster.<br>      </em>fmt.Println( <strong>&quot;Your data is stored with unique identifier important/%d/%d&quot;</strong>, partition, offset)<br>   }<br>}<br><br><strong>func </strong>GetAsyncProducer(brokerList []string) sarama.AsyncProducer {<br>   <em>// For the access log, we are looking for AP semantics, with high throughput.<br>   // By creating batches of compressed messages, we reduce network I/O at a cost of more latency.<br>   </em>config := sarama.NewConfig()<br>   config.Producer.RequiredAcks = sarama.<strong><em>WaitForLocal       </em></strong><em>// Only wait for the leader to ack<br>   </em>config.Producer.Compression = sarama.<strong><em>CompressionSnappy   </em></strong><em>// Compress messages<br>   </em>config.Producer.Flush.Frequency = 500 * time.<strong><em>Millisecond </em></strong><em>// Flush batches every 500ms<br><br>   </em>producer, err := sarama.NewAsyncProducer(brokerList, config)<br>   <strong>if </strong>err != nil {<br>      log.Fatalln(<strong>&quot;Failed to start Sarama producer:&quot;</strong>, err)<br>   }<br>   <em>// We will just log to STDOUT if we&#39;re not able to produce messages.<br>   // Note: messages will only be returned here after all retry attempts are exhausted.<br>   </em><strong>go func</strong>() {<br>      <strong>for </strong>err := <strong>range </strong>producer.Errors() {<br>         log.Println(<strong>&quot;Failed to write access log entry:&quot;</strong>, err)<br>      }<br>   }()<br><br>   <strong>return </strong>producer<br>}<br><br><strong>func </strong>GetSyncProducer(brokerList []string) sarama.SyncProducer {<br>   <em>// For the data collector, we are looking for strong consistency semantics.<br>   // Because we don&#39;t change the flush settings, sarama will try to produce messages<br>   // as fast as possible to keep latency low.<br>   </em>config := sarama.NewConfig()<br>   config.Producer.RequiredAcks = sarama.<strong><em>WaitForAll </em></strong><em>// Wait for all in-sync replicas to ack the message<br>   </em>config.Producer.Retry.Max = 10                   <em>// Retry up to 10 times to produce the message<br>   </em>config.Producer.Return.Successes = <strong><em>true<br>   </em></strong><em>// On the broker side, you may want to change the following settings to get<br>   // stronger consistency guarantees:<br>   // - For your broker, set `unclean.leader.election.enable` to false<br>   // - For the topic, you could increase `min.insync.replicas`.<br>   </em>producer, err := sarama.NewSyncProducer(brokerList, config)<br>   <strong>if </strong>err != nil {<br>      log.Fatalln(<strong>&quot;Failed to start Sarama producer:&quot;</strong>, err)<br>   }<br><br>   <strong>return </strong>producer<br>}</pre><p>I know the code is little funky, you guys should copy this and paste it into the text editor and have a clear look.</p><p>After running this above code. The messages will be produced into the Kafka topic <em>jawad</em>.</p><p>We haven’t set the key while producing the messages, so key is automatically set by the Kafka itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ijxz42BAh1brMJFmc86bNA.png" /><figcaption>Messages in topic jawad</figcaption></figure><p><strong>Consuming messages from Kafka using </strong><a href="https://github.com/bsm/sarama-cluster">sarama-cluster</a></p><pre><strong>package </strong>main<br><br><strong>import </strong>(<br>   <strong>&quot;fmt&quot;<br>   &quot;github.com/Shopify/sarama&quot;<br>   &quot;log&quot;<br>   &quot;os&quot;<br>   &quot;os/signal&quot;<br>   &quot;github.com/bsm/sarama-cluster&quot;<br></strong>)<br><br><strong>func </strong>main() {<br><br>   <em>// init (custom) config, enable errors and notifications<br>   </em>config := cluster.NewConfig()<br>   config.Consumer.Offsets.Initial = sarama.<strong><em>OffsetOldest<br>   </em></strong>config.Consumer.Return.Errors = <strong><em>true<br>   </em></strong>config.Group.Return.Notifications = <strong><em>true<br><br>   </em></strong><em>// init consumer<br>   </em>brokers := []string{<strong>&quot;localhost:9092&quot;</strong>}<br>   topics := []string{<strong>&quot;jawad&quot;</strong>}<br>   consumer, err := cluster.NewConsumer(brokers, <strong>&quot;eMumba&quot;</strong>, topics, config)<br>   <strong>if </strong>err != nil {<br>      panic(err)<br>   }<br><br>   <strong>defer </strong>consumer.Close()<br><br>   <em>// trap SIGINT to trigger a shutdown.<br>   </em>signals := make(<strong>chan </strong>os.Signal, 1)<br>   signal.Notify(signals, os.Interrupt)<br><br>   <em>// consume errors<br>   </em><strong>go func</strong>() {<br>      <strong>for </strong>err := <strong>range </strong>consumer.Errors() {<br>         log.Printf(<strong>&quot;Error: %s\n&quot;</strong>, err.Error())<br>      }<br>   }()<br><br>   <em>// consume notifications<br>   </em><strong>go func</strong>() {<br>      <strong>for </strong>ntf := <strong>range </strong>consumer.Notifications() {<br>         log.Printf(<strong>&quot;Rebalanced: %+v\n&quot;</strong>, ntf)<br>      }<br>   }()<br><br>   <em>// consume messages, watch signals<br>   </em><strong>for </strong>{<br>      <strong>select </strong>{<br>      <strong>case </strong>msg, ok := &lt;-consumer.Messages():<br>         <strong>if </strong>ok {<br>            fmt.Fprintf(os.Stdout, <strong>&quot;%s/%d/%d\t%s\t%s\n&quot;</strong>, msg.Topic, msg.Partition, msg.Offset, msg.Key, msg.Value)<br>            consumer.MarkOffset(msg, <strong>&quot;&quot;</strong>)   <em>// mark message as processed<br>         </em>}<br>      <strong>case </strong>&lt;-signals:<br>         <strong>return<br>      </strong>}<br>   }<br>}</pre><p>After running this above code. The messages will be consumed from the Kafka topic <em>jawad</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jxBnrCmscRaqiD0YprzZRg.png" /><figcaption>Consumed messages from Kafka</figcaption></figure><p>So, I wouldn’t go through all of the code as it is pretty straight forward and easy to understand. Different packages have different implementations to do the same thing. Pick one which feels right to you. I like Sarama as it feels just like Java implementation of Kafka client and it is pretty stable too.</p><p>I hope this article is useful to you. Please let me know if you have any comments or suggestions. Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f67986afb9a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basics of error handling in Go]]></title>
            <link>https://medium.com/@jawadahmadd/basics-of-error-handling-in-go-c6a4615b7881?source=rss-aeea6cde08ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6a4615b7881</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Jawad Ahmad]]></dc:creator>
            <pubDate>Sun, 30 Sep 2018 19:30:16 GMT</pubDate>
            <atom:updated>2018-10-01T04:47:50.358Z</atom:updated>
            <content:encoded><![CDATA[<p>No matter how great we are at programming, sometimes our programs have errors. They may occur because of our mistakes, an unexpected user input, an erroneous server response and for a thousand of other reasons.</p><p>A common and a huge mistake that we as developer do while programming is to take errors for granted. We consider handling them as a low priority feature that can be implemented later . We so much rely on the <strong>linters</strong> these days to spot out errors in our programs and we possibly do not cover all flows of the application while testing the application in our testing environment in which <strong>linters</strong> could spot things out for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/0*_lScrhZ_YEdDVm-h.jpg" /></figure><p>And when we deploy our application in production, a moment later, it crashes with the huge stack trace. We immediately start looking at the code and start debugging it, after few hours of debugging, you find out that you <strong>forget to</strong> <strong>close the opened file</strong> or you <strong>forget to handle a failure in network call</strong> or even <strong>forget to handle JSON or Date parsing failure from a string </strong>at some place in your code. This is so normal for even an experienced developer to forget things like these in the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/0*KE7zJiVaBpR5Q2QN" /></figure><p>Traditional way of handling errors in popular programming languages such as C++, Java, C#, Javascript and Python etc use the try catch block. It is considered as an optional feature. The language itself do not enforce you to handle errors. The traditional try catch works this way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/0*MePNTK-MQZiYoPFv.png" /><figcaption>Tradition way of handling errors.</figcaption></figure><pre>try {<br>  // code...<br>} catch (err) {<br>  // error handling<br>}</pre><p>Go took different approach to handle errors, it enforces you to handle these errors so you won’t forget. Although it makes your code little arguably difficult to read for some people but it makes your code robust and you might get little or no surprises at all when you run the code in production.</p><p>Today, we are going to take a look at handling errors in Go and how it enforces you to handle these errors in your main flow of the program so you won’t get any surprises when you run your application in production.</p><p><strong>NOTE: This article does not teach you the best practices to handle errors in Go.</strong></p><p><em>Errors in Go are just simple values. You can assign them to variables, pass to functions and even return from the functions. You can simply create them using the errors package which happens to be builtin package.</em> Yay!</p><pre>package main<br><br>import (<br>   &quot;errors&quot;<br>   &quot;fmt&quot;<br>)<br><br>func main(){<br>   <em>// Creating and assinging error value<br>   </em>myCustomError := errors.New(&quot;custom error&quot;)<br>   myCustomError2 := ThisFunctionReturnError()</pre><pre>   //passing error values to functions<br>   ThisFunctionGetsErrorValueAsAParameter(myCustomError)<br>   ThisFunctionGetsErrorValueAsAParameter(myCustomError2)<br>}<br><br>func ThisFunctionReturnError() error {<br>   return errors.New(&quot;custom error 2&quot;)<br>}</pre><pre>// Please never make your function name big, this is just for demonstration purpose.<br>func ThisFunctionGetsErrorValueAsAParameter(err error){<br>   fmt.Println(err.Error())<br>}</pre><pre>//output<br>custom error<br>custom error 2</pre><p><strong><em>Note: error is an interface type, which means values of error type would be of reference type that can be nil when no value is there. It has only one method which returns the error string.</em></strong></p><pre><strong>type </strong>error <strong>interface </strong>{<br>   Error() string<br>}</pre><p>So, to check for error is pretty simple. <strong>We just need to check for nil</strong>, if the value is <strong>nil</strong> then this means there is no error and vice versa.</p><pre>package main<br><br>import (<br>   &quot;errors&quot;<br>   &quot;fmt&quot;<br>)<br><br><br>func main(){<br>   <em>// Creating and assinging error value<br>   </em>myCustomError := errors.New(&quot;custom error&quot;)<br>   if myCustomError != nil {<br>      fmt.Println(myCustomError.Error())<br>   }<br>   myCustomError = nil<br>   if myCustomError != nil {<br>      fmt.Println(&quot;Error is still there&quot;)<br>   }else{<br>      fmt.Println(&quot;Woho, error has gone!&quot;)<br>   }<br>}</pre><pre>//output<br>custom error<br>Woho, error has gone!</pre><p>That is all you need to know about creating and consuming errors for now. let us have a look at some real use cases.</p><p>A simple network call failure example:-</p><pre>import (<br>   &quot;errors&quot;<br>   &quot;fmt&quot;<br>   &quot;http&quot;<br>)<br><br>func main(){<br>   response, err := http.Get(&quot;http://golang.org/&quot;)<br>   if err != nil {<br>      // handle network call failure   <br>   }<br>   // do something with the response.<br>}</pre><p>You can even return this error value from a function making network call.</p><pre>import (<br>   &quot;errors&quot;<br>   &quot;fmt&quot;<br>   &quot;os&quot;<br>   &quot;http&quot;<br>)<br><br>func main(){<br>   data, err := makeNetworkCall(&quot;http://golang.org/&quot;)<br>   if err != nil{<br>       fmt.Println(err.Error())<br>       os.Exit(0) // please do not do this is real case</pre><pre>       // you can also use log.Fatal(err.Error())<br>   }<br>   // parse or do whatever with your response<br>}</pre><pre>func makeNetworkCall(url) ([]byte, error) {<br>   response, err := http.Get(url)<br>   if err != nil {<br>      return nil, err<br>   }<br>   defer response.Body.Close()<br>   dataInBytes := parseBody(response.Body)<br>   // parse body is dummy function, it does not exists in any lib.<br>   // if all goes well<br>   <br>   return dataInBytes, nil<br>   // remember you can assign a nil value to error type because it         is of reference type.</pre><pre>}</pre><p>Similarly, all the builtin libraries return errors when their functions possibly can get fail. So the caller of function know that the respective function can fail and handle the returning error appropriately.</p><p>Few more examples :-</p><p>Opening a file</p><pre>f, err := os.Open(&quot;filename.ext&quot;)<br>if err != nil {<br>    log.Fatal(err)<br>}<br>// do something with the open *File f<br><strong>if</strong> err := f.Close(); err != <strong>nil</strong> {<br>    <strong>return</strong> err<br>}<br>// even closing a file can fail so f.close() also returns an error</pre><p>Marshing and Unmarshling JSON</p><pre>type Message struct {<br>    Name string<br>    Body string<br>}<br>m := Message{&quot;Hello&quot;, &quot;Emumba&quot;}</pre><pre>b, err := json.Marshal(m)</pre><pre>if err != nil { <br>   log.Fatal(err)<br>}</pre><pre>........</pre><pre>var m Message<br>b :=[]byte(`{&quot;Name&quot;:&quot;Hello&quot;,&quot;Body&quot;:&quot;Emumba&quot;}`)<br>err := json.Unmarshal(b, &amp;m)<br>if err != nil {<br>   log.Fatal(err)<br>}</pre><p>etc. There are plenty of more examples out there.</p><p>That is all for this article, it doesn’t cover all about the error handling in Go. There are plenty of more things that need to be cover but these are the basics of error handling in Go for a starter.</p><p>I hope this article is useful to you. Please let me know if you have any comments or suggestions. Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6a4615b7881" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>