<?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 Saswat Sahoo on Medium]]></title>
        <description><![CDATA[Stories by Saswat Sahoo on Medium]]></description>
        <link>https://medium.com/@saswat.sahoo.1988?source=rss-4ce965a15d5e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*h8Gs9jsnDwuoKWJc.jpg</url>
            <title>Stories by Saswat Sahoo on Medium</title>
            <link>https://medium.com/@saswat.sahoo.1988?source=rss-4ce965a15d5e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 16:10:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saswat.sahoo.1988/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[(Un)Lock Snowflake Data Access using External Tokenization]]></title>
            <link>https://medium.com/@saswat.sahoo.1988/un-lock-snowflake-data-access-using-external-tokenization-29273bf2c527?source=rss-4ce965a15d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/29273bf2c527</guid>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[snowflake-data-cloud]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Saswat Sahoo]]></dc:creator>
            <pubDate>Wed, 24 May 2023 21:12:49 GMT</pubDate>
            <atom:updated>2023-05-26T18:27:44.919Z</atom:updated>
            <content:encoded><![CDATA[<p>Snowflake provides several security features that allow you to control the exposure of sensitive data to non-privileged users. The most commonly used methods to protect data access are using Row-Level security (RLS) and Column-Level security. In this blog, we will focus on column-level security using <a href="https://docs.snowflake.com/en/user-guide/security-column-ext-token-intro"><strong>external tokenization</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*etaw79dK2cqUhs9Zv0kUQA.png" /></figure><h3>External Tokenization — Overview</h3><p>You can apply column-level security in Snowflake using one of the below 2 ways —</p><p><a href="https://docs.snowflake.com/en/user-guide/security-column-ddm-intro"><strong>Dynamic Data Masking (DDM) </strong></a><strong>— </strong>This<strong> </strong>enables you to mask or hide specific columns of data based on the user’s role, thereby providing an additional layer of protection to your sensitive data. In this approach, you store your sensitive <strong>data inside Snowflake</strong> and apply specific masking policies to redact the sensitive info on the fly during the query runtime.</p><p><a href="https://docs.snowflake.com/en/user-guide/security-column-ext-token-use"><strong>External Tokenization</strong></a><strong> — </strong>This is also a column masking feature but the main difference compared to the above is — you keep<strong> your sensitive information outside of Snowflake </strong>and only store a reference/pointer to your original data in Snowflake. Before bringing data into Snowflake you tokenize and store it securely somewhere (on-premise or any other cloud environment) and detokenize on the fly when somebody requests it.</p><p>Under the hood, External tokenization uses two objects —</p><ul><li><strong>Masking policy</strong> — This is a snowflake schema-level object which defines the rules for how a column is rendered for a role that is used to access table data</li><li><strong>External Function</strong>— This allows you to invoke an external API from within their Snowflake SQL query and combines the API response into the query result. In short, it is a UDF that runs <strong><em>outside</em></strong> of Snowflake. The external function is wrapped inside the masking policy that detokenizes the masked (tokenized) value and presents the original value to the end user. This is completely transparent to the user, so the user does not realize whether the tokenized/detokenized data is stored within or outside Snowflake.</li></ul><p>In this article, we will see how to use a masking policy in combination with an external function (an API via AWS API Gateway that will trigger an AWS Lambda function) to apply column-level masking.</p><h4>Loading Tokenized Data</h4><p>To protect sensitive information using <strong>external tokenization</strong>, the first step is to replace this information with randomly generated tokens. These tokens are saved in Snowflake along with other non-sensitive information. For example, consider a “Customers” table which stores details about customers. In this table, some columns are sensitive (like email address, SSN, address, etc.) and you would like to limit access only to authorized users. Using an external tokenization approach you can replace the sensitive information and store only random IDs in Snowflake. Below is an example of how a tokenized table would look like. On the left table, you see the real values of the customer id &amp; email. However, while storing this data on Snowflake, you would replace email ids with UUIDs and store the real values outside of Snowflake i.e. either On-Premise or any other cloud provider’s database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6oyLT1xa1y11wNbAqHooXg.png" /></figure><p>This means customers&#39; table is always protected in Snowflake, without even applying a masking policy as the table never stores the real values. Users/roles having read access to this table will always see a random id for the email column.</p><p>There are external services and solutions provided by third-party vendors to tokenize data before loading it into Snowflake. This is also possible to build it yourself. For the purpose of the blog, I have created a sample application that tokenizes the data and keeps the real values in a DynamoDB table. Sample code &amp; execution steps are available <a href="https://github.com/saswatkumarsahoo/snowflake-external-tokenization"><strong>here</strong></a>. In the next section, we will see how we can use a masking policy in combination with an external function to detokenize data on the fly.</p><h4>Detokeinzation — Set Up &amp; Demo</h4><p>For external tokenization, we need to create some components on both sides i.e. AWS &amp; Snowflake</p><p><strong>AWS components</strong> —</p><ul><li>A Lambda function — This is where the code is executed to retrieve de-tokenized data</li><li>An API Gateway (API GW) — This acts as a proxy between the lambda function and Snowflake and relays data between Snowflake and the lambda function</li></ul><p><strong>Snowflake components</strong> —</p><ul><li>A masking policy — This is applied to the table column(s) that you want to protect. In this case, we will use a dummy “Customers” table as shown in the previous section</li><li>An API Integration — It is a Snowflake object that provides an interface between Snowflake and third-party services i.e. API Gateway in this scenario</li></ul><p>I have created all these components using <a href="https://www.serverless.com/">Serverless framework</a>. The sample code is <a href="https://github.com/saswatkumarsahoo/snowflake-external-tokenization"><strong>available here.</strong></a> On deploying this application, it creates all the above AWS &amp; Snowflake components.</p><p>Additionally, it sets up a few resources for the demo purpose -</p><ul><li>A Snowflake table (named CUSTOMERS) under the TOKENIZER_DEMO database. Also, it is filled with some tokenized data</li><li>Original data is stored in a Dynamodb table</li><li>A warehouse (TOKENIZER_DEMO_WH) &amp; 2 roles i.e. DEMO_ANALYST &amp; DEMO_DEVELOPER</li></ul><p>Below is a pictorial representation of all components that are deployed by this serverless application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vaw16hhPIlTDzFqyJAG6FQ.png" /><figcaption>Image 2 – detokenizer under the hood</figcaption></figure><p>Let’s have a closer look at the masking policy —</p><pre>CREATE OR REPLACE MASKING POLICY TOKENIZER_DEMO.PUBLIC.email_de_token as (val string) returns string -&gt;<br>  CASE<br>    WHEN current_role() in (&#39;DEMO_ANALYST&#39;) then TOKENIZER_DEMO.PUBLIC.detokenize_string(val)<br>    ELSE val<br>  END;<br><br>ALTER TABLE IF EXISTS TOKENIZER_DEMO.PUBLIC.CUSTOMERS MODIFY COLUMN email SET MASKING POLICY email_de_token;</pre><p>This SQL snippet creates and attaches a masking policy to the table CUSTOMERS. Users with the ANALYST custom role see the detokenized email and all users without the ANALYST role see the tokenized values.</p><p>Let’s test this demo with 2 pre-created roles i.e. DEMO_ANALYST &amp; DEMO_DEVELOPER</p><p><strong>Scenario 1</strong> — Using the DEMO_DEVELOPER role — It shows UUIDs in email columns as per the policy we set before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*ofC4_gBsm73Fbb13GHfa5w.png" /><figcaption>Image 3 — Tokenized data</figcaption></figure><p><strong>Scenario 2</strong>— Using the DEMO_ANALYST role — It shows the original email ids as stored on the external datastore i.e. DynamoDB table in this case</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*CZl2mLTDjANR8ok8Tff-xg.png" /><figcaption>Image 3 — Detokenized data</figcaption></figure><p>Let&#39;s understand what happens under the hood. For any role other than DEMO_ANALYST, it&#39;s straightforward. Snowflake shows you what is stored in the table i.e. tokenized data. When the DEMO_ANALYST role queries this table, the following events happen in sequence (refer to image — 2)</p><ul><li>A user with a DEMO_ANALYST role submits the query to Snowflake</li><li>Snowflake uses the API integration object to invoke the external API i.e. API GW. This is a parallel operation and depends on the number of rows you have requested for</li><li>API GW invokes the lambda function where your detokenization logic runs</li><li>The lambda function queries the Dynamodb table and returns the original email ids to Snowflake.</li><li>Snowflake then combines these real values with other requested columns and presents back the final result to the user</li></ul><h4>Conclusion</h4><p>In this blog, we saw how can we protect confidential information in Snowflake using External Tokenization. There is also a possibility of combining this with <strong>Tag-based masking. </strong>This is a relatively new feature (enterprise only) and combines object tagging and dynamic data masking/ external tokenization.</p><p>In most cases, dynamic data masking is preferred over external tokenization due to its simplicity and less overhead of maintaining multiple components. You can expect degraded performance in tokenization due to multiple network calls, dependency on external functions &amp; databases, and lack of caching.</p><p>However, there are cases where you can use this to unlock data access. If your organization&#39;s policy does not allow you to store sensitive information outside of certain network boundaries, then External tokenization can be really handy. With this approach, tokenized data is pre-loaded into Snowflake; therefore even without applying a masking policy to a column in a table, users never see the real data value. Hence, this provides enhanced data security for the most sensitive data in your organization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29273bf2c527" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Step Functions for Massive Parallel Workflows]]></title>
            <link>https://medium.com/@saswat.sahoo.1988/aws-step-functions-for-massive-parallel-workflows-9cb8de075059?source=rss-4ce965a15d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cb8de075059</guid>
            <category><![CDATA[aws-step-functions]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-data-pipeline]]></category>
            <category><![CDATA[parallel-processing]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Saswat Sahoo]]></dc:creator>
            <pubDate>Sun, 30 Apr 2023 07:42:00 GMT</pubDate>
            <atom:updated>2023-05-01T16:27:11.251Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we will deep dive into the “<a href="https://docs.aws.amazon.com/step-functions/latest/dg/concepts-asl-use-map-state-distributed.html"><strong>Distributed Map</strong></a>” feature which makes step functions a great option for orchestrating workloads with a high degree of parallelism — even up to ten thousand concurrent tasks. In the past, step function had a “<a href="https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-map-state.html">Map</a>” state (now referred to as <strong>Inline Map</strong>) to run tasks in parallel for speeding up workflow execution. The distributed map has some additional abilities to address common challenges in the inline Map state. In the subsequent sections, I’ll show how to implement a state machine with a distributed map along with some key concepts and example code. I assume the readers have some Step Functions knowledge already, but will provide links where possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*jXWbJh6XuVyavxewSnwSRQ.png" /></figure><h4>Concepts</h4><p>What is a “Distributed Map” in the context of Step function? Before answering this let’s see what a <strong>Map</strong> is. In many functional programming, we must have seen <a href="https://en.wikipedia.org/wiki/Map_(higher-order_function)#:~:text=In%20many%20programming%20languages%2C%20map,when%20considered%20in%20functional%20form."><strong><em>map</em></strong></a> function. Below is the signature of the Python map function —</p><pre>map(a_funtion, iterable)</pre><p>The first argument is a function and the second argument is an iterable. In simple terms, an iterable is a collection of something which you can loop over. Python map(), passes each element of the collection to the specified function which performs some business logic on the input element. A more concrete example is below — Square operation is performed on each element of the numbers list and outputs a new list with squared numbers.</p><pre>def square(num):<br>    return num * num<br><br><br>numbers = [1, 2, 3, 4]<br>squared_numbers = map(square, numbers)<br><br>print(list(squared_numbers))<br># output : [1, 4, 9, 16]</pre><p>The same concept applies to Step function “<strong>Map</strong>” state with a minor but important difference. In Step function, a map state takes a JSON list as input, and some action is performed on each element of the list by a compute service (typically a lambda function or a Fargate task or a <a href="https://docs.aws.amazon.com/step-functions/latest/dg/concepts-service-integrations.html">service integration</a> API call); however in <strong>parallel</strong>. Parallel processing of tasks is the key differentiator between a Python map() function and a step function’s map state. The internal mechanics of the Step function’s Map state is quite similar to the “<a href="https://docs.aws.amazon.com/step-functions/latest/dg/concepts-service-integrations.html"><strong>MapReduce</strong></a>” programming commonly performed in Bigdata applications where a huge amount of data is split into smaller chunks and some action is performed on each chunk parallelly by a cluster of compute nodes.</p><p>Now coming to the original question — what is a “distributed map”? This is just a new mode of executing Map state with some enhanced capabilities. The main differentiating factor is the <strong>concurrency level</strong>. Now you have the option of running up to thousands of parallel tasks instead restricting to <strong>40</strong> (in Inline Map).</p><p>The distributed map has a few more notable features than its predecessor:</p><ul><li>The input to the distributed map state can be fed via a CSV/JSON file (located in S3) or S3 ListObject API action or S3 inventory result (CSV format)</li><li>The output of the map state can be written directly to an S3 bucket — this is basically an aggregation step where all output of the individual mapped task is collected in one or more files in S3</li></ul><p>The above 2 features are quite essential considering the scale at which distributed map works. Step function can pass up to 256KB of data between states which makes it impossible to utilize this concurrency level without reading input from an external location like S3.</p><p>The below image summarises the working mechanics of distributed map state. In the next section, we will see an example with some code snippets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*kzuObeyh1fUvwa_FYEAtcQ.png" /><figcaption>Image 1: Distributed Map Fundamentals <a href="https://docs.aws.amazon.com/step-functions/latest/dg/concepts-orchestrate-large-scale-parallel-workloads.html">Image Source</a></figcaption></figure><h4>An Example</h4><p>Let’s examine a real-world example where distributed maps can be useful. Consider a scenario where you are maintaining millions of files in an S3 bucket. A new requirement comes for adding an object tag(s) to all S3 files. For a handful of S3 objects, it can be done quite easily with a script or even using the console. Adding tags to millions of S3 objects in a timely &amp; efficient manner means using a complex multi-threaded application. The application becomes even more complex if we think about error handling, retries, state management, status reporting, etc.</p><p>Step function with Distributed Map comes to the rescue in this scenario. Below is a screenshot the how a step function would work in this scenario. You can find the full source code in my Github repo located <a href="https://github.com/saswatkumarsahoo/aws-step-function-examples/blob/master/src/asl/distributed_map.json">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQPm8FYoCHS04Tmml-W12A.png" /><figcaption>Image 2 — Step function workflow</figcaption></figure><p>The main components here are —</p><ul><li>An S3 bucket with objects where you want to add a new tag(s)</li><li>A step function with just one state i.e. distributed map</li><li>The map state uses SDK integration i.e. so no lambda or any other compute infra is needed for performing object tagging operation</li></ul><p>On running this state machine (with a proper payload), it starts a flood of PutObjectTag API action on each object of the bucket and completes the tagging depending on the number of objects and concurrency setting. The Map state gets the list of S3 files by calling ListObjectsV2 API action. Also at the end of the run, it will provide you a nice summary with details like —</p><ul><li>number of successes</li><li>number of failures</li><li>start &amp; time with total execution time</li><li>A link to navigate each and every execution of the map state (i.e. child workflows)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iiz3enGyhu7N-hm1bB7N-A.png" /><figcaption>Image 3 — Map Run Summary</figcaption></figure><blockquote>PS — This is a use case that is better suited to AWS S3 batch operation. however, I have used Step functions only for illustrating purposes.</blockquote><h4>Key Considerations</h4><p>Distributed mode is great and provides you a lot of power. But… with power comes great responsibility. Below are a few tuning parameters and key points you should take into account to run parallel workflows optimally without any negative side effects.</p><ul><li><strong>First, evaluate and then use </strong>— Before using a distributed map first, ask yourself a question whether you really need it. Inline mode with a concurrency level of 40 might be also sufficient for your application. So don’t pull out the big gun if you don’t need it. Analyze the conditions carefully before you make a choice. More information here — <a href="https://docs.aws.amazon.com/step-functions/latest/dg/concepts-inline-vs-distributed-map.html">https://docs.aws.amazon.com/step-functions/latest/dg/concepts-inline-vs-distributed-map.html</a></li><li><strong>Adjust the concurrency level</strong> — Executing things in parallel is great, but running thousands of parallel tasks can severely impact other parts of your application and (cloud) infrastructure. Most of the AWS services, databases, 3rd part APIs, etc. always have a service quota i.e. you can not perform transactions beyond a certain limit. For example, lambda provides a default concurrency limit of 1000 across all your functions in a region. This means you can not run more than 1000 lambda tasks in parallel even if step function allows you to do so. Also, other lambda functions in your account share this default quota. Hence, going beyond a certain level might adversely affect multiple applications. To avoid such situations you can configure the “<strong>MaxConcurrency</strong>” parameter to a limit that meets your SLA without bringing down other parts of your infrastructure</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*TpdtBedwrWbfbrLLEYPYig.png" /><figcaption>Image 4— Concurrency setting</figcaption></figure><ul><li><strong>Use batching </strong>— By default, each parallel task processes just one item from the list. For example — if you want to process a list of 1250 using lambda, then the step function will invoke the function 1250 times. For a relatively small collection, it sounds okay. But, the distributed map is meant to work on a much larger scale. Invoking a lambda function or any other API at this scale is inefficient. To mitigate this problem, You can use “<strong>ItemBatcher</strong>”. This config sends a batch of items to the downstream task to process multiple items in one invocation. You can set the batch limit based on size (up to 256KB) or a number and step function will optimally determine the batch size depending on your payload size. Assuming the processing time of items scales linearly, your workflow will take more time to finish. However, it has other advantages like better throughput, fewer service API calls, and also it is pocket friendly. With proper tuning of batching &amp; concurrency levels, you can optimize your application’s throughput and efficiency and avoid unforeseen consequences.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*Qx6l8-awr8DGaLOr8uqr0Q.png" /><figcaption>Image 5— Batch setting</figcaption></figure><ul><li><strong>Set a threshold for error tolerance — </strong>This is an optional config you can set on your map state to specify how many failures your workflow can tolerate before it terminates. Most of the time map state perform some activities on an input data set. For scenarios where you receive faulty data, fault tolerance parameters refrain you from processing the entire batch and help you avoid unnecessary costs. You can specify the tolerance based on the number or percentage of failed items as a failure threshold. Depending on which value you specify, your Map run fails automatically if this threshold is exceeded. If you specify both, the workflow fails when it exceeds either value</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*aBHA10RnDVwOVuG7clIATQ.png" /><figcaption>Image 6— Fault tolerance setting</figcaption></figure><ul><li><strong>Use ResultWriter for saving the output </strong>— This is again an optional config, however, choosing not to use this can cause workflow failures. Step function can only pass up to 256KB of data between states. If your distributed map produces an output of more than 256KB (most certainly it will), you can use <strong>ResultWriter</strong> to export the output data to S3. ResultWriter produces varieties of output files consolidating successful executions, failure executions, and a manifest file containing the location of result files. The export can also contain a large number of files depending on your output size. If you want to further process the output or perform a reduction operation you can chain another distributed/inline map to process the result files</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*4NturC2mUC0KLUbksGk5Hg.png" /><figcaption>Image 7 — ResultWriter</figcaption></figure><ul><li><strong>Know the limits</strong> — Like any other AWS service, distributed map state has also some soft limits &amp; hard limits. Understand these limits before you implement a workload in production. For example, if you are reading input from an S3 file, the Map step can read up to the first 100 million lines and stops beyond this point. If your use case requires more than these limits, you can split the files into chunks.</li></ul><h4>Wrap Up</h4><p>In this article, we have seen what a distributed Map state is, some key concepts around it, and a few best practices. Step function map state is not the only way to run large-scale parallel workloads. A lot of functionalities from the <a href="https://aws.amazon.com/s3/features/batch-operations/">AWS S3 batch</a> overlap with map execution. Similarly, with AWS EMR &amp; Glue, you can perform big data operations quite efficiently.</p><p>Before making any choices, you must carefully evaluate your use case in hand, your and your team’s core expertise (as each service needs a different tech skill), total cost &amp; ease of execution, etc.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cb8de075059" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combine the Simplicity of SQL with the Power of NoSQL (Pt-2)]]></title>
            <link>https://medium.com/@saswat.sahoo.1988/combine-the-simplicity-of-sql-with-the-power-of-nosql-pt-2-cff1c524297e?source=rss-4ce965a15d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/cff1c524297e</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws-athena]]></category>
            <dc:creator><![CDATA[Saswat Sahoo]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 04:36:01 GMT</pubDate>
            <atom:updated>2023-03-02T04:36:01.345Z</atom:updated>
            <content:encoded><![CDATA[<p>This is part two of this 2-part blog series. Part one was published <a href="https://medium.com/@saswat.sahoo.1988/combine-the-simplicity-of-sql-with-the-power-of-nosql-pt-1-9ea0c298038b">here</a>. In the first part, we learned about PartiQL which uses SQL-like syntax to query DynamoDb tables. It is worth noting that PartiQL only supports a subset of SQL and does not cover the full implementation of SQL. Also, PartiQL is meant to be used in transactional systems &amp; apps.</p><p>In this blog, we will learn about another “SQL option” to query DynamoDB. This is going to be done via <a href="https://aws.amazon.com/athena/">AWS Athena</a> and is suitable for OLAP (Online Analytical Processing) use cases.</p><h3>Overview</h3><p>DynamoDB offers NoSQL tables that do not natively support OLAP capabilities. OLAP typically requires a relational database or a data warehouse that can perform complex joins, aggregations, and other operations on table data, which DynamoDB does not provide. In this blog, we will explore how we can leverage Athena query federation to run SQL queries on a DynamoDB table and fulfill the missing OLAP capabilities.</p><h4>What is Athena Query Federation</h4><p>Athena is predominately used to query data on an S3 bucket and this was the primary purpose of using this service. In the year 2020, AWS released a new feature called “Query Federation” with Athena with a limited set of data connectors. This allowed Athena to query data stored in different sources i.e. (on-premise) relational databases such as RDS, Redshift, MySQL, etc, NoSQL databases such as MongoDB, Elasticsearch, and data stored on external cloud object stores like GCS, etc. This is quite a handy feature as you can now combine data from multiple sources without performing &amp; maintaining a complex ETL and create useful insights in real-time. <br>As you can see in the below image, Athena uses Lambda functions under the hood to connect the data sources. As the load increases lambda fans out and runs concurrent instances to optimize query performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*IUI87NJK2pm7hcx0Bwo43A.png" /><figcaption>Image Source — <a href="https://github.com/awslabs/aws-athena-query-federation">https://github.com/awslabs/aws-athena-query-federation</a></figcaption></figure><h3>Athena Query Federation In Action</h3><p>Now that we know what query federation is, let’s apply it to a sample DynamoDB table to run some queries. We will reuse the same “Movies” table we used in <a href="https://medium.com/@saswat.sahoo.1988/combine-the-simplicity-of-sql-with-the-power-of-nosql-pt-1-9ea0c298038b"><strong>part 1</strong></a> of this blog. We will run a few typical OLAP queries this time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v99SxA-LUif4e82i6cMVpw.png" /></figure><h4>Set Up Athena Data Connectors</h4><p>Before we can use Athena’s query federation, we need to set up the data connectors. Athena supports various data connectors that allow you to query data from different sources and formats. You can find the complete list of supported connectors in the AWS console or this <a href="https://github.com/awslabs/aws-athena-query-federation"><strong>GitHub link</strong></a><strong>. </strong>Also<strong>, </strong>You can develop your custom data connectors using the Athena Query Federation SDK. This allows you to query data from any data source not natively supported by Athena.</p><p>For our example, we will set up the DynamoDB connector. There are multiple ways you can use to deploy this. i.e. console, CLI/SDK, or IaC tools like CloudFormation, Terraform, etc. We will use Terraform to set this up. The Terraform code is available in this <a href="https://github.com/saswatkumarsahoo/athena-query-federation"><strong>GitHub repo</strong></a>. This project contains all the required resources (data connector, a DynamoDB table with some sample records) we need to test query federation. <br>The data connectors (backed by lambda function) are pre-baked and ready to use by AWS Serverless Application Repository (SAR). This way we can quickly deploy it without much effort. Below is a code Terraform resource code snippet which is enough to set up the DynamoDB connector.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8de861e1eb2c3b308c707b77aa92a46d/href">https://medium.com/media/8de861e1eb2c3b308c707b77aa92a46d/href</a></iframe><p>You can clone the Terraform project to your laptop and deploy it to your AWS account by running 2 simple commands.</p><pre>terraform plan<br>terraform apply</pre><p>After terraform creates the resources, you will see a new data source called “dynamodb” and the table i.e. movies_table in your Athena workspace. Now you are ready to query the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*ACVikwSNoVHziT3ho_2P8A.png" /><figcaption>image 2 — athena workspace</figcaption></figure><h4>Querying Tables</h4><p>We will execute some queries you generally use for analysis purpose —</p><ol><li>Use this query to find out which movie was voted for the most number of times</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rDNGou17TGGLM7YVehBsCw.png" /></figure><p>2. Now a query with common table expression (CTE) &amp; a subquery to figure out the highest-rated movie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FtQY1xboZwhNzW62E9AwrA.png" /></figure><p><em>Note — This is not the optimal query for this scenario. This is just for illustration to simulate commonly used query patterns for analytics.</em></p><h3>Query Federation Use Cases</h3><p>DynamoDB table is designed for transactional workload, so we should take into account a few additional factors before using it with Athena.</p><p>DynamoDB is at its best when it handles real-time transactions and is optimized for storing and retrieving individual transactions quickly and efficiently; often using GSI/LSI to support fast lookups. On the other hand, an OLAP database is designed for complex data analysis, reporting and ML workloads. Therefore, querying DynamoDB using Athena can be slower and more expensive than querying directly using DynamoDB. Performance degrades further for large tables and complex queries. Most of the queries will end up being a <strong>Scan</strong> operation in DynamoDB which gets costlier as the table size grows.</p><p>This is quite common to export data from DynamoDB to an OLAP datastore like S3 or Redshift to perform complex analytics. So what are the recommended use cases to federate queries via Athena?</p><p>Here are a few scenarios where using Athena to query DynamoDB may be useful:</p><ol><li>You want to join DynamoDB table(s) with other data sources, such as data stored in S3. (Do consider the table size and complexity of your queries beforehand)</li><li>You need to perform complex queries on your DynamoDB data that cannot be easily performed using the DynamoDB Query or Scan operations</li><li>You want to join multiple DynamoDB tables. It should be considered as a last resort if you are not able to design a single table with a denormalized and flexible schema</li><li>You want to analyze your DynamoDB data using a BI tool such as Amazon QuickSight (via Athena connectors)</li><li>You do not want to export your data via an ETL because you care about data freshness and your application can only rely on real-time data from the DynamoDB table</li></ol><h3>Conclusion</h3><p>We can conclude that Athena Query Federation is a simple (yet powerful) tool that allows you to easily query data from a variety of external data sources including a DynamoDB table using familiar SQL syntax. By leveraging this feature you can bring together data from multiple sources and gain new insights that would be difficult or impossible to obtain otherwise. It’s equally important to evaluate whether Athena Query Federation will meet your performance and cost requirements before you start using it.</p><p>Overall, DynamoDB Query Federation is an exciting addition to the AWS Athena ecosystem and will be a valuable tool for data engineers, analysts &amp; ML engineers. This provides a flexible and powerful way to access and analyze your data with ease without the need for data movement and duplication, which can help simplify your data architecture and reduce costs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cff1c524297e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combine the Simplicity of SQL with the Power of NoSQL (Pt-1)]]></title>
            <link>https://medium.com/@saswat.sahoo.1988/combine-the-simplicity-of-sql-with-the-power-of-nosql-pt-1-9ea0c298038b?source=rss-4ce965a15d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ea0c298038b</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[nosql]]></category>
            <dc:creator><![CDATA[Saswat Sahoo]]></dc:creator>
            <pubDate>Mon, 05 Sep 2022 16:41:21 GMT</pubDate>
            <atom:updated>2022-09-05T16:41:21.917Z</atom:updated>
            <content:encoded><![CDATA[<p>This is part one of a two-part blog series. It has been written with the assumption that the readers of this blog have some foundation knowledge about DynamoDB, its data structure, and the typical access patterns i.e. query v/s scan, etc. Now, Let’s get started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*lsnnVBG1VecuWtR5Z2zF0g.png" /><figcaption>Image 1</figcaption></figure><h3>Introduction</h3><p>DynamoDB offers multiple ways to interact with the service and access the underlying table data. Commonly used methods are —</p><ol><li><strong>AWS management console</strong>— The most preferred way for beginners to get started with</li><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/workbench.html"><strong>NoSQL workbench</strong></a><strong> </strong>— Nice intuitive way to perform CRUD (create, read, update &amp; delete) operation using a GUI tool installed on your laptop</li><li><strong>CLI &amp; SDKs</strong> — Preferred way for automating stuff and programming web/mobile or any other application backends</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*hy_ZppYayMA2CaBVLW74XA.png" /><figcaption>Image 2: DynamoDB API Interface</figcaption></figure><p>As illustrated in this image, irrespective of the method you chose, they all interact with the same API interface. These tools only take away the complexity of creating standardized request DynamoDB API expects and leaves us with only filling up a few required fields. Does it mean programming a DynamoDB application is simple? The short answer is <strong>YES</strong>. The long answer is — <strong>It depends on the level of familiarity with the service</strong>. For starters (especially from an SQL background), it can be a slow start to adapt to DynamoDB syntaxes. On the surface, it looks effortless to interact with tables and query/manipulate data. Most of the time, we (in this context “we” means “I”) need to look through the developer’s guide to revive our memory about syntaxes and nitty-gritty details.</p><p>In this blog, I will explain a relatively new feature in DynamoDB i.e. <a href="https://partiql.org/"><strong>PartiQL</strong></a> takes away this small, although noticable effort. We will learn how PartiQL simplifies DynamoDB table operations even further and thereby enhances our productivity.</p><h3>What is PartiQL?</h3><p>It is a <strong>SQL-compatible</strong> query language to access structured, semi-structured, and nested data. It has a wide variety of use cases, although, in the context of DynamoDB, it is used to perform CRUD operations on the table data using SQL. PartiQL is supported in all the methods I mentioned before i.e. console, CLI/SDK, and NoSQL workbench</p><h4>Why do we need it?</h4><p>Below are a few reasons one would choose PartiQL over DynamoDB DSL.</p><ol><li><strong>The simplicity of SQL</strong></li></ol><p>DynamoDB has a wide range of programming language support. Then why do we need another language i.e. SQL on top of it? <br>Let’s understand it with an example — Below is a simple table with 4 attributes —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*lb4GLEsp9bj3V8fowC-hoA.png" /><figcaption>Image 3: Movie table data structure</figcaption></figure><p>Imagine you have a mobile app where users can rate the movies by a star rating ((1- 5) system. Now, let’s see a python code snippet that updates the number of votes and stars when a user submits a rating.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd4d5741d2ba0d8d540b1b57f2173fbb/href">https://medium.com/media/fd4d5741d2ba0d8d540b1b57f2173fbb/href</a></iframe><p>Terms like <em>UpdateExpression, ExpressionAttributeValues, ExpressionAttributeNames</em> (in case you are using reserved DynamoDB keyword) are purely DynamoDB specific. It may not sound familiar or make a lot of sense when a newbie on DynamoDB looks at it.</p><p>Now let&#39;s see the PartiQL version of the same scenario —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c53447b29484f9577129c000cf480ded/href">https://medium.com/media/c53447b29484f9577129c000cf480ded/href</a></iframe><p><em>The UPDATE</em> <em>SQL</em> statement looks quite familiar already. It does not involve any DynamoDB-specific keywords. It uses an SQL statement to update the item in a NoSQL table. As the title of this blog says — Now you can harness NoSQL power by SQL’s simplicity.</p><p>2. <strong>Easy to learn</strong> — Although there is a learning curve to understand PartQL, it is relatively less compared to traditional DynamoDB DSL. SQL is a very well-known language among most software engineers. Taking this assumption into account, it would be easier to switch to a NoSQL database like DynamoDB.</p><p>3. <strong>Faster Development </strong>—As compared to the older approach, PartiQL allows one to increase productivity since less time is spent looking at AWS documents. Writing SQL code feels quite natural without memorizing a lot of DynamoDB terms.</p><h3>Key Considerations while using PartiQL</h3><p>Things you can perform with PariQL —</p><ol><li>CRUD operations on a DynamoDB table are supported</li><li>Actions like query &amp; scan can be replaced with SELECT statements with appropriate predicates in the “WHERE” clause</li><li>You can also use it on table indexes i.e. global secondary index (GSI) &amp; local secondary index (LSI)</li></ol><p>Things to keep in mind while using PartiQL —</p><ol><li>Now that you can use SQL statements to access a DynamoDB table, it does not mean that you can run COUNT() function. The LIMIT clause is not supported either.</li><li>The main purpose is to complement the existing methods by adding SQL simplicity</li><li>PartiQL on DynamoDB is strictly for OLTP use cases. In part 2 of this blog, I will explain how you can run OLAP queries on DynamoDB</li><li>You might wonder whether PartiQL is faster/slower than traditional methods GetItem/PutItem etc. And what about Query v/s Scan? Does it vanish with the introduction of PartQL? The answer is — they are all there under the hood. PartiQL queries are translated internally to make it DynamoDB API-supported format; hence it is transparent to the end users.</li><li>It is free of cost and AWS does not charge any extra cents. However, it is quite easy to make a mistake while writing a SELECT statement. If the “WHERE” clause involves non-key attributes (other than PK &amp; SK), it will result in a table scan. It can cause performance and cost penalties. You can restrict tables scan by putting an additional condition in the <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-iam.html#access-policy-ql-iam-example6"><strong>IAM policy</strong></a>.</li></ol><h3>Sample Code</h3><p>Here are a few samples of CLI commands using PartiQL to perform CRUD operations on the “Movies” (Ref — Image 2)table.</p><ol><li>Create an item</li></ol><pre>aws dynamodb execute-statement --statement &quot;INSERT INTO movies VALUE <br>{&#39;year&#39;:1996,&#39;title&#39;:&#39;mission impossible&#39;, &#39;num_votes&#39;:90, &#39;total_stars&#39;:360}&quot;</pre><p>2. Query/Read an item (Note — You can also use operators such as IS, LIKE, IN, NOT IN, CONTAINS, BEGINS WITH, etc.)</p><pre>aws dynamodb execute-statement --statement &quot;select * from movies where year=1996 and title = &#39;mission impossible&#39;&quot;</pre><p>3. Update an item</p><pre>ws dynamodb execute-statement --statement &quot;update movies set total_stars=400 where year=1996 and title=&#39;mission impossible&#39;&quot;</pre><p>4. Delete an item</p><pre>aws dynamodb execute-statement --statement &quot;delete from movies where year=1996 and title = &#39;mission impossible&#39;&quot;</pre><h3>Conclusion</h3><p>In this blog, We learned how PartiQL is capable of simplifying app programming on DynamoDB. The main takeaway is that — if you are already proficient at accessing tables using the traditional approach, then you will not benefit a lot from PartiQL except to have one more option. For those just getting started with DynamoDB, PartiQL can provide a great headstart without requiring too much effort. We should also keep in mind that — PartiQL is strictly for OLTP use cases. In the second part of this blog, I will explain a way to run “OLAP” workload on DynamoDB. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ea0c298038b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom CloudWatch Metrics from Lambda Functions]]></title>
            <link>https://medium.com/@saswat.sahoo.1988/custom-cloudwatch-metrics-from-lambda-functions-d5373a67bc34?source=rss-4ce965a15d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5373a67bc34</guid>
            <category><![CDATA[aws-lambda-functions]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloudwatch]]></category>
            <category><![CDATA[cloudwatch-logs]]></category>
            <dc:creator><![CDATA[Saswat Sahoo]]></dc:creator>
            <pubDate>Sat, 23 Apr 2022 16:20:26 GMT</pubDate>
            <atom:updated>2022-04-23T16:20:26.565Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will explain different methods that a lambda function can use to create custom cloudwatch metrics. Lambda pushes a few default metrics to cloudwatch; for example number of invocations, success rate, error counts, execution time, etc. These metrics are published once a minute and free of cost. Ops team depends on these stats to monitor a lambda function and take corrective action in case of abnormalities. <br>Many times you require business insights &amp; KPIs from lambda. While developing a function, we often focus only on the functional requirements and fail to utilize the full potential of this service. Cloudwatch is a great service to collect and monitor metrics in (near)real-time. AWS offers a lot of integration options between lambda and cloudwatch. Considering these at an initial stage of development can not only provide you right business metrics but also save you from re-designing your function architecture. In the subsequent section, we will see it in more detail with a hypothetical use case.</p><h4>Concepts</h4><p>There are a few cloudwatch nomenclatures we should be familiar with before diving into the actual implementation<br><strong>Metric</strong>: It is the value of a variable over time. For example, EC2 instance publishes the CPU usage to cloudwatch and it is stored in cloudwatch service as a time-ordered list of data points. This can be plotted in a 2-dimensional graph where X-axis represents the timestamp &amp; Y-axis represents the CPU usage. In this context, we can say CPU utilization is a metric of the EC2 instance.</p><p><strong>Namespace</strong>: Each metric in cloudwatch is stored in a container called a namespace. This makes sure that metrics from different AWS services are isolated from each other. CPU utilization of an EC2 instance &amp; an RDS instance is stored under 2 separate namespaces i.e. <em>AWS/EC2</em> and <em>AWS/RDS</em> respectively. With this separation, we accidentally do not mix the metrics of one service with another.</p><p><strong>Dimension</strong>: Metric contains a key/value pair (minimum 1 &amp; maximum 10) and acts as an identifier of the metric. For example, Amazon EC2 metric publishes InstanceId as a dimension name and the actual instance ID as the value for that dimension.</p><p>The below image consolidates all these concepts. Here “CPU Utilization” and “DiskWrite Bytes” metrics are published in the “AWS/EC2” namespace and are distinguished by their dimension instance_id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*fNA0AwNWbrkZkPLIDR69pA.png" /><figcaption>Image 1: Cloudwatch Concepts</figcaption></figure><h4>Use Case</h4><p>Let’s take a hypothetical use-case of a movie ticket booking portal. This application is built by a number of microservices and backed by single-purpose lambda functions for each service i.e. ticket booking service, cancellation service, user login service, etc. For simplicity let&#39;s focus on only one service — “TicketBooking”. Our goal is to visualize the number of tickets booked per movie in near real-time. We will see 4 different approaches to fulfill this requirement and compare the pros/cons.</p><h4>Approach 1: Using Cloudwatch API</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*GexZdxDGQB1gZoWk-HYycQ.png" /><figcaption>Image 2: Cloudwatch REST API</figcaption></figure><p>This is by far the simplest and most straightforward solution to publish a custom metric.</p><p>If you are familiar with AWS SDKs, you already know that all the AWS services provide APIs to interact with the underlying service. Cloudwatch metric is no different than the rest. Below is a sample python code. It selects a movie from the movies list and publishes a custom metric — random ticket count (between 1 and 5).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/069edb2f87cd39e4eb0350aec7b0015d/href">https://medium.com/media/069edb2f87cd39e4eb0350aec7b0015d/href</a></iframe><p>This information is instantly available on the cloudwatch dashboard for visualization. In the below image, you can see the “<em>BookedTicketsCount</em>” metric is collected under the namespace “<em>MovieTicketPortal</em>”. Each metric holds a dimension key “<em>movie_name</em>” and the actual name of the movie which answers how many tickets were booked per movie</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*Yrpp_63Dw3jFHoYL4NX2DQ.png" /><figcaption>Image 3: Cloudwatch Metric Console</figcaption></figure><p>Pros: — <br>1. Easy to implement with a few lines of code<br>2. ̶(̶N̶e̶a̶r̶)̶ Real-time availability of metrics</p><p>Cons: — <br>1. It is synchronous i.e. it&#39;s a network call and blocks the code execution until it receives a response back from API. This tends to increase the lambda runtime and thereby increases the overall cost.<br>2. Tight coupling between functional &amp; non-functional requirements, so not considered a development best practice.</p><p>In most cases, you will refrain from using this option due to these shortcomings. The only advantage over the rest approaches is that it is real-time. As soon as lambda finishes, your dashboard will be up to date with live data. However, most companies can live with near real-time solutions. If you do not have such stringent requirements, one of the subsequent options is the way to go.</p><h4>Approach 2: Using Cloudwatch Metric Filter</h4><p>Lambda emits all the request logs and function logs automatically to CloudWatch(provided the function has required IAM permissions). The default log group associated with the lambda function is named as <em>/aws/lambda/&lt;function name</em>&gt;. In this section, we will leverage this log group and extract custom metrics.</p><p>Cloudwatch provides a feature called “<a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/MonitoringLogData.html">Metric Filter</a>”. It is useful for searching &amp; filtering logs. Additionally using a “metric filter” you can convert log data into numeric values/metrics by pattern matching. These numeric values can be later used to graph &amp; visualize. Look at the below code snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82aabb447b8dbf15439e6ec4d7412e45/href">https://medium.com/media/82aabb447b8dbf15439e6ec4d7412e45/href</a></iframe><p>It emits a space-delimited logline with movie and ticket information. Sample log from the console—</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SM_nDIp0bn2OmuIr6_vKvA.png" /><figcaption>Image 4: Cloudwatch Logs</figcaption></figure><p>Look at the 2nd logline: “<strong>TICKET_BOOKING_SERVICE 5 tickets booked for Troy</strong>”. you can extract the metrics using a filter pattern like this —</p><pre>[w1=TICKET_BOOKING_SERVICE, ticket_count, ... , movie_name]</pre><p>How does this pattern work??</p><p>In a <strong>space-delimited</strong> logline, you specify a variable for each field/word. The Metric filter then interpolates each variable with the actual value. Ellipsis (triple dots <strong>…</strong>) is used when you don’t know the number of fields beforehand or you don’t want to parse them into a pre-defined variable. Also, notice the equality comparison <strong>w1=TICKET_BOOKING_SERVICE</strong>. This makes sure that loglines that don’t start with this string are filtered out.<br>In the above example <em>ticket_count (5 tickets) </em>and <em>movie_name(troy)</em> appear in the 2nd and last position of the logline. So cloudwatch match them like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*sV0X1JE5POI-dbMgHZFoEA.png" /><figcaption>Image 5: Metric Filter</figcaption></figure><p>Now that you know the filter pattern, you can create a metric using this CLI command (or AWS console). This command will create a filter pattern on the lambda’s log group and start publishing metrics to cloudwatch whenever there is a pattern match.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/572296fec571fc8e77f36ac02f30d5cf/href">https://medium.com/media/572296fec571fc8e77f36ac02f30d5cf/href</a></iframe><p><strong>Pros</strong>:<br>1. Asynchronous in nature and requires minimal configuration<br>2. Supports both structured (JSON) and unstructured logging (space-delimited)<br>3. Suitable for simple use cases<br><strong>Cons</strong>:<br>1. For each lambda it should be defined separately. It can be a tedious task if you need to manage a lot of functions<br>2. Logs should have some unique string identifier for pattern matching, else it can produce unwanted results. This takes away some flexibility in modifying the application logging structure. If you change the log format, you need to modify the pattern accordingly.</p><h4>Approach 3: Embedded Cloudwatch Logs</h4><p>Embedded cloudwatch logs allow us to ingest high-cardinality application data in the form of logs and extract metrics from them. If you generate logs in a specific format i.e. <strong>Embedded Metric Format </strong>(EMF), then cloudwatch automatically transforms the logs into custom metrics asynchronously. Take a look at this JSON snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb99654b9fe8981b8b4887e9411d851f/href">https://medium.com/media/cb99654b9fe8981b8b4887e9411d851f/href</a></iframe><p>You can emit this JSON log to cloudwatch and forget about any additional configuration or API calls. Cloudwatch will automatically parse the metrics from logs and publish them within the namespace(see line 18) and dimension (see line 9) you define. You can generate the log in this structure manually Or you can pick one of some open source libraries based on your choice of programming language.</p><p><a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Libraries.html">Using the client libraries to generate embedded metric format logs</a></p><p>In this context, it is worth mentioning <a href="https://awslabs.github.io/aws-lambda-powertools-python/latest/">“Lambda PowerTools</a>”. This is an open-source library for lambda functions for adopting observability best practices i.e. logging, tracing, custom metrics, parameter utility, etc. Powertool has support for the lambda layer which eases the adoption of this package. Currently, it&#39;s available for python only, but there is a roadmap for other languages too.</p><p>If you are planning to use EMF for logging, it&#39;s advisable to use powertools over the other libraries as you get added advantage of other utilities. With a few sample lines from powertools library, you can adhere to AWS recommended best practices for serverless applications.</p><p><strong>Pros</strong>:<br>1. EMF also allows you to publish additional attributes which then can be searched via cloudwatch log insights. This way you can publish some meaningful contextual information along with the metric. <br>2. Due to the JSON logging format indexing logs with external services like Splunk/ELK is much simpler <br>3. Asynchronous and no extra configuration is needed. <br><strong>Cons</strong> — I can not think of any as this is my preference over the other two options ;)</p><h3>Conclusion</h3><p>We saw 3 ways to create custom metrics in AWS. Also, we saw the benefits and shortcomings of each approach. These are not limited to lambda, rather they are applicable to any application running on EC2, ECS, or even on-premise. As long as your application can reach the Cloudwatch service endpoint you can pick any of these options and create powerful dashboards using custom metrics. With lambda, many things simply work out of the box due to its tight integration with cloudwatch log service.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5373a67bc34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Identity Federation In AWS (Pt. 1)]]></title>
            <link>https://medium.com/@saswat.sahoo.1988/identity-federation-in-aws-pt-1-33fb69f540c6?source=rss-4ce965a15d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/33fb69f540c6</guid>
            <category><![CDATA[cognito-identity-pool]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-iam]]></category>
            <category><![CDATA[identity-federation]]></category>
            <category><![CDATA[cognito-user-pools]]></category>
            <dc:creator><![CDATA[Saswat Sahoo]]></dc:creator>
            <pubDate>Mon, 15 Nov 2021 19:17:08 GMT</pubDate>
            <atom:updated>2021-11-15T19:17:08.919Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, I will explain how you can set up a federation with AWS for a web and mobile application using external identity providers like Facebook, Google, Apple, or any other OIDC compatible identity provider (Idp). This is going to be a <strong>2 part</strong> series. In this first part, I will walk you through the solution using AWS Cognito Identity pool service. In the next part, we will understand the limitations of this solution and how we can extend it to make it better.</p><h4><strong>What is Federation? Why is it needed?</strong></h4><p>Most of the modern apps have features like “Sign in with Google”, “Login with Facebook” and a few more options like Twitter, Amazon, Apple, etc. I as the “blog author” signed in with medium using my google account. And, you as a reader might be using one of the above options to log in. We are using the “federation” already by doing so. In simple terms, an identity federation is a process of delegating a user’s authentication to an external trusted entity. Thereby gained several benefits for both application users and application developers. <br>As a user, it is one less password to remember. The login process is seamless. We do not even manually log in using our credentials as most likely there is an active session on our devices. <br>As an application developer, it is one less system to manage. Identity management is a complex process and requires real expertise to get it right on the first attempt. Also, asking users to fill up a registration form makes the application less attractive and most likely users will give up before even using it. How many times it has happened that we download an app from the play store and the first thing it asks us to do “Sign up” is by filling up a form. We end up uninstalling it right away.</p><p>Clearly identity federation is a win-win for both parties.</p><h4>Identity Federation in AWS</h4><p>By default, we depend on AWS IAM to authenticate ourselves to use AWS services. In a corporate environment, it might be slightly different. AWS console or CLI access is gained by enterprise username and password. This is also federation and generally, the IT department is the target audience for such setup. Corporate employees use SSO to login into AWS console/CLI and develop applications on the cloud. In this blog, I will not focus on this scenario, rather talk about identity federation for customer-facing applications. <br>Imagine you want to develop a mobile app using AWS services where users upload their photos and it guesses their age. You anticipate it will be popular one day and attract a large audience. Without spending too much effort on building your own identity store, you would like to leverage external trusted identity provides like Google, Facebook, etc. <br>For the end-user, the flow will look like below —<br>1. User opens the app and selects “Login with Google” or any other Idp. It takes the user to the Idp’s sign-in page. <br>2. After successful login user is redirected back to the app<br>3. User uploads a photo and receives the result (hopefully a number close to the user’s age so he/she is not offended) as soon as the app completes the backend processing.</p><p>As AWS is the target platform for this app, S3 instantly strikes as the most suitable service for storing pictures. The backend process can be one of the AWS AI services or custom homebrew model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*dzk41zBjUf2HSB8icOlztQ.png" /><figcaption>Figure 1 — Application Flow</figcaption></figure><p>How can you allow such external users (can scale to millions) to access the S3 bucket in a secure way? There are a few options —</p><ol><li>Make S3 bucket public — <strong>Never do it unless there is a compelling reason.</strong></li><li>Create IAM credentials for each user — Does not sound feasible to create an IAM user for each app user.</li><li>Create an IAM service user and embed its credentials in the app — Not a security best practice as you may end up disclosing it to the entire world. Even if you are able to successfully hide it, you may never get a green signal from yoursecurity officer.</li><li><strong>Use identity federation</strong> — We will use this approach. In the next section, we will go through step by step how to set it up. Instead of using google or any external Idp, we will use AWS Cognito user-pool as an identity store. The approach will be the same for all the OIDC providers.</li></ol><h4>Build the Infrastructure</h4><p>Let’s set up a bare minimum infrastructure to demonstrate identity federation. The cloudformation template is available <a href="https://raw.githubusercontent.com/saswatkumarsahoo/identity-federation-example/master/infra_part_1/template.yml"><strong>here</strong></a></p><p>It will set up a few things for us —</p><ol><li><strong>Cognito Identity Pool</strong> — This is the service that will facilitate federation. It enables us to grant external users access to AWS services with and without authentication. For the purpose of this blog, we will only cover authenticated access.</li><li><strong>Cognito User Pool</strong> — This is also a service under the AWS Cognito portfolio and used a user directory service (OIDC compliant). Common requirements for user identity lifecycle management like signup, sign-in. change/forgot password, MFA login, etc. are provided out-of-the-box by Cognito user pool.</li><li><strong>S3 bucket</strong> — For storing user’s photos</li><li><strong>IAM role </strong>— It will be assumed by the end-user after successful login with the Idp.</li></ol><p>The cloudformation stack will produce the below output. Copy the stack output. We will use it in the next step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BsAQdaGS8SVRMK1rBtL9tw.png" /><figcaption>Figure — 2 Output from Cloudformation</figcaption></figure><h4>Let’s Run the App</h4><p>Now that our infra is ready, we can see identity federation in action. Instead of a mobile app, we will use a simple python app to simulate the below flow. The application code is available <a href="https://github.com/saswatkumarsahoo/identity-federation-example/"><strong>here</strong></a><strong>.</strong></p><p><strong>Pre-requisites<br></strong>1<strong>. </strong>Python3<br>2. AWS CLI</p><p>Clone the app to your local and follow the steps below:</p><p><strong>Step 1</strong>: Open the <strong>.env</strong> file from the root folder of the app. Replace the placeholders using cloudformation output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*mwDma0tQ_JIN6G9rIk0cqw.png" /><figcaption>Figure — 3 .envfile</figcaption></figure><p><strong>Step 2</strong>: Create a demo user in the Cognito user pool using AWS CLI. Replace the &lt;client_id&gt; with the clientId copied from cloudformation output. (Provide a valid email id as it will send a one time token)</p><pre>aws cognito-idp sign-up --client-id &lt;client_id&gt; --username &lt;email_address&gt; --password &lt;password&gt;</pre><p>You will receive a one-time token in your email to verify the user registration. Replace the &lt;otp&gt; you received in the email.</p><pre>aws cognito-idp confirm-sign-up --client-id &lt;client_id&gt; --username &lt;email_address&gt; --confirmation-code &lt;otp&gt;</pre><p>Now you have successfully created a user in the Cognito user pool. We will establish federation using this user and upload a object to S3 in thee next step.</p><p><strong>Step 3</strong>: Run the python application using the below commands(replace username and password used in step 1)</p><pre>python3 -m venv venv<br>pip intsall -r requirements.txt<br>python3 main.py &lt;username&gt; &lt;password&gt;</pre><p>If everything goes well, you will see a message on the terminal that a file has been uploaded to the S3 bucket successfully.</p><p><strong>What just happened?</strong></p><p>Let’s walk through the application flow (Refer to figure 4)</p><ul><li>The user we created in step 2 is authenticated against the Cognito user pool (Login provider in this case). As a result of the successful login, the app received 3 JWT tokens i.e. IdToken, AccessToken, and RefreshToken. Each of the tokens has its own usage. Without going into details, we just need IdToken for our use case. API used for this step <a href="https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html"><strong>InitiateAuth</strong></a></li><li>The app then requests an identity from Cognito Identity Pool by providing the IdToken (valid up to 60 minutes by default). Cognito Id Pool validates the token (it performs checks like whether the token is expired, the token provider is trusted or not, etc.). If the validation is successful, it returns an Identity. API used for this step <a href="https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetId.html"><strong>GetID</strong></a></li><li>This identity is used to request AWS STS credentials which are then used to access the S3 bucket and upload a file. API used for this step <a href="https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html"><strong>GetCredentialsForIdentity</strong></a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6AV1obCUovnI08nwZ3Bjg.png" /><figcaption>Figure 4: Image reference: <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/authentication-flow.html">Link</a></figcaption></figure><p>You can also verify in the AWS console (inside the Cognito service page) that a new identity has been created in your identity pool. If the same user logs in next time, Cognito will return the existing identity instead of creating a new one. And a new STS token is generated for the subsequent logins.</p><p>This example app can be used to facilitate federation with any of the supported Idp below (Figure 5). You can configure additional social identities using a single Cognito id pool and thereby provide multiple types of login options in your web and mobile app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KIwdtPILjs78_HoSpOeSRw.png" /><figcaption>Figure — 5 Cognito Identity pool configuration</figcaption></figure><h4>Clean Up</h4><p>After finishing the steps you can destroy the cloudfromation stack. The services used in this example will not cost anything as everything is covered under free-tier.</p><h4>Wrap Up</h4><p>In less than 5 steps we saw how simple it is to set up an identity federation in AWS. We used a python application to establish federation. However, the concept and steps are applicable to any app irrespective of its language. In the next part, we will see how we can improvise on the existing setup by applying operational and security best practices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33fb69f540c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Step Function SDK Integration— No More Lambdas ?]]></title>
            <link>https://medium.com/@saswat.sahoo.1988/aws-step-function-sdk-integration-no-more-lambdas-76aa023ec477?source=rss-4ce965a15d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/76aa023ec477</guid>
            <category><![CDATA[aws-step-functions]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <dc:creator><![CDATA[Saswat Sahoo]]></dc:creator>
            <pubDate>Wed, 27 Oct 2021 19:27:01 GMT</pubDate>
            <atom:updated>2021-10-27T20:14:05.376Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS Step Function SDK Integration— No More Lambdas?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*rdPZi8cqGj2yMEvx1Kf8zQ.png" /></figure><p>AWS step function was launched during the 2016 re-invent. Just like any other AWS service, step-functions was also launched with a limited set of capabilities. Over the years AWS has been piling up with tons of new feature enhancements to this service by which makes it a default choice among AWS customers for creating serverless workflows. In this blog post, I will talk about one of the major releases i.e. <a href="https://aws.amazon.com/about-aws/whats-new/2021/09/aws-step-functions-200-aws-sdk-integration/"><strong>SDK integration</strong></a> AWS has announced recently. With this change, we can now integrate Step functions with more than 200 AWS services and over 9000 APIs with minimal code. I will explain how to use SDK integration in step functions with an example and how does it change the way we are creating state machines so far.</p><h3>Problem In Hand</h3><p>Step functions are a chain of tasks orchestrated one after another to accomplish a multi-step workflow. A task performs a single unit of work and hands over the result to the next task. Generally, these tasks are single- purpose applications built using lambda functions. Apart from lambda functions, Step functions also support <a href="https://docs.aws.amazon.com/step-functions/latest/dg/connect-supported-services.html"><strong>optimised service integration</strong></a> patterns. To reduce excessive usage lambda function and to keep things simple and tidy, it is recommended to use one of the available optimised service integration over lambda. However, these integrations are limited to only 17 AWS services with 46 integrations. (as of writing this blog). Therefore, most of the time developers end up writing a lambda function for every each task of the workflow.</p><p>Using a handful of lambda functions for simple workflows does not have a negative side effect in terms of cost and maintainability. For complex applications, however we end up writing so many lambda functions and the number of AWS resources just grows. We should not forget that each lambda function needs to have at least an IAM role, a cloudwatch log group, and configuration of its own i.e. subnets (if inside VPC), security groups, memory, timeout, environment variables etc. These are just a lot to manage. And at scale the overall cost will just increase.</p><p>In the next section, you will see how the <strong>SDK integration </strong>pattern can help us overcome this problem.</p><h3><strong>Example</strong></h3><p>Let’s consider a simple workflow:</p><ol><li>User/an application drops a file to an S3 bucket</li><li>First the file is validated. If the validation is successful then file is copied over to another S3 bucket for downstream processing. Else, it is moved to a separate S3 location for debugging error cause.</li><li>File content isread and then inserted into a DynamoDB table</li><li>The processed file is archived</li><li>Original file from step 1 and processed files are deleted</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pPzUXhdsCDZWi2yVczMqbg.png" /><figcaption>Figure 1: Visual representation of state machine</figcaption></figure><p>As we can see from figure 1, Building a simple file processing workflow needs a minimum of 5 lambda functions (for simplicity I have only considered happy path and excluded the branch for the failure scenario, try/catch and retry states).</p><p>Now, let’s talk about what can be changed with the SDK integration pattern i.e. call it “<strong>the new way</strong>”.</p><h4>What is it? And How to use it?</h4><p>Step function SDK integration allows calling an AWS API directly from the workflow using <a href="https://states-language.net/spec.html">Amazon State Language i.e ASL</a>. Instead of wrapping an API action inside a lambda function, we can directly call an API from the step function’s execution environment. In the above example, “CopyFile” task copies a file from one S3 bucket to another. Lambda function calls “<a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_CopyObject.html"><strong>CopyObject</strong></a>” api with required parameters to perform the file copy operation. With the new approach, we can simply replace the lambda function this code snippet</p><pre>&quot;Resource&quot;: &quot;arn:aws:states:::aws-sdk:<strong>serviceName:apiAction.[serviceIntegrationPattern&quot;]</strong></pre><p>where <strong>serviceName</strong> corresponds to AWS service e.g. s3, ec2, dynamodb etc. <strong>apiAction</strong> = Name of the api in <strong>camelCase</strong> e.g. copyObject, getObject etc.<br><strong>serviceIntegrationPattern</strong> = can be one of the supported patterns listed <a href="https://docs.aws.amazon.com/step-functions/latest/dg/connect-to-resource.html"><strong>here</strong></a></p><p>Additionally, we need to provide the parameters (in <strong>PascalCase</strong>) an API needs. This can be found in AWS documentation.</p><p>In our example, for the “CopyFile” task we need to replace the lambda task with the code snippet and we have 1 lambda less in the pipeline. The complete code block will look like this —</p><pre>&quot;Resource&quot;: &quot;arn:aws:states:::aws-sdk:s3:copyObject&quot;,<br>&quot;Parameters&quot;: {<br>  &quot;Bucket.$&quot;: &quot;$.destBucket&quot;,<br>  &quot;Key.$&quot;: &quot;States.Format(&#39;process/{}&#39;,$.key)&quot;,<br> &quot;CopySource.$&quot;: &quot;States.Format(&#39;{}/inbox/{}&#39;,$.sourceBucket,$.key)&quot; <br> }</pre><h4>Let’s see it in action</h4><p>Now let’s run the example workflow. You can create it straight from the console using Amazon State Language (just copy &amp; paste the below code in console) or <a href="https://aws.amazon.com/blogs/aws/new-aws-step-functions-workflow-studio-a-low-code-visual-tool-for-building-state-machines/">Step Function Workflow Studio</a>. Or using any IaC tool like Cloudformation, CDK, or Terraform. For this blog, I have chosen CDK. Complete code is available <a href="https://github.com/saswatkumarsahoo/stepfunctions-sdk"><strong>here</strong></a>. You can also find the instructions on how to run the application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ad9495d64509702aafef9b45c168904/href">https://medium.com/media/0ad9495d64509702aafef9b45c168904/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*60dIVMLkDnIB2ywLLSE6zw.png" /></figure><p>Above we have the ASL snippet, and on the left we have the visual representation of it. All the S3 file operations i.e. copy, read, delete are just API calls straight from state machine code. It is also worth mentioning that you can call these APIs in parallel using map or parallel state (see the “DeleteFile” task). We can call any of the supported service APIs in parallel without having to write any complex multi-threaded code.</p><h4>Things to consider additionally</h4><ol><li>Using SDK integration requires more access on the Step function side. the IAM permissions attached to a lambda function is shifted to the step function’s role</li><li>There are some overlaps between SDK integration and optimised service integration. For example, you can send a message to a SQS queue using either of the options. Choose one depending on your use case. One benefit of optimised pattern is that it supports <a href="https://docs.aws.amazon.com/step-functions/latest/dg/connect-to-resource.html#connect-sync"><strong>synchronous</strong></a> task execution, unlike SDK. It eliminates the necessity of wait loops in workflows where downstream tasks are explicitly dependent on the upstream job completion.</li><li>Make use of <a href="https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-intrinsic-functions.html"><strong>intrinsic function</strong></a> as much as possible — These are great additions to step function capabilities and provide a lot of flexibility in the transformation of request/response payload</li><li>Be careful while passing api responses to the subsequent step. You may hit the service limit if you do not handle it carefully. For example- Reading a large file from S3 and passing the file content to the next task will error out as it exceeds the <a href="https://docs.aws.amazon.com/step-functions/latest/dg/limits-overview.html#service-limits-task-executions">service limit</a>. It is a best practice to only pass relevant information between steps using available <a href="https://docs.aws.amazon.com/step-functions/latest/dg/concepts-input-output-filtering.html"><strong>filters</strong></a></li><li>Make sure to verify the list of supported services and APIs before considering SDK integration. A complete list of services is available <a href="https://docs.aws.amazon.com/step-functions/latest/dg/supported-services-awssdk.html"><strong>here</strong></a></li></ol><h3>Conclusion</h3><p>The title of the blog says “<strong>No more lambdas ?</strong>”. Is it true? The short answer is — <strong>NO</strong>. And the long answer is — it depends on the use case you are building. In most of the production applications, we do more than just one API call inside a lambda function. For executing business logic we need a compute environment — it may be a lambda or an ECS task or some third-party API. So it is very early days to say we can build a step function in a lambda-less manner. Nevertheless, introduction of this feature is not to remove lambda functions, rather to use lambdas the right way. I say SDK integration is worth of a try. It promotes the agenda — “Configuration over Code”. It is not only better in terms of cost and maintenance but also simplifies building complex workflows in a low-code &amp; declarative fashion.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76aa023ec477" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>