<?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 Madhav Chaturvedi on Medium]]></title>
        <description><![CDATA[Stories by Madhav Chaturvedi on Medium]]></description>
        <link>https://medium.com/@csmadhav?source=rss-7de4e15b242d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6eHs86_58ExFSw4kCs5YEA.jpeg</url>
            <title>Stories by Madhav Chaturvedi on Medium</title>
            <link>https://medium.com/@csmadhav?source=rss-7de4e15b242d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:42:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@csmadhav/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[Biggest Multibagger Asset!]]></title>
            <link>https://medium.com/@csmadhav/biggest-multibagger-asset-950b2a902b7f?source=rss-7de4e15b242d------2</link>
            <guid isPermaLink="false">https://medium.com/p/950b2a902b7f</guid>
            <category><![CDATA[life-lessons]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[investment]]></category>
            <category><![CDATA[knowledge]]></category>
            <category><![CDATA[multibagger-stocks]]></category>
            <dc:creator><![CDATA[Madhav Chaturvedi]]></dc:creator>
            <pubDate>Wed, 09 Feb 2022 17:47:12 GMT</pubDate>
            <atom:updated>2022-02-09T17:47:12.279Z</atom:updated>
            <content:encoded><![CDATA[<p>Money makes money isn’t it? Invest in this stock and get 50% return, Invest in this crypto, get 500% return, This penny stock gave 1000% return in 2 years! Everyone has one question:</p><p>Just tell me a multibagger !</p><p>Trust me, today, I am going to tell you a multi-bagger asset, no kidding.</p><p><strong>Knowledge</strong>.</p><p>Old-fashioned eh?</p><p>Not really.</p><p>You think that working in a corporate, Monday to Friday with a decent pay, investing regularly in stock markets, funds, cryptos and everything is fine, life is good. Right? No.</p><p>Investing your money is not enough.</p><p>Let me tell you, world progresses every day, smart people innovate and a lot of new things come into the market everyday. Companies will adopt new technologies, and demand in the job market for older jobs will cut down and your primary source of income will become stagnant at some point in time.</p><h4>Invest in Knowledge</h4><p>You should always look out for new things coming in your domain, be proactive and see where the world is leading to, keep yourself updated, learn new technologies. If you are not convinced, let me give you an example from software engineering field.</p><p>Before the smartphone era, software industry was solving quite rudimentary problems like building basic websites with decent UI, scaling the backend, but when smartphone era came, world started to generate exabytes of data everyday, new problems debuted like how to make sense out of this data at such volume, something called as “Big Data” was introduced and demand for data engineering came out. When big data was settling in the industry, machine learning came out, then blockchain and so on. Result of this was that market was flooded with new heavy paying jobs.</p><p>This is true for all domains and thats why investing in knowledge is so important.</p><p>This thing is so important that Jeff Bezos added this as a leadership principle in Amazon: <a href="https://medium.com/4th-coffee/working-like-an-amazonian-leadership-principles-explained-5-learn-and-be-curious-c96d83fb5d88">Learn and Be Curious</a></p><p>Invest in <em>you.</em></p><p>Believe in <em>you </em>🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=950b2a902b7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event Publishing in Microservice Architecture]]></title>
            <link>https://medium.com/@csmadhav/event-publishing-in-microservice-architecture-468aa221fd87?source=rss-7de4e15b242d------2</link>
            <guid isPermaLink="false">https://medium.com/p/468aa221fd87</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[atomicity]]></category>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Madhav Chaturvedi]]></dc:creator>
            <pubDate>Wed, 12 Aug 2020 21:15:03 GMT</pubDate>
            <atom:updated>2020-08-14T23:02:39.691Z</atom:updated>
            <content:encoded><![CDATA[<p>In Microservice Architecture it is very common to find a use-case where an event triggered in a microservice is to be asynchronously processed by other microservices. Typically in a distributed environment, this problem is solved by simply introducing a message broker. The event is published to a queue that can be consumed by other machines (or services). But this approach comes with a lot of challenges, how to <strong><em>atomically</em></strong> publish our events, or <strong><em>reliably</em></strong> update databases owned by other microservices. In this blog, I am going to introduce a pattern which is adapted to cover these kinds of use-cases, <strong>The Transactional Outbox Pattern.</strong></p><p>Let’s take a simple example, consider three services:</p><ol><li>Card Service: Which is responsible for payment processing of a card transaction.</li><li>Pricing Service: Which calculates how much a merchant earns from that transaction.</li><li>Analytics Service: It is responsible for some analytics on all the transactions happening around in your system.</li></ol><p>Pricing and analytics services need the transaction information which is an <strong><em>Event</em></strong> being generated in card service on a payment request. Obviously we can’t hit pricing and analytics services’ endpoint within the payment request itself since it will impact the latency of that request. We need to do some async communication among the services. We need to introduce a message broker where this transaction will be <strong><em>Published</em></strong> and pricing and analytics service can consume this transaction and do their own processing. But here we will run into a problem if card service fails to push into the queue after creating a payment transaction.</p><p>Let’s jump into some more details related to this problem. One scenario could be payment transaction was successful but pushing to the queue was not maybe because of the unavailability of the queue, where the service is up and running but it was not able to push to the queue. This problem can be easily solved by introducing a mechanism to retry pushing to the queue. There are several retry patterns available for that which is beyond the scope of this article. Another scenario where we are interested in, however, is that what if service itself crashes and loses its context after creating an event, in our case the payment transaction. In this case, once the service will become available again it won’t have the context available to push to the queue and the event will be lost. Traditionally we have <a href="https://en.wikipedia.org/wiki/Two-phase_commit_protocol">two-phase commit protocol</a> (2PC) to overcome this problem but that brings too much complexity onto the table and the solution for this we are about to discuss in this article is quite easy to understand and can reliably publish messages.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FTa7lq6ZMBOqzu%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FTa7lq6ZMBOqzu%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FTa7lq6ZMBOqzu%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/96ed83a85c8df37dfb5663b85df23486/href">https://medium.com/media/96ed83a85c8df37dfb5663b85df23486/href</a></iframe><p>This is called a <strong><em>Saga, </em></strong>a transaction that spans across the microservices, which involves updating multiple databases owned by other microservices and we are trying to solve the problem of atomicity in a saga.</p><p>In the transactional outbox pattern, a microservice inserts an event to a database table called an <strong>outbox table</strong><em> </em>which is closely monitored by a process called a <strong>message relay</strong><em>. </em>Message relay listens for changes in the outbox table and whenever a change is detected by this process, it publishes this event to a message broker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*tf-qJmEs6UdaSBvql-nVnQ.png" /><figcaption>Transactional outbox pattern</figcaption></figure><p>Insertion into the outbox table should happen in a single database transaction. Let’s assume there is a payments table in the card service, in the database transaction where insertion to payments table is happening, should insert into an outbox table also. Let’s name the outbox table as “transaction_events”</p><blockquote>A NoSQL database can insert as a property inside a record. Maybe a very common requirement, but here we are depending on the ACID property of a database and if any database in the world doesn’t guarantee atomicity, it can’t be used. (if that kind of database exists).</blockquote><p>A message relay should monitor this outbox table and should take responsibility for pushing an event always and exactly once to the message broker. There can be multiple approaches to implement a message relay:</p><ol><li>Transaction Log Tailing Pattern</li><li>Polling Publisher Pattern</li></ol><p>In transaction log tailing pattern, process listens to database logs like write-ahead logs (WAL log), bin logs, streams, etc, and act accordingly. While in polling publisher pattern, the process simply polls the outbox table.</p><p>AWS DMS can be used as a message relay if you are on the cloud and <a href="https://github.com/eventuate-tram/eventuate-tram-core">Eventuate Tram</a> is an open-source project that can help you otherwise.</p><p>Further, in our example, pricing and analytics services can simply consume this queue to process the payment transaction.</p><p>This pattern talks about a lot of major issues we face when we move to microservice architecture and understanding of this explores a lot of challenges related to it.</p><p>Hope this article helps your use-case.</p><p>References:</p><ol><li><a href="https://microservices.io/patterns/data/transactional-outbox.html">https://microservices.io/patterns/data/transactional-outbox.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=468aa221fd87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to mock current time in GoLang]]></title>
            <link>https://medium.com/@csmadhav/how-to-mock-current-time-in-golang-fb91007124e?source=rss-7de4e15b242d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb91007124e</guid>
            <category><![CDATA[test]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Madhav Chaturvedi]]></dc:creator>
            <pubDate>Sun, 30 Jun 2019 21:01:33 GMT</pubDate>
            <atom:updated>2019-07-01T06:36:29.553Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KqGaijWcjAnjzP5aaJk9GQ.jpeg" /><figcaption>time.Now()</figcaption></figure><h4>Introduction</h4><p>While I was writing unit test cases in my go programs I got stuck in a place where I needed to mock the current time the time.Now() function in Golang. The problem arises function under test calls time.Now() and your test tries to assert the value returned by this function. In this blog, I am going to discuss my solution to this problem using monkey patch approach and using a simple wrapper, Choose what&#39;s best for you!</p><p>For working code for this tutorial check out <a href="https://github.com/csmadhav/mock-time-demo">this</a>.</p><h4>Caution!</h4><p>You should use monkey patch in a test environment and only WHEN YOU NEED IT!, It may occur to you that you may really need to use time.Now() and then you should not use monkey patch! You should make sure that the test functions which really need the mocking should ONLY use this approach.</p><h4>Time matters!</h4><p>Imagine you are creating a transaction, you created a service file where you create a transaction struct and pass it to datastore. while you do this you create your transaction’s submission time using time.Now()</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74e0f782bb476598d72b88c417bd0a69/href">https://medium.com/media/74e0f782bb476598d72b88c417bd0a69/href</a></iframe><p>the test file contains the setup test function where you perform all the setup for your test function since here you need to mock the datastore interactions. ‘Create’ function of your datastore service accepts a transaction object. When you try to mock it and run it without mocking time.Now() you will face something like this (You can run the test in the GitHub repo using branch “without-monkey-patch”):</p><pre>--- Expected</pre><pre>+++ Actual</pre><pre>@@ -3,3 +3,3 @@</pre><pre>Amount: (int) 100,</pre><pre>- SubmissionTime: (time.Time) 2019-07-01 01:38:31.060511 +0530 IST m=+0.002901756</pre><pre>+ SubmissionTime: (time.Time) 2019-07-01 01:38:31.060579 +0530 IST m=+0.002969902</pre><pre>}</pre><p>This happens because there is SOME lag when your code runs in a test environment and main code. Here expected time is less because we created time mock before in the setup test and the actual time is created in the main code.</p><p><a href="https://github.com/bouk/monkey">Monkey</a> comes to the rescue!</p><p>With this Go package, you can replace time.Now() with your implementation.</p><pre>monkey.Patch(time.Now, func() time.Time {</pre><pre>return time.Date(2009, 11, 17, 20, 34, 58, 651387237, time.UTC)</pre><pre>})</pre><p>When control comes to the above line, the time.Now will point to this given function so it will always return 17th November 2009 (some time) no matter when you call it after patching.</p><h4>How does it work?</h4><p>Monkey patching is the technique where you can modify the current packages you have for your currently running instance only. This is done using unsafe package in Go, you can replace the address of the function time.Now() in the memory with your function’s address on runtime.</p><p>You should check out the original blog <a href="https://bou.ke/blog/monkey-patching-in-go/">here</a> for more explanation.</p><h4>Another Solution</h4><p>You can create your own wrapper around time.Now() and store it in a variable and override it with some mock wrapper in the test environment. Easy-peasy right? but then you need to import to other packages which will create dependency issues maybe? You can solve it by making a commons package and put your wrapper there but if you are in the middle of your project then you might need to change the usage of time.Now() with your wrapper.</p><p>Pick whichever approach suits you best! no personal opinions here!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb91007124e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Awesomeness of GoLang + AWS Lambda]]></title>
            <link>https://medium.com/@csmadhav/awesomeness-of-golang-aws-lambda-d6bd08131117?source=rss-7de4e15b242d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6bd08131117</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Madhav Chaturvedi]]></dc:creator>
            <pubDate>Wed, 22 Aug 2018 21:22:29 GMT</pubDate>
            <atom:updated>2018-08-22T21:35:56.020Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*kq4txOodYgH6Mdv3y_1cgQ.png" /></figure><p>Thinking to write serverless microservices on cloud so that you can scale?</p><p>Lambda is a good tool isn’t it?</p><p>GoLang’s simplicity and performance is great!</p><p>Don’t tell me? Lambda supports Go?</p><p>I can tell you how you can start development right away, run your Go programs locally and then deploy to the cloud and moreover debug your lambda functions on the cloud YAY!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*1OZTKA_LCx_YZGnnrODhyw.gif" /></figure><p>Why it is really so much important to optimize you Lambda’s total execution time? Don’t forget you will be billed for every millisecond your lambda function spends. Although in AWS free tier, Lambda has quite huge limits but even then lambda’s response time will matter!</p><p>I am going to show you how easily you can trigger Lambda function on a SNS event and then doing CRUD operations with it in DynamoDB.</p><p>I started writing lambda functions when I started building Amazon Alexa skills in node.js, I used <a href="https://claudiajs.com/">claudia.js</a> for the deployment and used <a href="https://www.npmjs.com/package/lambda-local">lambda-local</a> (for a very stupid reason I didn’t use Serverless framework in place of claudia, But hold on! I later switched to it!), Then AWS announced support for Go and when I compared the memory and execution time (Node and Go), there was a significantly HUGE difference!</p><p>Okay, so here’s how I did it,</p><p>I used these ingredients: ( You need to install these if you are following this tutorial )</p><ol><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/serverless_app.html">AWS SAM</a> ( Because serverless framework doesn’t support running Lambda function on local for Go, requires Docker!)</li><li><a href="https://serverless.com/">ServerLess framework</a> ( A fantastic framework to develop and deploy lambda functions to the cloud, can be installed using NPM )</li><li><a href="https://aws.amazon.com/cli/">AWS CLI</a> (Install using pip)</li><li><a href="https://github.com/golang/dep">Dep</a> ( Go’s dependency manager )</li></ol><blockquote>There are multiple triggers for lambda function most common one is from API gateway. For every trigger, event for our lambda function will change. I used SNS trigger because I want to show off. You can follow similar procedure for all other trigger</blockquote><p>Okay follow me, this way!</p><p><strong>Step 1: Make IAM user, Its important don’t use root credentials or AdministrativeAccess permission </strong>😤<strong>!</strong></p><blockquote>You can simply assign Administrative access policy and move on with this step but I don’t like this at all! I prefer to keep access restricted and I make sure that my IAM user has only those permission which are really required.</blockquote><p>Make an IAM user give it a nice name, select programmatic access and assign following policies to it.</p><ol><li>AWSLambdaFullAccess</li><li>IAMFullAccess</li><li>AWSCloudFormationFullAccess ( You need to create this policy explained below )</li></ol><p>“AWSCloudFormationFullAccess” policy is made by me, to create this you can click on “Attach existing policies directly”&gt;&gt;”Create Policy” &gt;&gt; “JSON” and add this JSON:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor0&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;cloudformation:DescribeStackEvents&quot;,<br>                &quot;cloudformation:CreateStack&quot;,<br>                &quot;cloudformation:GetTemplate&quot;,<br>                &quot;cloudformation:DescribeStackResources&quot;,<br>                &quot;cloudformation:ValidateTemplate&quot;,<br>                &quot;cloudformation:DescribeStacks&quot;,<br>                &quot;cloudformation:DescribeStackResource&quot;,<br>                &quot;cloudformation:UpdateStack&quot;,<br>                &quot;cloudformation:DeleteStack&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        }<br>    ]<br>}</pre><p>Just to clarify IAMFullAccess is needed to create the role to run the Lambda function. ( If you come up with a limited access for this one then please mention in the comments! )</p><p>Needless to say add credentials of this IAM user to the file ~/.aws/credentials, So that serverless framework could use this credentials</p><blockquote>Psst! You can add multiple profiles to credentials file and you can choose which profile to use by giving profile name by --profile option of serverless.</blockquote><p><strong>Step 2: Run serverless create command</strong></p><pre>serverless create -t aws-go-dep -p tars</pre><p>aws-go-dep is the Go template for serverless, tars is the service name which we are going to build. This command will locally create a serverless project.</p><p>This command will make two functions “hello” and “world”, we are making only function so lets delete one function by deleting world directory and renaming hello to tars, open ./serverless.yml file and change hello to tars and you should see something like ( remove world attribute ):</p><pre>provider:<br>  name: aws<br>  runtime: go1.x<br>  region: ap-south-1 # Preferred AWS region here<br>  stage: dev # default stage</pre><pre>functions:<br>  tars:<br>    handler: bin/tars</pre><p>After compiling Go programs the respective binaries will be stored in bin directory, since we are building only one lambda function you will see only one binary named tars in ./bin</p><p>you need to change ./Makefile as well :</p><pre>build:<br>  dep ensure<br>  env GOOS=linux go build -ldflags=&quot;-s -w&quot; -o bin/tars tars/main.go</pre><p><strong>Step 3: Coding time</strong></p><p>Let’s develop a small program which will recieve the SNS event, logs it on Cloudwatch and inserts, updates and deletes items in DynamoDB.</p><blockquote>BTW which code editor would you prefer to write Go programs? drop in the comments section below, I prefer VSCode, GoLand takes hell lot of memory and irritates, Choosing a right code editor is important as it increases your efficiency, What do you think? Also! never bound to any editor, experiment around and choose which one is best comfortable for YOU!</blockquote><p>File: [PROJECT_ROOT]/tars/main.go</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23a410618f4c586ca11a92b8544f9ba7/href">https://medium.com/media/23a410618f4c586ca11a92b8544f9ba7/href</a></iframe><p><strong>Step 4: Running it locally</strong></p><p>To make your program run locally you need to pass a JSON as a SNS event to our program, save a JSON file named tars/event.json.</p><pre>{<br>  &quot;Records&quot;: [<br>    {<br>      &quot;EventVersion&quot;: &quot;1.0&quot;,<br>      &quot;EventSubscriptionArn&quot;: &quot;arn:aws:sns:EXAMPLE&quot;,<br>      &quot;EventSource&quot;: &quot;aws:sns&quot;,<br>      &quot;Sns&quot;: {<br>        &quot;SignatureVersion&quot;: &quot;1&quot;,<br>        &quot;Timestamp&quot;: &quot;1970-01-01T00:00:00.000Z&quot;,<br>        &quot;Signature&quot;: &quot;EXAMPLE&quot;,<br>        &quot;SigningCertUrl&quot;: &quot;EXAMPLE&quot;,<br>        &quot;MessageId&quot;: &quot;95df01b4-ee98-5cb9-9903-4c221d41eb5e&quot;,<br>        &quot;Message&quot;: &quot;{ \&quot;operation\&quot; : \&quot;CREATE\&quot;, \&quot;id\&quot; : 1, \&quot;data\&quot; : \&quot;Some awesome data\&quot; }&quot;,<br>        &quot;MessageAttributes&quot;: {<br>          &quot;Test&quot;: {<br>            &quot;Type&quot;: &quot;String&quot;,<br>            &quot;Value&quot;: &quot;TestString&quot;<br>          },<br>          &quot;TestBinary&quot;: {<br>            &quot;Type&quot;: &quot;Binary&quot;,<br>            &quot;Value&quot;: &quot;TestBinary&quot;<br>          }<br>        },<br>        &quot;Type&quot;: &quot;Notification&quot;,<br>        &quot;UnsubscribeUrl&quot;: &quot;EXAMPLE&quot;,<br>        &quot;TopicArn&quot;: &quot;arn:aws:sns:EXAMPLE&quot;,<br>        &quot;Subject&quot;: &quot;TestInvoke&quot;<br>      }<br>    }<br>  ]<br>}</pre><p>Notice the message JSON which will be parsed by our program and data part will be inserted or updated in DynamoDB.</p><p>You also need to create template.yml file required for SAM for all its configration about your lambda function separately.</p><pre>Resources:<br>  tars:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      Handler: bin/tars<br>      Runtime: go1.x</pre><p>You now need to first create a dynamoDB table in your preferred region, I used ‘ap-south-1’, as you can see in the code I named the table as ‘tars-test’, also the primary key was set to id “Number” field, And then run this command to make a build and running it locally:</p><pre>make &amp;&amp; sam local invoke tars --event tars/event.json</pre><p>If everything goes well you should see something like this:</p><pre>dep ensure<br>env GOOS=linux go build -ldflags=&quot;-s -w&quot; -o bin/tars tars/main.go<br>2018/04/03 22:53:40 Successfully parsed template.yml<br>2018/04/03 22:53:40 Connected to Docker 1.37<br>2018/04/03 22:53:40 Fetching lambci/lambda:go1.x image for go1.x runtime...<br>go1.x: Pulling from lambci/lambda<br>Digest: sha256:c92d36b1cd07dfdeb2f9623cbd520e40fcad780262fc872ad1b4a93cd1593ef9<br>Status: Image is up to date for lambci/lambda:go1.x<br>2018/04/03 22:53:48 Invoking bin/tars (go1.x)<br>2018/04/03 22:53:48 Mounting /home/madhav/go/src/tars as /var/task:ro inside runtime container<br>START RequestId: d303a256-c864-1cde-334e-62aa896cfe44 Version: $LATEST<br>SNS Event received: {&quot;Records&quot;:[{&quot;EventVersion&quot;:&quot;1.0&quot;,&quot;EventSubscriptionArn&quot;:&quot;arn:aws:sns:EXAMPLE&quot;,&quot;EventSource&quot;:&quot;aws:sns&quot;,&quot;Sns&quot;:{&quot;Signature&quot;:&quot;EXAMPLE&quot;,&quot;MessageId&quot;:&quot;95df01b4-ee98-5cb9-9903-4c221d41eb5e&quot;,&quot;Type&quot;:&quot;Notification&quot;,&quot;TopicArn&quot;:&quot;arn:aws:sns:EXAMPLE&quot;,&quot;MessageAttributes&quot;:{&quot;Test&quot;:{&quot;Type&quot;:&quot;String&quot;,&quot;Value&quot;:&quot;TestString&quot;},&quot;TestBinary&quot;:{&quot;Type&quot;:&quot;Binary&quot;,&quot;Value&quot;:&quot;TestBinary&quot;}},&quot;SignatureVersion&quot;:&quot;1&quot;,&quot;Timestamp&quot;:&quot;1970-01-01T00:00:00Z&quot;,&quot;SigningCertUrl&quot;:&quot;EXAMPLE&quot;,&quot;Message&quot;:&quot;{ \&quot;operation\&quot; : \&quot;CREATE\&quot;, \&quot;id\&quot; : 1, \&quot;data\&quot; : \&quot;Some awesome data\&quot; }&quot;,&quot;UnsubscribeUrl&quot;:&quot;EXAMPLE&quot;,&quot;Subject&quot;:&quot;TestInvoke&quot;}}]}<br>Message { &quot;operation&quot; : &quot;CREATE&quot;, &quot;id&quot; : 1, &quot;data&quot; : &quot;Some awesome data&quot; } Subject TestInvoke<br>END RequestId: d303a256-c864-1cde-334e-62aa896cfe44<br>REPORT RequestId: d303a256-c864-1cde-334e-62aa896cfe44 Duration: 805.34 ms Billed Duration: 900 ms Memory Size: 128 MB Max Memory Used: 14 MB <br>null</pre><p>Hopefully you should see last line, the REPORT line in green and shouldn’t see anything in red, by any chance you’ve encountered any errors checkout the call stack and the error message, there might be some issues with your code.</p><p>So now lets take a deep breath and let me explain you what happened there.</p><p>First part is the make command, It is used to make binaries for your program and MakeFile is used to tell make command how to make a build. As you might have seen the first line in MakeFile is dep ensure, it’s the dep’s ( The dependency manager of Go ) command to fetch all the dependencies for your code and save it in ‘vendor’ directory similar to composer with PHP ( and node_modules directory in case of NPM ). Now, in the next line when go build command is executed it will include all the dependencies from the vendor directory. On the other hand when you just write a simple go program in a scenario where you are not using dep and you need to import a dependency which doesn’t exists in your system, you do go get … which gets the dependencies and saves globally in GOPATH and when you build, it fetches from GOPATH. The best explanation about the difference between using dep ensure and go get ... is <a href="https://github.com/golang/dep/issues/1400">here</a>.</p><p>Second, you invoked sam command and invoked ‘tars’ lambda function with an event object defined in tars/event.json . Notice SNS Event received: is printed in the output which was executed by fmt.Println in our program, you will see this logged on cloudwatch when we will excute it on cloud.</p><p>You should see item in your DynamoDB table till now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*xILDysXeWfHCbP_DfCIFGQ.png" /><figcaption>Go to items of your dynamoDB table and then click on the id attribute of your item.</figcaption></figure><p>We are now all set to run our program on cloud! 😋.</p><p><strong>Step 5: Deploy it to the cloud</strong></p><p>Run this command to deploy it on your cloud.</p><pre>sls deploy</pre><p>Output:</p><pre>Serverless: Packaging service...<br>Serverless: Excluding development dependencies...<br>Serverless: Creating Stack...<br>Serverless: Checking Stack create progress...<br>.....<br>Serverless: Stack create finished...<br>Serverless: Uploading CloudFormation file to S3...<br>Serverless: Uploading artifacts...<br>Serverless: Uploading service .zip file to S3 (3.12 MB)...<br>Serverless: Validating template...<br>Serverless: Updating Stack...<br>Serverless: Checking Stack update progress...<br>...............<br>Serverless: Stack update finished...<br>Service Information<br>service: tars<br>stage: dev<br>region: ap-south-1<br>stack: tars-dev<br>api keys:<br>  None<br>endpoints:<br>  None<br>functions:<br>  tars: tars-dev-tars</pre><p>Navigate to AWS console on to your browser, make sure right region is selected.</p><p>You need to create a SNS topic which will trigger your lambda function. I named it ‘tars-test’. Now create a subscription to this topic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*PUMIeS3pPF0DRXO9kykuzA.png" /><figcaption>Subscribe to a topic</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*EkL9iziEF0w9s0_TdvYDSQ.png" /><figcaption>Set protocol as Lambda and endpoint to the ARN of your lambda function.</figcaption></figure><p>And you are done.</p><p>To validate that you have indeed configured your lambda function currently, go to lambda service, click on hamburger menu and then on functions. You should see your lambda function! click on it. In configuration tab, in the designer section, you should see one SNS trigger already configured. Click on it to see its ARN.</p><p>You also need to give access to DynamoDB to the execution role which lambda function uses, checkout execution role panel of your lambda function, you can see the IAM role name which is used by the lambda function while execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*TCr7w-xag_Cq02WBbQ3X0A.png" /></figure><p>To do this simply navigate to IAM Roles, select above shown role and then attach policy “AmazonDynamoDBFullAccess”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*Rl25RMVniDcoRcHJhmLXxg.png" /></figure><p><strong>Step 6: Run it!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/0*JGAExMcJB56YteIN.gif" /><figcaption>THE GAME IS ON!</figcaption></figure><p>Go to SNS on your console, select your topic you’ve just created and click publish to this topic, set message to this JSON:</p><pre>{ <br>    &quot;operation&quot; : &quot;CREATE&quot;, <br>    &quot;id&quot; : 1, <br>    &quot;data&quot; : &quot;Some awesome data&quot; <br>}</pre><p>PUBLISH!</p><p>Checkout cloudwatch logs for logs of the execution of lambda function and to debug if any there is any error while executing your lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wkioKsHYxnyIZj-NumcxVQ.png" /><figcaption>CloudWatch logs</figcaption></figure><p>Ohh! its Orgasmic :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6bd08131117" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>