<?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 Budvin Chathura on Medium]]></title>
        <description><![CDATA[Stories by Budvin Chathura on Medium]]></description>
        <link>https://medium.com/@budvin?source=rss-871f67af159a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ks7Q2CLX3-oy0VIFeIrf7g.jpeg</url>
            <title>Stories by Budvin Chathura on Medium</title>
            <link>https://medium.com/@budvin?source=rss-871f67af159a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:37:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@budvin/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[From Control Dependencies to Data Dependencies]]></title>
            <link>https://budvin.medium.com/from-control-dependencies-to-data-dependencies-45359293ac24?source=rss-871f67af159a------2</link>
            <guid isPermaLink="false">https://medium.com/p/45359293ac24</guid>
            <category><![CDATA[perf]]></category>
            <category><![CDATA[control-dependency]]></category>
            <category><![CDATA[data-dependency]]></category>
            <category><![CDATA[cmov]]></category>
            <category><![CDATA[branchless-programming]]></category>
            <dc:creator><![CDATA[Budvin Chathura]]></dc:creator>
            <pubDate>Tue, 07 Jun 2022 13:25:17 GMT</pubDate>
            <atom:updated>2022-06-07T13:30:44.763Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*muRK-Ez8Kx6LrxzXFrB9dg.jpeg" /><figcaption>Source: <a href="https://www.youtube.com/watch?v=Ma08iHI3e2c">https://www.youtube.com/watch?v=Ma08iHI3e2c</a></figcaption></figure><h4>Introduction to Branchless Programming</h4><p>I recently watched few CppCon sessions and I was inspired by the talk <a href="https://www.youtube.com/watch?v=g-WPhYREFjk">Branchless Programming in C++</a> by Fedor Pikus, to write this article.</p><p>Modern computer processors are well capable of executing programs efficiently using pipelining, super-scalar execution and multi-threading. Modern compilers are also “smart” enough to optimize the machine code to obtain the best possible performance with underlying hardware. However, not every program can be 100% pipelined or multithreaded. Often, the dependencies between instructions are the main reason. Usually there are 2 types of such dependencies.</p><ul><li>Data dependencies</li><li>Control dependencies</li></ul><p>In simple terms, data dependency is where several instructions access the same register to read write data. The behavior of the program is decided according to the user defined order of accessing such shared register. Control dependency is where the execution of a particular instruction depends on the result of another instruction. Usually it is a branch instruction followed by other instructions.</p><p>Depending on the type of the data dependency, it can be handled using register renaming, reorder buffers and mechanisms like Tomasulo’s algorithm. When it comes to control dependencies, the commonly used method for efficient execution branch prediction. Branch prediction can vary from 1 bit simple branch predictors to more complex multi-level or intelligent branch predictors. In branch prediction, if a predicted branch is wrong, things get ugly. The processor has to flush the pipeline to remove any intermediate results and restart from the correct instruction order.</p><p>In this article we will see if there are any significant differences between data dependencies and control dependencies for the same logic in the program code.</p><p>First let’s see what are the modern branch predictors are capable of. For each of the following experiments I used a simple driver program written in C. It implements a loop for 1000000000 times and executes an if statement in each iteration. I used perf (<a href="https://perf.wiki.kernel.org/">https://perf.wiki.kernel.org/</a>) to get the information about branch misses, execution time and other data.</p><p>The following code has an if statement that has the outcome pattern T T F F F T T F F F….</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#define ITER_N 1000000000</pre><pre>int main(int argc, char const *argv[]) {</pre><pre>    int ans = 0;</pre><pre>    for (size_t iter_i = 0; iter_i &lt; ITER_N; iter_i++) {<br>        /*<br>         * branch pattern  T T F F F T T F F F<br>         */<br>        if ((iter_i % 5) &lt;= 1) {<br>            ans += iter_i;<br>        } else {<br>            ans += iter_i / 2;<br>        }<br>    }<br>    printf(&quot;ans = %d\n&quot;, ans);</pre><pre>    return 0;<br>}</pre><p>perf stat returns following information</p><pre>2,011.21 msec task-clock                #    1.000 CPUs utilized          <br>                 6   context-switches   #    2.983 /sec                   <br>                 1   cpu-migrations     #    0.497 /sec                   <br>                54   page-faults        #   26.850 /sec                   <br>     8,340,214,561   cycles             #    4.147 GHz                    <br>    21,002,898,727   instructions       #    2.52  insn per cycle         <br>     2,400,529,540   branches           #    1.194 G/sec                  <br>            25,129   branch-misses      #    0.00% of all branches</pre><pre>2.012005863 seconds time elapsed</pre><pre>2.011604000 seconds user<br>0.000000000 seconds sys</pre><p>Out of 2 billion branch instructions there are only around 25K branch misses. So it is fair to say that branch predictor did a good job here.</p><p>Next we will see a little more complicated outcome pattern. The following if condition has the pattern T T F T F F F T T F T F F F T T F T F F F ….</p><pre>/*<br> * branch pattern  T T F T F F F T T F T F F F T T F T F F F<br> */<br>if ((iter_i % 7) &lt;= 1 || (iter_i % 7 == 3)) {<br>    ans += iter_i;<br>} else {<br>    ans += iter_i / 2;<br>}</pre><p>perf stat returns the following statistics.</p><pre>2,709.33 msec task-clock                #    0.999 CPUs utilized          <br>                34   context-switches   #   12.549 /sec                   <br>                 2   cpu-migrations     #    0.738 /sec                   <br>                54   page-faults        #   19.931 /sec                   <br>    11,108,985,851   cycles             #    4.100 GHz                    <br>    36,432,755,309   instructions       #    3.28  insn per cycle         <br>     3,143,627,532   branches           #    1.160 G/sec                  <br>            32,688   branch-misses      #    0.00% of all branches</pre><pre>2.711987299 seconds time elapsed</pre><pre>2.710903000 seconds user<br>0.000000000 seconds sys</pre><p>Here also the branch miss rate is below 0.01% of total branches.</p><blockquote>Branch predictor managed to identify the pattern T T F T F F F T T F T F F F T T F T F F F even though it was slightly complex.</blockquote><p>Now we will see what happens when we implement a branch instruction with unpredictable outcome. For this, in each iteration I generate a random integer and check whether it is even or odd. With that there is a 50–50 chance of taking the branch.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#define ITER_N 1000000000</pre><pre>int main(int argc, char const *argv[])<br>{</pre><pre>    int ans = 0;<br>    int number;<br>    srand(42);</pre><pre>    for (size_t iter_i = 0; iter_i &lt; ITER_N; iter_i++)<br>    {<br>        /*<br>         * branch pattern not predictable<br>         */<br>        number = rand();<br>        if (number % 2)<br>        {<br>            ans += iter_i;<br>        }<br>        else<br>        {<br>            ans += iter_i / 2;<br>        }<br>    }<br>    printf(&quot;ans = %d\n&quot;, ans);</pre><pre>    return 0;<br>}</pre><p>perf stat gives the following information.</p><pre>11,548.05 msec task-clock                #    1.000 CPUs utilized          <br>                56   context-switches    #    4.849 /sec                   <br>                 1   cpu-migrations      #    0.087 /sec                   <br>                53   page-faults         #    4.590 /sec                   <br>    49,365,449,710   cycles              #    4.275 GHz                    <br>    76,885,692,071   instructions        #    1.56  insn per cycle         <br>    18,405,840,263   branches            #    1.594 G/sec                  <br>       564,409,901   branch-misses       #    3.07% of all branches</pre><pre>11.550121994 seconds time elapsed</pre><pre>11.549105000 seconds user<br> 0.000000000 seconds sys</pre><p>This time we have a branch miss rate of 3%. You might think this is not significant but observe the elapsed time for the program. For fair comparison I executed the same code with random number generation but without the if-else block. That version had around 6 seconds of total execution time. But with the branch misses, this version reports an execution time of 11 seconds. That is the cost we pay for incorrect branch prediction.</p><blockquote>Execution time almost doubled with 3% branch miss rate. Imagine the execution time if we had a branch miss rate more than 10%.</blockquote><p>To make things more clearer, following is the annotated report generated with perf(you can generate this report with perf record command followed by perf annotate command). It shows the number of branch-miss events associated with each instruction. (Left hand column denotes the branch-miss count.)</p><pre>                        <br>                 Disassembly of section .text:<br>                         <br>                 0000000000001189 &lt;main&gt;:<br>                 main():        <br>                 #include &lt;stdio.h&gt;<br>                 #include &lt;stdlib.h&gt;<br>                 #define ITER_N 1000000000<br>                         <br>                 int main(int argc, char const *argv[])<br>                 {              <br>                   endbr64            <br>                   push    %rbp       <br>                   mov     %rsp,%rbp  <br>                   sub     $0x20,%rsp <br>                   mov     %edi,-0x14(%rbp)<br>                   mov     %rsi,-0x20(%rbp)<br>                         <br>                 int ans = 0;   <br>                   movl    $0x0,-0x10(%rbp)<br>                 int number;    <br>                 srand(42);     <br>                   mov     $0x2a,%edi <br>                 → callq   srand@plt  <br>                         <br>                 for (size_t iter_i = 0; iter_i &lt; ITER_N; iter_i++)<br>                   movq    $0x0,-0x8(%rbp)<br>                 ↓ jmp     66         <br>                 {              <br>                 /*             <br>                 * branch pattern not predictable<br>                 */             <br>                 number = rand();<br>             2e: → callq   rand@plt   <br>    5904435        mov     %eax,-0xc(%rbp)<br>                 if (number % 2)<br>                   mov     -0xc(%rbp),%eax<br>   11783062        and     $0x1,%eax  <br>      43297        test    %eax,%eax  <br>                 ↓ je      50         <br>                 {              <br>                 ans += iter_i; <br>      57951        mov     -0x8(%rbp),%rax<br>   27722080        mov     %eax,%edx  <br>      29251        mov     -0x10(%rbp),%eax<br>     118293        add     %edx,%eax  <br>   32036002        mov     %eax,-0x10(%rbp)<br>  182895209      ↓ jmp     61         <br>                 }              <br>                 else           <br>                 {              <br>                 ans += iter_i / 2;<br>     102344  50:   mov     -0x8(%rbp),%rax<br>   22806204        shr     %rax       <br>   27633391        mov     %eax,%edx  <br>     259912        mov     -0x10(%rbp),%eax<br>      21004        add     %edx,%eax  <br>  142245868        mov     %eax,-0x10(%rbp)<br>                 for (size_t iter_i = 0; iter_i &lt; ITER_N; iter_i++)<br>   51492589  61:   addq    $0x1,-0x8(%rbp)<br>   11733686  66:   cmpq    $0x3b9ac9ff,-0x8(%rbp)<br>    1485196      ↑ jbe     2e         <br>                 }              <br>                 }              <br>                 printf(&quot;ans = %d\n&quot;, ans);<br>                   mov     -0x10(%rbp),%eax<br>                   mov     %eax,%esi  <br>                   lea     _IO_stdin_used+0x4,%rdi<br>                   mov     $0x0,%eax  <br>                 → callq   printf@plt <br>                         <br>                 return 0;      <br>                   mov     $0x0,%eax  <br>                 }              <br>                   leaveq             <br>                 ← retq</pre><p>We can see that the instructions inside if block and else block accounts for majority of the branch misses. This is solely because the branch outcome is so random that the branch predictor is not capable of identifying a correct pattern.</p><h3>Applying Branchless Programming Technique</h3><p>So how can we optimize this with branchless technique? Following is the branchless programming technique applied to the same logic.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#define ITER_N 1000000000</pre><pre>int main(int argc, char const *argv[])<br>{</pre><pre>    int ans = 0;<br>    int number;<br>    int additions[2] = {0, 0};<br>    int branch_result;<br>    srand(42);</pre><pre>    for (size_t iter_i = 0; iter_i &lt; ITER_N; iter_i++)<br>    {<br>        /*<br>         * branchless version<br>         */<br>        number = rand();<br>        additions[0] = iter_i / 2;<br>        additions[1] = iter_i;<br>        branch_result = (number % 2);</pre><pre>        ans += additions[branch_result];<br>    }<br>    printf(&quot;ans = %d\n&quot;, ans);</pre><pre>    return 0;<br>}</pre><p>Essentially what we do is we transform control dependencies into data dependencies. In this specific example, the branch outcome decides what is added to the ans variable. So we keep those 2 possible values</p><ul><li>iter_i</li><li>(iter_i)/2</li></ul><p>in some place (here in an array called additions). Then we remove the if-else construct. Instead of that, we test the branch condition manually and keep the result in another variable branch_result. Then finally we choose the correct value from additions array using the value of branch_result.</p><p>Let’s observe the report generated by perf stat for this code.</p><pre>6,565.04 msec task-clock                #    0.999 CPUs utilized          <br>                27   context-switches   #    4.113 /sec                   <br>                 2   cpu-migrations     #    0.305 /sec                   <br>                52   page-faults        #    7.921 /sec                   <br>    27,569,132,701   cycles             #    4.199 GHz                    <br>    82,878,908,427   instructions       #    3.01  insn per cycle         <br>    16,904,634,658   branches           #    2.575 G/sec                  <br>        32,312,415   branch-misses      #    0.19% of all branches</pre><pre>6.570007460 seconds time elapsed</pre><pre>6.565850000 seconds user<br>       0.000000000 seconds sys</pre><p>With the branchless technique we can clearly see the branch miss rate has been reduced to 0.19%. Although the reduction is small, observe the elapsed time. The time has been reduced to 6 seconds from earlier 11 seconds. That is almost 2X speedup. This is the advantage of using branchless technique rather than using conventional if-else blocks.</p><h3>Should I optimize my if-else constructs like this by manually modifying the code?</h3><p>Not always. So far, for all the code segments above, I used the usual gcc compilation without additional optimizations. However if you re-compile the code which had significant branch miss rate (3%), with optimization enabled, you get a better execution time. Following is the perf stat report for that gcc optimized code.</p><pre>6,602.75 msec task-clock                #    1.000 CPUs utilized          <br>                28   context-switches   #    4.241 /sec                   <br>                 4   cpu-migrations     #    0.606 /sec                   <br>                54   page-faults        #    8.178 /sec                   <br>    27,796,427,314   cycles             #    4.210 GHz                    <br>    72,878,741,658   instructions       #    2.62  insn per cycle         <br>    16,904,607,596   branches           #    2.560 G/sec                  <br>        32,304,814   branch-misses      #    0.19% of all branches</pre><pre>6.604396945 seconds time elapsed</pre><pre>6.604120000 seconds user<br>0.000000000 seconds sys</pre><p>We can see that the report is almost identical to our branchless version. The reason is, with optimization flags enabled, gcc also does the same optimization strategy we applied for the branchless version. However gcc does that with a dedicated cmove instruction. Following is the disassembly and the annotated branch miss count of that code.</p><pre>Disassembly of section .text:<br>                         <br>                 0000000000001189 &lt;main&gt;:<br>                 main():        <br>                   endbr64            <br>                   push    %rbp       <br>                   push    %rbx       <br>                   sub     $0x8,%rsp  <br>                   mov     $0x2a,%edi <br>                 → callq   srand@plt  <br>                   mov     $0x0,%ebp  <br>                   mov     $0x0,%ebx  <br>             1e: → callq   rand@plt   <br>   10730709        mov     %eax,%edx  <br>        123        mov     %rbp,%rax  <br>                   shr     %rax       <br>    3104309        add     %ebx,%eax  <br>    3922878        add     %ebp,%ebx  <br>                   test    $0x1,%dl   <br>                   cmove   %eax,%ebx  <br>     129379        add     $0x1,%rbp  <br>     643845        cmp     $0x3b9aca00,%rbp<br>                 ↑ jne     1e         <br>                   mov     %ebx,%edx  <br>                   lea     _IO_stdin_used+0x4,%rsi<br>                   mov     $0x1,%edi  <br>                   mov     $0x0,%eax  <br>                 → callq   __printf_chk@plt<br>                   mov     $0x0,%eax  <br>                   add     $0x8,%rsp  <br>                   pop     %rbx       <br>                   pop     %rbp       <br>                 ← retq</pre><p>You can see that there are no jump instructions related to the if-else block. Instead we have cmove instruction. cmove is one instruction from cmov instruction group (<a href="https://www.felixcloutier.com/x86/cmovcc">https://www.felixcloutier.com/x86/cmovcc</a>). Specifically, cmove moves a value from source to destination only if the zero flag is set (ZF=1). cmove is usually added to transform control dependencies to data dependencies.</p><h3>So, should we always use branchless method instead of if-else?</h3><p>When choosing either technique, you should consider your use case and run adequate profiling and benchmarking tests to decide on a method. Compilers also consider those facts when deciding to use cmove instead of branch instructions. Following are some useful resources I found about this comparison.</p><ul><li><a href="https://yarchive.net/comp/linux/cmov.html">https://yarchive.net/comp/linux/cmov.html</a></li><li><a href="https://discourse.llvm.org/t/rfc-cmov-vs-branch-optimization/6040">https://discourse.llvm.org/t/rfc-cmov-vs-branch-optimization/6040</a></li><li><a href="https://kristerw.github.io/2022/05/24/branchless/">https://kristerw.github.io/2022/05/24/branchless/</a></li></ul><p>If you are using techniques like branchless programming for optimization, analyze whether you are really getting an advantage by using it. Usually modern compilers, combined with modern instruction sets are well capable of optimizing our code. Check whether you have tried built-in optimization options to speedup your code. If it is already done, do some profiling and benchmark tests when adding your own optimization strategies, and confirm your method really optimizes the code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45359293ac24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Parallelism in AWS Step Functions]]></title>
            <link>https://budvin.medium.com/dynamic-parallelism-in-aws-step-functions-530f434dd933?source=rss-871f67af159a------2</link>
            <guid isPermaLink="false">https://medium.com/p/530f434dd933</guid>
            <category><![CDATA[serverless-framework]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[parallel-processing]]></category>
            <category><![CDATA[dynamic-parallelism]]></category>
            <category><![CDATA[aws-step-functions]]></category>
            <dc:creator><![CDATA[Budvin Chathura]]></dc:creator>
            <pubDate>Tue, 09 Mar 2021 14:36:23 GMT</pubDate>
            <atom:updated>2021-03-12T10:30:07.555Z</atom:updated>
            <content:encoded><![CDATA[<h4>An example with <a href="https://www.serverless.com/">Serverless</a> Framework</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FYUq-PkSdxwCaeTTqXKFlQ.png" /><figcaption><a href="https://www.freepik.com/vectors/business">Business vector</a> created by vectorjuice — <a href="http://www.freepik.com/">www.freepik.com</a></figcaption></figure><p><a href="https://aws.amazon.com/step-functions/">“Step Functions”</a> is the serverless orchestration service provided by AWS. It can be used to define and manage workflows. AWS Step Functions can be used with various other AWS services such as AWS Lambda, AWS Batch and AWS ECS. Step Functions support both sequential, parallel and hybrid workflows. In this article I am going to describe about <em>“dynamic parallelism”</em> in Step Functions.</p><p>Before dynamic parallelism feature, AWS Step Functions only had something like “static parallel workflow” where the developers have to specify the definition for each parallel branch. Such static parallel functions are defined in the Step Function workflow definition as &quot;Type&quot;:&quot;Parallel&quot; . Those defined branches look like this in the Step Function definition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*6J3gr6w3p9M85McRy4y9bA.png" /><figcaption>source: <a href="https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-parallel-state.html">https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-parallel-state.html</a></figcaption></figure><p>With dynamic parallelism, you can develop something similar to a parallel loop. Each parallel iteration will do the same task but slightly differently depending on the set of inputs. Such iterator is defined in the Step Function definition as &quot;Type&quot;:&quot;Map&quot; . This implementation will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*p2g1co0hnpbbdjwzAA5MFg.png" /><figcaption>“ProcessTaskStep” will be executed parallelly for each iteration.</figcaption></figure><p>In this article I am using Lambda functions with Step Function definition to demonstrate this feature. Final workflow of our state machine will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*gH1lFSVleblc7LFMnLwy5w.png" /></figure><p>In this workflow, FindTasksStep generates a list of tasks. After that, the iterations are executed for each element in the list parallelly. In each iteration the corresponding element is processed in ProcessTasksStep and saved to an S3 bucket. After completing all the iterations, resulting values are gathered in SummaryTasksStep and a summarized file is also written to the same S3 bucket.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/907cea43759a469439c9419b0e431486/href">https://medium.com/media/907cea43759a469439c9419b0e431486/href</a></iframe><blockquote>This is the template used with Serverless Framework for this workflow. <strong>Note that</strong> you can re-use everything under thedefinition attribute (i.e. from line 43 to 83) along with AWS CloudFormation templates also.</blockquote><p>The most important part in the definition is ProcessTasksMappedTask. Type of the step is Map which implies that it is a mapped task. InputPath and ItemsPath should be defined to tell the Map task to where to look for the list of inputs for the parallel iteration. For this to work, in its previous step, FindTasksStep should return a compatible data object. In the Lambda handler of that step I have returned such a data object in the lambda callback.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68302e2ce40a7c48669e73e8a7660225/href">https://medium.com/media/68302e2ce40a7c48669e73e8a7660225/href</a></iframe><p>With this returned object, the task list can be found inevent-&gt; body-&gt; taskList path. This is the path defined in</p><pre>InputPath: &quot;$.body&quot;            <br>ItemsPath: &quot;$.taskList&quot;</pre><p>part in the Step Function definition.</p><p>Data in each object in the list can be accessed via event parameter in the Lambda handler of ProcessTaskStep. After processing each object, result list can be accessed in event-&gt;results object. This is specified in</p><pre>ResultPath: &quot;$.results&quot;</pre><p>in ProcessMappedTask definition.</p><p>This result list is then accessed in the Lambda handler of SummaryTaskStep as event.results.</p><blockquote>Note that before deploying this code you need to have a dedicated S3 bucket to store the results of this Step Function.</blockquote><p>After deploying we can start an execution and observe the results. After a successful execution, files will be created in the specified S3 bucket in the following manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I4VwmKz6Wa3oYKuuCyHsPA.png" /><figcaption>files created after one execution of the state machine</figcaption></figure><p>You can also define MaxConcurrency attribute to define the maximum parallel execution limit.</p><p>Complete source code is available at <a href="https://github.com/budvinchathura/serverless-aws-dynamic-parallelism">https://github.com/budvinchathura/serverless-aws-dynamic-parallelism</a>.</p><p>In this example I have only used AWS Lambda functions with Step Functions. You can also use AWS Batch and AWS ECS to create more complex hybrid workflows. You can find such a tutorial in <a href="https://www.serverless.com/blog/deploy-hybrid-serverless-cluster-workflows">https://www.serverless.com/blog/deploy-hybrid-serverless-cluster-workflows</a>.</p><p>For further explanations about the dynamic parallelism feature please visit <a href="https://aws.amazon.com/blogs/aws/new-step-functions-support-for-dynamic-parallelism/">this</a> blog post from AWS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=530f434dd933" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why You Should Consider Securing Your Servers?]]></title>
            <link>https://medium.com/ixdlabs/why-you-should-consider-securing-your-servers-453c375bdd89?source=rss-871f67af159a------2</link>
            <guid isPermaLink="false">https://medium.com/p/453c375bdd89</guid>
            <category><![CDATA[port-scanning]]></category>
            <category><![CDATA[server-security]]></category>
            <category><![CDATA[intrusion-detection]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[suricata]]></category>
            <dc:creator><![CDATA[Budvin Chathura]]></dc:creator>
            <pubDate>Thu, 25 Feb 2021 12:50:09 GMT</pubDate>
            <atom:updated>2021-02-25T12:50:09.958Z</atom:updated>
            <content:encoded><![CDATA[<h4>Looking into port scanning and other attacks with <a href="https://suricata-ids.org/">Suricata</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kMQpED1p7reGWxJ9.png" /><figcaption>Image Source : <a href="https://www.varonis.com/blog/port-scanning-techniques/">https://www.varonis.com/blog/port-scanning-techniques/</a></figcaption></figure><p>When living in 2021 with digital technologies you might probably know that all our devices should be secure against possible attacks <em>(or at least against attacks that we are aware of)</em> which are coming from various sources; inside or outside. If you are a responsible person in a corporate environment which is mostly related to web servers and cyber security, you MUST be a well experienced person in this domain.</p><blockquote>But, you might be hosting some few servers for you own projects, client projects or even for a small startup. If that is the case you might think ‘<strong>should I worry about cyber security that much?</strong>’.</blockquote><p>In this article we will see the importance of configuring proper security procedures even for a development server in a project.</p><p>We are going to use a tool called <a href="https://suricata-ids.org/">Suricata</a>, which is an open-source IDS (Intrusion Detection System) to analyze the threats that are coming to a cloud hosted server.</p><p>You can easily setup Suricata in a server by referring some of these tutorials.</p><ul><li><a href="https://www.atlantic.net/vps-hosting/how-to-install-and-setup-suricata-ids-on-ubuntu-20-04/">How to Install And Setup Suricata IDS on Ubuntu 20.04 | Atlantic.Net</a></li><li><a href="https://suricata.readthedocs.io/en/suricata-6.0.0/install.html">3. Installation - Suricata 6.0.0 documentation</a></li><li><a href="https://redmine.openinfosecfoundation.org/projects/suricata/wiki/Basic_Setup">Suricata</a></li></ul><p>Suricata needs “rules” to operate. Rules are the commands which tell Suricata to what should be scanned and what should be considered as suspicious attacks. Rules can be added either at Suricata build stage or later with <a href="https://suricata.readthedocs.io/en/suricata-4.1.4/rule-management/oinkmaster.html">Oinkmaster</a>.</p><p><a href="https://redmine.openinfosecfoundation.org/projects/suricata/wiki/Rule_Management_with_Oinkmaster">Suricata</a></p><blockquote>Now we have a small VM running with Suricata enabled. You might think, <strong>no one knows this VM , so what happens now?</strong></blockquote><p>Apparently this is not the case. There are large number of attacks and port scans happening in every minute. In most of the times these scans come from bots but port scanning is one of the early steps when doing an attack.</p><blockquote>To collect data for this article, I created a small VM in Azure and installed Suricata. From the moment I installed it, there were port scans, at least 1 or 2 scans in every minute.</blockquote><p>Suricata maintains a log file for recording the attacks. These records looks like this.</p><pre>02/21/2021-14:54:59.897071  [**] [1:2402000:5812] ET DROP Dshield Block Listed Source group 1 [**] [Classification: Misc Attack] [Priority: 2] {TCP} 45.146.165.171:53784 -&gt; 10.1.0.6:28302</pre><pre>02/21/2021-14:54:59.897071  [**] [1:2403325:63572] ET CINS Active Threat Intelligence Poor Reputation IP group 26 [**] [Classification: Misc Attack] [Priority: 2] {TCP} 45.146.165.171:53784 -&gt; 10.1.0.6:28302</pre><p>Log records contain the timestamp, destination and source IPs, ports, type of the attack and the priority.</p><p>You can view some of the latest port scans and attacks with the following command. (which shows the last few lines of the log file)</p><pre>tail -f /var/log/suricata/fast.log</pre><p>I found a small python script to convert these log records to more readable CSV format which you can access from <a href="https://gist.github.com/tjnel/8834536167a30047aa02d41f46d94b22">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e21ba97d13755c28837f375be955a9d/href">https://medium.com/media/9e21ba97d13755c28837f375be955a9d/href</a></iframe><p>Lets look into some of the records.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33701b610a9544dbb0071c02567da206/href">https://medium.com/media/33701b610a9544dbb0071c02567da206/href</a></iframe><p>As you can see, ‘<em>rule_name</em>’ column shows the reason for recording each scan attempt. Most of them are labelled as ‘poor reputation group’, which suggests that the source IP has been previously listed as a malicious source. By looking at ‘<em>to_addr</em>’ column we can observe the particular ports which were targeted by scans. I did not start any service to run in port 1433 (which typically MySQL port) in this server but still there are scans. There are also scans for port 22 which is usually the port for ssh communications. Records in the above table are a very few amount of records which were filtered from all the records. Original log file contained hundreds of scans per hour which were similar to above records.</p><p>With these observations it is reasonable to assume that your small dev servers or production servers are also vulnerable when exposed to internet. To minimize the impact, you should configure necessary security settings in various levels.</p><ul><li>Your application level (configure correct access levels, secure password hashing methods, preventing SQL injection etc.)</li><li>More protection when serving static files via http. (if you have some incorrect configurations, attackers might be able to view files like .env .git . Personally I have experienced such scenarios where the application logs showed that someone tried to access the .env file).</li><li>Enable logging/auditing in application level. Cloud vendors also provide logging services such as; <a href="https://aws.amazon.com/cloudwatch/">AWS Cloudwatch</a>, <a href="https://docs.microsoft.com/en-us/azure/azure-monitor/overview">Azure Monitor</a>.</li><li>Configure firewall rules in OS level.</li><li>In cloud environments there is another security layer called ‘Security Groups’ which is another filtering layer outside your servers. You can configure the security groups with allowed ports and IP s.</li></ul><p>I hope now you have a fair understanding on why you should secure your servers with best security practices. Try to install Suricata in one of your dev servers and observe the scan logs and decide on what are the steps you should take to protect your server.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=453c375bdd89" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ixdlabs/why-you-should-consider-securing-your-servers-453c375bdd89">Why You Should Consider Securing Your Servers?</a> was originally published in <a href="https://medium.com/ixdlabs">iXDLabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going Serverless with AWS Lambda, Serverless Framework and faunaDB.]]></title>
            <link>https://medium.com/ixdlabs/going-serverless-718ed43db563?source=rss-871f67af159a------2</link>
            <guid isPermaLink="false">https://medium.com/p/718ed43db563</guid>
            <category><![CDATA[faunadb]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[serverless-framework]]></category>
            <dc:creator><![CDATA[Budvin Chathura]]></dc:creator>
            <pubDate>Wed, 27 Jan 2021 11:18:00 GMT</pubDate>
            <atom:updated>2021-02-23T20:46:47.443Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Serverless application from scratch with Serverless Framework, AWS Lambda and faunaDB</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OJ4V7xHsFm6R8qyv.png" /></figure><p>TL; DR</p><ul><li>“serverless” design is using the FaaS (Function as a Service) feature in cloud environments.</li><li>In serverless applications you deploy functions, not servers. Those functions are executed when they are triggered.</li><li>Examples: AWS Lambda, Google Cloud functions, Azure functions</li><li>Serverless Framework can be used to develop and deploy serverless applications</li><li>faunaDB is a noSQL database with some features of relational databases</li><li>Starter code is here <a href="https://github.com/budvinchathura/serverless-faunadb-test-starter">https://github.com/budvinchathura/serverless-faunadb-test-starter</a></li><li>Complete source code is here <a href="https://github.com/budvinchathura/serverless-faunadb-test">https://github.com/budvinchathura/serverless-faunadb-test</a></li></ul><h3>What is “Serverless”?</h3><p>“Serverless” technology in cloud environments is relatively a new technology compared to traditional server-based options. This is also called as “Function as a Service” feature. You can think it is as a function deployed in the cloud. It is not like a server which is running continuously; it is only a function definition. Just like in programming languages, you just define a function to be used later. When a user calls that cloud function, cloud vendor spins up an execution environment and execute the function. Hence serverless functions are short-lived and can be considered as “stateless”. (But different cloud vendors may have slightly different implementations where the execution environment or context is sometimes shared between consecutive function invocations.)</p><p>Some vendor-specific serverless examples are,</p><ul><li>AWS Lambda functions</li><li>Google Cloud functions</li><li>Azure functions</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*dS5EP24JoaG67l7K.jpeg" /><figcaption>Source: <a href="https://www.freecodecamp.org/news/what-is-serverless-architecture-what-are-its-pros-and-cons/">https://www.freecodecamp.org/news/what-is-serverless-architecture-what-are-its-pros-and-cons/</a></figcaption></figure><p>In most of the times, serverless approach can be considered as a cost-saving way because you are billed only for the execution time of function invocations. (<em>Currently, </em><a href="https://aws.amazon.com/lambda/pricing/"><em>pricing</em></a><em> for AWS Lambda is around $0.20 per 1 million requests and $0.0000166667 for every GB-second).</em> Meanwhile, if you are hosting a traditional server you are billed for each hour (or day) regardless of the traffic to the server. Also, scalability in serverless is more flexible than using a server because you can have a large amount of serverless function executions running at the same moment.</p><p>But don’t get too excited about this because serverless has its own drawbacks as well. If your function gets called for too many times for much long-running tasks, it may not be efficient or cost effective as traditional server-based approach. There are other issues like ‘cold-starts’, debugging issues, managing security and vendor locking (for some extent).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*C3nvWuiHWSLQsmDx.png" /><figcaption>Degree of automation when using serverless design (Source: <a href="https://specify.io/concepts/serverless-baas-faas">https://specify.io/concepts/serverless-baas-faas</a>)</figcaption></figure><p>Shifting to serverless does not mean that we are getting rid of servers. Any cloud service needs running servers for execution. Serverless is a slightly different paradigm which provides much abstraction for the developers with more flexible pricing strategies and scalability options.</p><p>You can easily find more insights about serverless architecture and its characteristics in many other articles. In this article, I am going to guide you to build a serverless app from scratch.</p><p>I will use these technologies and frameworks for this tutorial.</p><ul><li><a href="https://www.serverless.com/">Serverless Framework</a></li><li><a href="https://aws.amazon.com/lambda/">AWS Lambda</a></li><li><a href="https://fauna.com/">faunaDB</a> (faunaDB is a noSQL database with some features of relational databases. You may use any other database service if you have a running instance for that.)</li></ul><h3>What you will need</h3><ul><li>Activated AWS account with AWS CLI configured with an Administrator IAM user.</li></ul><p>You can use these user guides for configuring AWS CLI V2.</p><ul><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html">Installing or updating to the latest version of the AWS CLI</a></li><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html">Configuring the AWS CLI</a></li></ul><p>Check your AWS CLI configuration by running following command in your terminal.</p><pre>aws configure list</pre><p>You should get something similar to this, with ‘XXXX’ replaced by your credentials and your region instead of ‘us-east-1’. (I am using us-east-1 for this tutorial.)</p><pre>Name                    Value             Type    Location<br>      ----                    -----             ----    --------<br>   profile                &lt;not set&gt;             None    None<br>access_key     ****************XXXX shared-credentials-file<br>secret_key     ****************XXXX shared-credentials-file<br>    region                us-east-1      config-file    ~/.aws/config</pre><ul><li>Create a new DB in faunaDB from <a href="https://dashboard.fauna.com/db-new/">here</a> and obtain access credentials for that DB.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*E1_QrYAJQuBbKCuxxQpSeA.png" /><figcaption>faunDB security key tab for a database</figcaption></figure><ul><li>npm and NodeJS installed.</li><li>Install serverless as a global npm package.</li></ul><pre>npm install -g serverless</pre><p>Check your installation with,</p><pre>serverless -v</pre><p>You should get something like the following configuration. Exact versions may differ.</p><pre>Framework Core: 2.20.1<br>Plugin: 4.4.2<br>SDK: 2.3.2<br>Components: 3.5.1</pre><h3>Let’s code</h3><p>We are going to create a simple CRUD API with entities as ‘users’. ‘user’ records can be added, modified, searched, listed and deleted. Let’s start with the starting code available at <a href="https://github.com/budvinchathura/serverless-faunadb-test-starter">https://github.com/budvinchathura/serverless-faunadb-test-starter</a>. Clone this repo and install all the dependencies with</p><pre>npm install</pre><p>Since we are using TypeScript for this we have to use webpack to get JavaScript output and then deploy it to AWS Lambda. (Currently AWS Lambda supports <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html">several runtimes</a> such as NodeJS, Python, Ruby, Java, Go and .NET. If you decide to use JavaScript for this, you don’t need webpack configurations. JavaScript code can be directly added to AWS Lambda with Serverless). For now, you don’t have to worry about webpack related configurations, I have added them to the repo already.</p><p>Before compiling or deploying any code, you have to create <strong><em>env.json </em></strong>file in project root directory and add the following contents where xxxxxxxx is replaced with your access secret for the newly created empty database in faunaDB.</p><pre>{<br>    &quot;FAUNADB_SECRET_KEY&quot;:&quot;xxxxxxxx&quot;<br>}</pre><p>This is obviously to keep our environment variables, in this scenario faunaDB access credentials.</p><p>Now let’s look at the contents of each file.</p><p><strong>1. fauna-setup.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d39553210238d5fe51385be13aac644/href">https://medium.com/media/2d39553210238d5fe51385be13aac644/href</a></iframe><p>This is basically the initial structure of our database. You can see in line #8 we are creating a new client to access faunaDB. In line #9 we are creating a new collection called ‘users’<strong><em>.</em></strong> A <strong><em>‘collection’</em></strong> is something like a <strong><em>‘table’</em></strong> in relational databases. You can execute this file with just the node execution environment with.</p><pre>node faunadb-setup.js</pre><p>If everything goes well, you will see the terminal output as,</p><pre>&quot;users&quot; collection created.<br>finished</pre><p>Now our database is ready.</p><p><strong>2. serverless.yml</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1536c7d6fcd27de7854d6ca1b8d390c5/href">https://medium.com/media/1536c7d6fcd27de7854d6ca1b8d390c5/href</a></iframe><p>This is the most important part of our initial code. <strong><em>serverless.yml</em></strong> file defines the infrastructure resources we need inside AWS. Basically we are deploying a service called <strong><em>‘serverless-faunadb-test-starter’</em></strong> and inside that service, we have 2 functions.</p><ul><li>create</li><li>list</li></ul><p>These are actually 2 AWS Lambda functions that we are going to create inside this service.</p><p>Lets consider the <strong><em>‘create’</em></strong> function.</p><pre>create:<br>  handler: users/create.create<br>   events:<br>     - http:<br>         path: users<br>         method: post<br>         cors: true</pre><ul><li>‘<strong><em>handler’ </em></strong>attribute defines the actual function in our code, which should be executed when we call <strong><em>‘create’</em></strong> function in our service.</li><li>Meaning of <strong><em>users/create.create</em></strong> is that we are using <strong><em>‘create’</em></strong> function of <strong><em>‘create’</em></strong> file which is inside <strong><em>‘users’</em></strong> directory. (It is just the path to the actual function).</li><li><strong><em>‘events’</em></strong> attribute defines trigger(s) for this function. (specifying what should trigger this function). AWS has many triggers such as http, websocket, schedule, sns etc. Single lambda functions may have more than one trigger. Here we are using only an <strong><em>http </em></strong>event trigger since we need to execute this Lambda function when a user sends an http request to our service.</li><li>Under http event, <strong><em>path</em></strong> attribute is for the URL prefix of our endpoint. Method is POST since we have to get details for the new user in http body. CORS is set to ‘true’ to allow requests from all domains.</li></ul><p>If you want, you can change <strong><em>‘region’</em></strong> attribute under <strong><em>‘provider’</em></strong> to any other AWS region.</p><p>For this service we have defined our faunaDB secret under environment variables (line #27, #28). Meaning of <strong><em>${file(./env.json):FAUNADB_SECRET_KEY} </em></strong>is to read env.json file and get FAUNADB_SECRET_KEY attribute from that json file.</p><p>Now we will move into actual handler files.</p><p><strong>create.ts</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37c4cf55cd12c19c26fe636e89c5db8f/href">https://medium.com/media/37c4cf55cd12c19c26fe636e89c5db8f/href</a></iframe><p>In this function, we are parsing and validating the data attributes which are submitted to POST /users endpoint. After that, the user record is created with <strong><em>faunadbClient.query</em></strong> method. Finally, the response is formatted and sent to the user.</p><p>If we look into <strong><em>buildResponse</em></strong> function which is in <strong><em>utils.ts</em></strong> file,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3add358de27c8dfb1d97595a2d57e8d5/href">https://medium.com/media/3add358de27c8dfb1d97595a2d57e8d5/href</a></iframe><p>We should set <strong><em>‘Content-Type’</em></strong> header and also <strong><em>‘statusCode</em></strong>’ since this output from our Lambda function is forwarded to the API users via AWS API Gateway. Those attributes are needed to transform Lambda response to an http response.</p><p>Code segments for <strong><em>‘list’</em></strong> function are similar to <strong><em>‘create’</em></strong> function with few changes to query for existing users. Function implementation code is in <strong><em>users/list.ts</em></strong> <strong><em>list </em></strong>function. I assume it will not be much difficult to understand the code related to the <strong><em>‘list’</em></strong> function.</p><p>Now we have developed 2 functions and it’s time to deploy.</p><h3>Let’s deploy the code</h3><p>I am sure you have previously deployed some web server related project to a cloud virtual instance. Most of the times, this deployment process involves provisioning virtual machines, installing dependencies, configuring the server and several other tasks. With serverless design and thanks to Serverless Framework, deploying one service is just a single command. Run this command in the project root directory.</p><pre>serverless deploy</pre><p>If everything goes well, after a few seconds, you should see the last few lines of the terminal output as.</p><pre>......<br>service: serverless-faunadb-test-starter<br>stage: dev<br>region: us-east-1<br>stack: serverless-faunadb-test-starter-dev<br>resources: 17<br>api keys:<br>  None<br>endpoints:<br>  POST - <a href="https://o0w083r53f.execute-api.us-east-1.amazonaws.com/dev/users">https://xxxx.execute-api.us-east-1.amazonaws.com/dev/users</a><br>  GET - <a href="https://o0w083r53f.execute-api.us-east-1.amazonaws.com/dev/users">https://xxxx.execute-api.us-east-1.amazonaws.com/dev/users</a><br>functions:<br>  create: serverless-faunadb-test-starter-dev-create<br>  list: serverless-faunadb-test-starter-dev-list<br>layers:<br>  None</pre><p>‘xxxx’ will be replaced by a unique id for your API service.</p><p>Yp, that’s it, we just deployed our service with 2 functions (or 2 endpoints).</p><p>This <strong><em>serverless deploy </em></strong>command will execute many steps.</p><ol><li>Compile TypeScript code into JavaScript</li><li>Bundle with necessary dependencies</li><li>Upload code to AWS</li><li>Validate serverless.yml template</li><li>Create AWS resources</li><li>Remove previous resources or resource definitions. (only if you are re-deploying after some code changes)</li></ol><p>In fact, step 5 creates many AWS resources such as,</p><ul><li>Lambda functions (for each function we have defined)</li><li>API Gateway (to connect these Lambda functions with http triggers)</li><li>Log groups for each Lambda functions. (If you have any console.log statements or any logging commands in your code, those console outputs will be automatically added to these logs. Logs also contain execution time and memory used for each Lambda invocation)</li><li>S3 bucket (to store our code and Serverless template in AWS).</li><li>Cloudformation stack (It is the entity which packages all above resource as a single resource group so that tracking and managing is easier when accessed from one place.)</li></ul><p>After login into <a href="https://console.aws.amazon.com/console/home">AWS Console</a> You should be able to view this deployment stack in <a href="https://console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/">https://console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/</a></p><p>There should be stack named <strong><em>‘serverless-faunadb-test-starter-dev’. </em></strong>If you click and open that stack, you will be able to see all the resources and even get a simple visualization of those resources.</p><p><strong>Note</strong>: If you have changed your region to something other than ‘us-east-1’, please edit and use above link accordingly.</p><h3>Testing the deployment</h3><p>Now we have deployed our code and its time to test the functionality. Remember we got our endpoint URL s in the terminal output just after the deployment.</p><p>To create a new user, we are using <strong><em>‘create’</em></strong> endpoint. Note that this is a POST request and the content type is json. Remember to replace ‘xxxx’ with the real identifier and replace ‘us-east-1’ with the region. (only if you have changed the region in serverless.yml).</p><pre>curl --request POST https://xxxx.execute-api.us-east-1.amazonaws.com/dev/users --header &quot;Content-Type: application/json&quot; --data-raw &#39;{&quot;name&quot;:&quot;Test user 1&quot;, &quot;dob&quot;:&quot;2000-01-01&quot;,&quot;email&quot;:&quot;abc@abc.com&quot;,&quot;city&quot;:&quot;Downtown&quot;}&#39;</pre><p>This will return an output similar to,</p><pre>{&quot;                           <br>status&quot;:&quot;SUCCESS&quot;,&quot;data&quot;:{&quot;user&quot;:{&quot;name&quot;:&quot;Test user 1&quot;,&quot;dob&quot;:&quot;2000-01-01&quot;,&quot;city&quot;                           <br>:&quot;Downtown&quot;,&quot;email&quot;:&quot;abc@abc.com&quot;,&quot;id&quot;:&quot;288722901473952259&quot;}}}</pre><p>Value of id field maybe different since this id is auto generated by faunaDB for each record.</p><p>We have just created a user in our database. Now let’s view the list of users.</p><pre>curl https://xxxx.execute-api.us-east-1.amazonaws.com/dev/users</pre><p>It will return the users as,</p><pre>{&quot;status&quot;:&quot;SUCCESS&quot;,&quot;data&quot;:{&quot;users&quot;:[{&quot;name&quot;:&quot;Test user 1&quot;,&quot;dob&quot;:&quot;2000-01-01&quot;,&quot;city&quot;:&quot;Downtown&quot;,&quot;email&quot;:&quot;abc@abc.com&quot;,&quot;id&quot;:&quot;288722901473952259&quot;}]}}</pre><p>I assume now you have a fair knowledge about deploying a service which has several functions by using Serverless Framework. You can now try to add new endpoints like</p><ul><li>Get details of a specific user</li><li>Update a user</li><li>Delete a user</li></ul><p>Procedure is same as previous 2 functions we just deployed.</p><ul><li>Add the function definition to <strong><em>serverless.yml</em></strong> file</li><li>Create a new .ts file or edit an existing .ts file to add the function implementation code. Remember to declare the TypeScript function as an export function. If not, Serverless Framework can not access your function code.</li><li>Run <strong><em>serverless deploy</em></strong> in the project root terminal</li></ul><p>If you just want to modify .ts files only for a single function, after modifying those files you can run the following command to re-deploy only that function.</p><pre>serverless deploy -f functionName</pre><p>For example, if I modify any code only in create.ts, I have to run</p><pre>serverless deploy -f create</pre><p>This command will re-deploy only the <strong><em>‘create’</em></strong> function.</p><p>Note that if you edit any code in <strong><em>types.ts</em></strong> or <strong><em>utils.ts</em></strong> you have to run <strong><em>serverless deploy -f functionName </em></strong>for all the functions, because those files are imported in all the functions that we have defined (or you can run <strong><em>serverless deploy</em></strong> to re-deploy the whole service). Also, if you are doing any modifications to <strong><em>serverless.yml</em></strong> you have to run <strong><em>serverless deploy.</em></strong></p><p>These re-deployments will not change the URL s of existing endpoints. (assuming you are not changing <strong><em>serverless.yml</em></strong> attributes such as <strong><em>stage</em></strong> and <strong><em>region.</em></strong>)</p><p>If you want to remove the deployed service and delete all AWS resources, simple run the following command.</p><pre>serverless remove</pre><p>This command will remove all the AWS resources related to the service.</p><p><strong>Note</strong>: If you execute <strong><em>serverless deploy</em></strong> again after <strong><em>serverless remove</em></strong> , ‘xxxx’ part in <a href="https://xxxx.execute-api.us-east-1.amazonaws.com/"><em>https://xxxx.execute-api.us-east-1.amazonaws.com</em></a> will change.</p><p>Serverless Framework also offers to execute and debug your functions locally. For VSCode editor, I have included the launch configurations in .vscode -&gt; launch.json file. Or you can run</p><pre>serverless offline</pre><p>in the terminal to start executing locally.</p><p>When running locally the URL prefix will be changed to localhost. i.e. <a href="https://xxxx.execute-api.us-east-1.amazonaws.com/"><em>https://xxxx.execute-api.us-east-1.amazonaws.com</em></a> will be changed to something like <a href="http://localhost:3333/"><em>http://localhost:3333</em></a><em>. </em>With the offline, feature you can test and debug your functions before deploying to the cloud environments.</p><p>After some improvements to the code, I have added some additional features like,</p><ul><li>Get user, update user, delete user</li><li>Add followers to a user, remove followers from a user</li></ul><p>For the ‘followers’ feature, you may have to use <a href="https://docs.fauna.com/fauna/current/api/fql/indexes">faunaDB indexes</a> to model the relationship between ‘user’ records.</p><p>Complete source code with above functionalities can be accessed in <a href="https://github.com/budvinchathura/serverless-faunadb-test"><strong><em>https://github.com/budvinchathura/serverless-faunadb-test</em></strong></a></p><p>It is not mandatory to use faunaDB for this, but I just thought using it since it will also be a new experience. You can always use any other different databases like PostgreSQL, MySQL, MongoDB, AWS DynamoDB etc.</p><blockquote>If you are using a relational database like PostgreSQL or MySQL, pay attention to use a singleton design pattern for database connections. This is because AWS Lambda persists execution environment for consecutive Lambda invocations, up to some limits. (read more about that in <a href="https://docs.aws.amazon.com/lambda/latest/dg/runtimes-context.html">here</a>). Hence, you can initialize database connection outside the function handler and re-use that connection. But don’t forget to re-check and initialize the connection when necessary.</blockquote><p>You can find a lot more tutorials and examples in <a href="https://www.serverless.com/examples/">https://www.serverless.com/examples/</a> about Serverless Framework.</p><p>You will be able explore many things like,</p><ul><li>Adding authorizers for Lambda functions (custom authorizers or AWS Cognito user pools)</li><li>Using AWS DynamoDB, AWS RDS with Serverless</li><li>Uploading files to S3 or any other storage services</li><li>Creating multiple services under a single API gateway. (in this tutorial we deployed only one service)</li><li>Other Lambda triggers like websocket, data streams, scheduled triggers etc.</li></ul><p>I hope now you have a fair understanding of serverless design. But keep in mind that serverless is not a complete replacement for traditional server-based design. This serverless pattern has it own ups and downs. Please read about them and get a good understanding before using serverless in a production environment. Also, don’t forget to try Serverless Framework with other cloud vendors as well.</p><p>Good luck with your next serverless project !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=718ed43db563" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ixdlabs/going-serverless-718ed43db563">Going Serverless with AWS Lambda, Serverless Framework and faunaDB.</a> was originally published in <a href="https://medium.com/ixdlabs">iXDLabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a simple autocomplete model with your own Google search history]]></title>
            <link>https://medium.com/analytics-vidhya/build-a-simple-autocomplete-model-with-your-own-google-search-history-ead26b3b6bd4?source=rss-871f67af159a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ead26b3b6bd4</guid>
            <category><![CDATA[autocomplete]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[probabilistic-models]]></category>
            <dc:creator><![CDATA[Budvin Chathura]]></dc:creator>
            <pubDate>Wed, 22 Jul 2020 12:39:40 GMT</pubDate>
            <atom:updated>2020-07-28T13:39:33.270Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*0UgE8WV-f9nJJcbFljm61g.png" /></figure><p>Here we are using a simple <strong><em>probabilistic approach</em></strong> for the autocomplete model.</p><p>First we have to extract your google search history.</p><p>Go to <a href="https://takeout.google.com/settings/takeout">https://takeout.google.com/settings/takeout</a></p><p>Click deselect all. (we don’t need all the data, google search queries will be sufficient)</p><figure><img alt="click deselect all" src="https://cdn-images-1.medium.com/max/906/1*K0akB5Um_hFweousO1gkog.png" /></figure><p>Locate ‘My Activity’ section and select it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*TPmMV9hgpeGmM6wzrZ6MSg.png" /></figure><p>Then we have to filter our results for google search queries. For that, <strong>click ‘All activity data included’ </strong>and deselect every option except ‘search’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*G0bC972RmC6dciEk22rbuw.png" /></figure><p>Then you may select the output format as JSON. For this, <strong>click ‘Multiple Formats’</strong> and select JSON in the drop-down list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*TPmyOpCPR6FAlSuQHb5wcw.png" /></figure><p>Proceed to next step and select your preferred download method. After couple of minutes you will be able to download the zip file named as <strong>takeout&lt;some_numbers&gt;.zip</strong> . Unzip and locate <strong>MyActivity.json</strong> file. This will be the input file for our model.</p><p>Let’s do some preprocessing to this MyActivity.json file and extract the search queries to a myactivity.txt file. This text file fill be the input for our model.</p><pre>import json<br>import re<br>data=[]</pre><pre>processed=[]<br>regex = re.compile(&#39;[^a-zA-Z ]&#39;)</pre><pre>with open(&#39;myActivity.json&#39;,encoding=&quot;utf8&quot;) as f:<br>    data = json.load(f)</pre><pre>for i in range(len(data)):<br>    search_query = data[i][&#39;title&#39;]<br>    if search_query.startswith(&#39;Visited&#39;):<br>        search_query = search_query[8:].lower()<br>        search_query = regex.sub(&#39;&#39;, search_query)<br>        if search_query.startswith(&#39;http&#39;):<br>            continue<br>        processed.append(search_query)<br>    elif search_query.startswith(&#39;Searched for&#39;):<br>        search_query = search_query[13:].lower()<br>        search_query = regex.sub(&#39;&#39;, search_query)<br>        if search_query.startswith(&#39;http&#39;):<br>            continue<br>        processed.append(search_query)<br>    else:<br>        pass</pre><pre>print(processed[:50])</pre><pre>with open(&#39;myactivity.txt&#39;,&#39;w&#39;) as file:<br>    file.write(&#39;\n&#39;.join(processed))</pre><p>For next steps we will use JavaScript (😋 why not?). Maybe you will be able to integrate this model with a simple front-end system with text suggestions.</p><p>Import the required packages. For this, you may have to download the npm package <a href="https://www.npmjs.com/package/sentence-tokenization">https://www.npmjs.com/package/sentence-tokenization</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03e68e96e368cc84a8e996c3231a33ad/href">https://medium.com/media/03e68e96e368cc84a8e996c3231a33ad/href</a></iframe><p>Now we have to read the file myactivity.txt line by line and tokenize each sentence. Tokenizing is simply splitting the sentence to words and storing them as elements in an array-like structure. For this simple model I have only considered words with English letters. For more advanced models you can use punctuation marks and emojis as tokens.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5647b7e0834ff9df9ad896ebc0cb600f/href">https://medium.com/media/5647b7e0834ff9df9ad896ebc0cb600f/href</a></iframe><p>Before executing the main() function, we need some helper functions for our model.</p><p>Now we have to build a small vocabulary. In this example we will build the vocabulary with tokens which appeared at least 2 times in the input file. After building the vocabulary, replace other tokens in the input sentences as &lt;unk&gt; token. (which says it is an out-of-vocabulary word)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6095a23b983a9e8484d0408c5e48a72e/href">https://medium.com/media/6095a23b983a9e8484d0408c5e48a72e/href</a></iframe><p>Now let’s dive into the actual logic of the model.</p><p><strong><em>This method is based on n-gram language model. N-gram is an adjacent set of n number of tokens.</em></strong> For simplicity consider n = 2. In this scenario, n-grams would be called as bigrams.</p><p>Bigrams of the sentence “this is a simple probabilistic model” would be</p><pre>[&quot;this&quot;, &quot;is&quot;], [&quot;is&quot;, &quot;a&quot;], [&quot;a&quot;, &quot;simple&quot;], [&quot;simple&quot;, &quot;probabilistic&quot;], [&quot;probabilistic&quot;, &quot;model&quot;]</pre><p>For n=3, trigrams would be</p><pre>[&quot;this&quot;, &quot;is&quot;, &quot;a&quot;], [&quot;is&quot;, &quot;a&quot;, &quot;simple&quot;], [&quot;a&quot;, &quot;simple&quot;, &quot;probabilistic&quot;], [&quot;simple&quot;, &quot;probabilistic&quot;, &quot;model&quot;]</pre><p>Likewise we have to count number of times each n-gram appeared in the input text. For this we can use an n sized window to scan the token list. Before that we have to add special tokens to denote the start and end of a sentence. &lt;s&gt; and &lt;e&gt;. &lt;s&gt; token is added n-1 times at the beginning of the sentence and &lt;e&gt; is added only once.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28becfc62c42cdfd24652285ba422aee/href">https://medium.com/media/28becfc62c42cdfd24652285ba422aee/href</a></iframe><p>Now we have the counts of bigrams and trigrams (i.e. n-grams and n+1-grams). Now we can estimate the probability for next word, given the previous two words.</p><p>Suppose the previous two words (tokens) are [“what”, “is”]. Then, for each word <strong><em>w</em></strong> in vocabulary, we can calculate the probability as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*TOEo3GkFfqzBkAvP_x91Dg.png" /></figure><p>There is a possibility for above counts to be 0. As a solution we can add a smoothing constant <strong><em>k</em></strong> to the equation. Then the equation becomes,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*z_Zx886HzgamEnq1LPIdBw.png" /></figure><p>Likewise we can get the probability for each word in the vocabulary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e1a5427f6f48ea03fd52feaa85fc81f/href">https://medium.com/media/1e1a5427f6f48ea03fd52feaa85fc81f/href</a></iframe><p>After calculating probabilities for each word, we can choose the best suggestion based on the maximum probability. You may also choose several suggestions with words with maximum probabilities.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/353f19eccffcd7eb387882a365e2bcf4/href">https://medium.com/media/353f19eccffcd7eb387882a365e2bcf4/href</a></iframe><p>We can further develop the model by using several n-gram counts. If the starting words are “what is a” we can use several models and get more suggestions.</p><ul><li>Use [“a”] as starting token and use unigram and bigram counts</li><li>Use [“is”, “a”] as starting tokens and use bigram and trigram counts</li><li>Use [“what”, “is”, “a”] as starting tokens and use trigram and quadgram counts.</li></ul><p>Note that always we have to use n-gram count and n+1-gram count for each method.</p><p>Here I have used up to 5-gram counts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68e378e34a1d8b879d633660746523cd/href">https://medium.com/media/68e378e34a1d8b879d633660746523cd/href</a></iframe><p>With this approach, for starting words “what is a”, I got following suggestions with respective probability values.</p><p>function → 0.020064602834036733<br>lightweight → 0.008857318249583442<br>good → 0.0019493177387914227<br>good → 0.0019529433646424251</p><p>Note that the word ‘good’ appears 2 times because both 3-gram and 4-gram models predicted the word ‘good’.</p><p>Complete source code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8687853b4c12ebeb47f840a33210f3e5/href">https://medium.com/media/8687853b4c12ebeb47f840a33210f3e5/href</a></iframe><p>As you can see we managed to build a simple autocomplete model with a probabilistic approach. If you are interested in this kind of natural language processing models, I highly encourage you to take the Natural Language Specialization by deeplearning.ai in Coursera. You will be able to learn more advanced models with machine learning and also with deep neural networks.</p><p>Another useful resource book <a href="https://web.stanford.edu/~jurafsky/slp3/">https://web.stanford.edu/~jurafsky/slp3/</a></p><p>Good luck !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ead26b3b6bd4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/build-a-simple-autocomplete-model-with-your-own-google-search-history-ead26b3b6bd4">Build a simple autocomplete model with your own Google search history</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>