<?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 Abhra Prakash Deb on Medium]]></title>
        <description><![CDATA[Stories by Abhra Prakash Deb on Medium]]></description>
        <link>https://medium.com/@abhra-deb?source=rss-ab6ef0efbf8e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*m8h9aDWb7jU7UZ6S</url>
            <title>Stories by Abhra Prakash Deb on Medium</title>
            <link>https://medium.com/@abhra-deb?source=rss-ab6ef0efbf8e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 05:14:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhra-deb/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[Securing APIs with HMAC Digital Signatures]]></title>
            <link>https://abhra-deb.medium.com/securing-apis-with-hmac-digital-signatures-fb4aa7d5333e?source=rss-ab6ef0efbf8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb4aa7d5333e</guid>
            <category><![CDATA[api-security]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[man-in-the-middle-attack]]></category>
            <dc:creator><![CDATA[Abhra Prakash Deb]]></dc:creator>
            <pubDate>Sat, 13 Jul 2024 05:38:51 GMT</pubDate>
            <atom:updated>2024-07-13T05:38:51.692Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In today’s digital landscape, securing APIs is of paramount importance. APIs, or Application Programming Interfaces, are the backbone of modern web applications, enabling different software systems to communicate and share data. However, this communication can be susceptible to various security threats, including man-in-the-middle attacks, where an attacker intercepts and potentially alters the data being transmitted between the client and server.</p><p>One effective method to secure API communications is through HMAC (Hash-based Message Authentication Code) digital signatures. HMAC ensures the integrity and authenticity of a message, making it a crucial tool for securing APIs. In this blog, we will delve into the concept of HMAC digital signatures, their importance in API security, and provide implementations in both ReactJS and Spring Cloud Gateway.</p><h3>What is HMAC?</h3><p>HMAC is a specific type of message authentication code (MAC) involving a cryptographic hash function and a secret cryptographic key. It combines the hash function with the secret key to produce a hash value that is unique to the message and key. HMAC provides both data integrity and authenticity, ensuring that the message has not been altered and that it comes from a legitimate source.</p><h3>How HMAC Works</h3><ol><li><strong>Hash Function</strong>: A cryptographic hash function (such as SHA-256) is used.</li><li><strong>Secret Key</strong>: A secret key known only to the sender and receiver.</li><li><strong>Message</strong>: The data that needs to be authenticated.</li></ol><p>The process involves the following steps:</p><ol><li>The message is concatenated with the secret key.</li><li>The concatenated string is hashed using the hash function.</li><li>The resulting hash is the HMAC signature.</li></ol><p>When the receiver gets the message and HMAC signature, they repeat the process using the same secret key. If the computed HMAC matches the received HMAC, the message is verified.</p><h3>Importance of HMAC in API Security</h3><p>HMAC plays a critical role in securing API communications by:</p><ul><li><strong>Ensuring Data Integrity</strong>: Any changes to the message will result in a different HMAC, allowing the receiver to detect tampering.</li><li><strong>Authenticating the Sender</strong>: Only parties with the secret key can generate the correct HMAC, ensuring the message is from a trusted source.</li><li><strong>Preventing Replay Attacks</strong>: By including timestamps or unique nonces in the message, HMAC can help prevent replay attacks.</li></ul><h3>Implementing HMAC in ReactJS</h3><p>To demonstrate how HMAC can be used in a client-side application, let’s implement HMAC in a ReactJS application. We will generate HMAC signatures for the URL, query parameters, and the body of a request.</p><p><strong>Install the crypto-js library</strong></p><blockquote>npm install crypto-js</blockquote><p><strong>Create a utility function for generating HMAC</strong></p><pre>import CryptoJS from &#39;crypto-js&#39;;<br>export const generateHMAC = (message, secret) =&gt; {<br> return CryptoJS.HmacSHA256(message, secret).toString(CryptoJS.enc.Hex);<br>};</pre><p><strong>Generate HMAC for URL, Query Parameters, and Body</strong></p><pre>const secret = &#39;your-secret-key&#39;;<br>const generateHMAC = () =&gt; {<br>const message = `${url}?${queryParams}${body}`;<br>const hmacSignature = generateHMAC(message, secret);<br>headers: { &#39;Content-Type&#39;: &#39;application/json&#39;, &#39;X-HMAC-Signature&#39;: hmacSignature}<br>};</pre><h3>Implementing HMAC Validation in Spring Cloud Gateway</h3><p>Spring Cloud Gateway is a popular framework for building API gateways on top of Spring Boot. It provides a flexible way to route requests and apply various filters and predicates. Here, we will implement HMAC validation in Spring Cloud Gateway to secure incoming API requests.</p><h3>Step-by-Step Implementation</h3><p><strong>Create a filter for HMAC validation</strong></p><pre>public class DigitalSignatureValidationFilter<br>  extends AbstractGatewayFilterFactory&lt;DigitalSignatureValidationFilter.Config&gt; {<br><br> private static final String HMAC_HEADER = &quot;X-HMAC-Signature&quot;;<br> private static final String HMAC_ALGORITHM = &quot;HmacSHA256&quot;;<br> private static final String HMAC_ERROR_MESSAGE = &quot;Missing HMAC signature&quot;;<br><br> @Value(&quot;${secret.key}&quot;)<br> private String secretKey;<br><br> public DigitalSignatureValidationFilter() {<br>  super(Config.class);<br> }</pre><p><strong>GET Request: Retrieve URL with Query Params and validate HMAC</strong></p><pre>public GatewayFilter apply(Config config) {<br>  return (exchange, chain) -&gt; {<br>   ServerHttpRequest request = exchange.getRequest();<br>   String signature = exchange.getRequest().getHeaders().getFirst(HMAC_HEADER);<br>   if (signature == null) {<br>    return handleUnauthorized(exchange,&quot;&quot;, HMAC_ERROR_MESSAGE);<br>   }<br><br>   // Read the URL path<br>   String url = getUrl(request);<br><br>   HttpMethod method = exchange.getRequest().getMethod();<br><br>   if (method == HttpMethod.GET || method == HttpMethod.DELETE) {<br>    // Generate signature from url, query params and body<br>    String dataToSign = getDataToSign(url, null);<br><br>    if (isValidHMAC(dataToSign, signature, secretKey)) {<br>     return chain.filter(exchange);<br>    } else {<br>     return handleUnauthorized(exchange, &quot;&quot;, HMAC_ERROR_MESSAGE);<br>    }<br><br>   }</pre><p><strong>POST Request: Retrieve Body and validate HMAC</strong></p><p>This is tricky, In a reactive programming model like WebFlux, data streams are consumed in a sequential manner. When the request body is read, it is typically read as a stream.</p><ol><li><strong>One-Time Consumption</strong>: Streams are designed to be read in a one-time, sequential manner. Once the data has been read from the stream, it is considered consumed and is no longer available. This is akin to reading a file from start to end; once you reach the end, you can’t re-read the content without re-opening the file.</li><li><strong>Non-Blocking Nature</strong>: WebFlux’s non-blocking, asynchronous model means that it processes data as it arrives. This design avoids holding onto data unnecessarily to maximize performance and resource efficiency. Keeping the stream open or re-readable would require additional memory and processing overhead.</li><li><strong>Reactive Streams Specification</strong>: The reactive streams specification, which WebFlux follows, dictates that streams should emit data items to their subscribers in a way that the items are not retained once consumed. This ensures efficient memory usage and promotes the stream’s ephemeral nature.</li></ol><p>In summary, the stream’s one-time consumption is an intentional design choice to maintain efficiency and adhere to the principles of reactive programming.</p><p><strong>How to solve this?</strong></p><p>Read the request body, perform hashing and HMAC validation, and write the body back to the Exchange stream and return the Exchange.</p><pre>if (method == HttpMethod.POST || method == HttpMethod.PUT || method == HttpMethod.PATCH) {<br><br>    // Read the request body<br>    return DataBufferUtils.join(request.getBody()).flatMap(dataBuffer -&gt; {<br>     // Convert dataBuffer to String<br>     byte[] bytes = new byte[dataBuffer.readableByteCount()];<br>     dataBuffer.read(bytes);<br>     DataBufferUtils.release(dataBuffer);<br>     String bodyString = new String(bytes, StandardCharsets.UTF_8);<br><br>     // Generate signature from url, query params and body<br>     String dataToSign = getDataToSign(url, bodyString);<br><br>     if (isValidHMAC(dataToSign, signature, secretKey)) {<br>      // Create a new DataBuffer with the modified body<br>      DataBuffer buffer = exchange.getResponse().bufferFactory()<br>        .wrap(bodyString.getBytes(StandardCharsets.UTF_8));<br><br>      // Create a new ServerHttpRequest with the modified body<br>      ServerHttpRequest modifiedRequest = new ServerHttpRequestDecorator(request) {<br>       @Override<br>       public Flux&lt;DataBuffer&gt; getBody() {<br>        return Flux.just(buffer);<br>       }<br>      };<br>      // Create a new ServerWebExchange with the modified request<br>      ServerWebExchange modifiedExchange = exchange.mutate().request(modifiedRequest).build();<br><br>      // Proceed with the modified exchange<br>      return chain.filter(modifiedExchange);<br>     } else {<br>      return handleUnauthorized(exchange, &quot;&quot;, HMAC_ERROR_MESSAGE);<br>     }<br>    });<br>   } else {<br>    return chain.filter(exchange);<br>   }</pre><p><strong>Validate HMAC</strong></p><pre>private boolean isValidHMAC(String data, String hmac, String key) {<br>  try {<br>   Mac mac = Mac.getInstance(HMAC_ALGORITHM);<br>   SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), HMAC_ALGORITHM);<br>   mac.init(secretKeySpec);<br>   byte[] hashBytes = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));<br>   String expectedHmac = Base64.getEncoder().encodeToString(hashBytes);<br>   return expectedHmac.equals(hmac);<br>  } catch (Exception e) {<br>   e.printStackTrace();<br>   return false;<br>  }<br> }</pre><p><strong>Handle Exception &amp; Other Utils</strong></p><pre>private Mono&lt;Void&gt; handleUnauthorized(ServerWebExchange exchange, String title, String message) {<br>  ServerHttpResponse response = exchange.getResponse();<br>  response.setStatusCode(HttpStatus.UNAUTHORIZED);<br>  response.getHeaders().add(&quot;Content-Type&quot;, &quot;application/json&quot;);<br><br>  String correlationId = UUID.randomUUID().toString();<br>  String jsonResponse = String.format(&quot;{\&quot;status\&quot;: &quot; + HttpStatus.UNAUTHORIZED.value()<br>    + &quot;, \&quot;correlationId\&quot;: \&quot;%s\&quot;, \&quot;errors\&quot;: [{\&quot;errorCode\&quot;: 4302, \&quot;title\&quot;: \&quot;&quot; + title<br>    + &quot;\&quot;, \&quot;detail\&quot;: \&quot;%s\&quot;, \&quot;desc\&quot;: \&quot;%s\&quot;}]}&quot;, correlationId, message, message);<br><br>  byte[] bytes = jsonResponse.getBytes(StandardCharsets.UTF_8);<br>  return response.writeWith(Mono.just(response.bufferFactory().wrap(bytes)));<br> }<br><br>private static void safeAppend(StringBuilder sb, String str) {<br>  if (!StringUtils.isEmpty(str)) {<br>   sb.append(str);<br>  }<br> }<br><br><br> private static String getDataToSign(String urlPath, String bodyString) {<br>  StringBuilder dataToSignBuilder = new StringBuilder();<br>  safeAppend(dataToSignBuilder, urlPath);<br>  safeAppend(dataToSignBuilder, bodyString);<br><br>  return dataToSignBuilder.toString();<br> }<br><br><br> private String getUrl(ServerHttpRequest request) {<br>  URI uri = request.getURI();<br>  String query = uri.getQuery();<br>  return uri.getPath() + (query != null ? &quot;?&quot; + query : &quot;&quot;);<br> }</pre><h3>Conclusion</h3><p>HMAC digital signatures provide a robust mechanism for securing API communications. By ensuring data integrity and authenticity, HMAC helps protect against various security threats, including tampering and man-in-the-middle attacks. In this blog, we explored the importance of HMAC in API security and provided implementations in both ReactJS and Spring Cloud Gateway.</p><p>By integrating HMAC validation in your API architecture, you can significantly enhance the security of your applications and protect sensitive data from unauthorized access and manipulation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb4aa7d5333e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Connected Car technology is enabling insurance companies to derive accurate insurance premium?]]></title>
            <link>https://abhra-deb.medium.com/how-connected-car-technology-is-enabling-insurance-companies-to-derive-accurate-insurance-premium-15bd7d8ff5aa?source=rss-ab6ef0efbf8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/15bd7d8ff5aa</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[auto-insurance]]></category>
            <category><![CDATA[connected-car-platform]]></category>
            <category><![CDATA[iot]]></category>
            <dc:creator><![CDATA[Abhra Prakash Deb]]></dc:creator>
            <pubDate>Fri, 03 Jun 2022 07:24:37 GMT</pubDate>
            <atom:updated>2022-06-03T07:24:37.730Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What’s missing?</strong></p><p>If we look at the traditional way of doing things, an insurance company generally looks at your age, past driving records (accidents, traffic violations), medical history, and specially credit score to come up with an insurance premium. That means, drivers with poor credit score have to pay higher prices. Forbes estimates, drivers with poor credit pays nearly $1,180 more per year compared to drivers with good credit.</p><p>What’s missing is a smarter insurance eco-system, that looks at your driving over time, and provides insurance, discounts, rewards based on your driving skills and usage.</p><p><strong>How to bridge the gap?</strong></p><p>With the emergence of Connected Car technology, a vehicle can now connect to the internet and exchange telematics to an IoT (Internet of Things) platform. Based on the collected telemetry, artificial intelligence and analytics, a highly accurate insight can be formed which can contribute in better decision making. According to market research, the global connected car market was valued at $63.03 billion in 2019, and is projected to reach $225.16 billion by 2027.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*0DBGvsQe_AuHUIkrYM7c7g.png" /><figcaption>High-level components</figcaption></figure><p>While on the road, your vehicle is recording each move that you make while driving, such as how much distance travelled on a particular trip, sudden braking, rapid acceleration, deceleration, speeding alert. This information is then transmitted from the vehicle using 4G/ 5G/ LTE to the cloud where it’s stored securely on a data lake. It then gets analyzed by an artificial intelligence program, and other advanced analytics software that determines your driving safety score on a scale of 0 to 100, 0 being worst and 100 being the best.</p><p>The score report can be generated for an individual trip or can be aggregated daily, weekly and monthly timeframes, and can be shared with the insurance company to receive additional discounts and lower insurance premium. This allows a smarter and fairer way to purchase cheaper car insurance based on how you drive.</p><p><strong>What’s next?</strong></p><p>This not only saves money spent on an insurance, but also promotes safe driving behaviors and speed responsibility that eventually helps to increase fuel economy, vehicle efficiency, and longevity. Personalized recommendations and tips highlighting areas of improvement, such as braking smoothly, accelerating or decelerating gently helps driver to improve driving behavior and build better driving habits. Connected Car technology has opened up new possibilities, and use cases like this one will most likely benefit all segment of people.</p><p>Read more on Connected Car platform — <a href="https://bit.ly/3DxSi8H"><strong>https://bit.ly/3DxSi8H</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15bd7d8ff5aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Lambda Layer — Simplified Dependency Management and Deployment with Java and SAM]]></title>
            <link>https://abhra-deb.medium.com/aws-lambda-layer-simplified-dependency-management-and-deployment-with-java-and-sam-640de70659f7?source=rss-ab6ef0efbf8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/640de70659f7</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloudformation]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Abhra Prakash Deb]]></dc:creator>
            <pubDate>Tue, 01 Dec 2020 11:40:48 GMT</pubDate>
            <atom:updated>2020-12-01T11:40:48.571Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS Lambda Layer — Simplified Dependency Management and Deployment with Java and SAM</h3><h3>Introduction</h3><p>In the programming world, including libraries and dependencies in the function code is a common practice required for successful compilation and execution. Whether it is an SDK or external library, it is beneficial for the developers to keep the deployment package small, if possible, containing just the core function. In the Serverless domain, AWS Lambda Layer lets the developer achieve just that. It allows creating a separate archive called a layer containing additional code, such as libraries, dependencies, or custom runtimes. This post focuses on building a Layer and including it in the Lambda function using AWS Serverless Application Model template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*k48Qik2YZDxefmpQmBHkjA.png" /><figcaption>Lambda + Layer Deployment</figcaption></figure><h3>Lambda Layer Use Cases</h3><p><strong>Simplified Dependency Management</strong>— Use and share common and reusable dependencies between functions in or across projects and other AWS accounts. <em>A function can use up to 5 layers at a time.</em></p><p><strong>Large Dependency Set </strong>— The application consists of a large dependency set, and a less frequent deployment is desired for those common dependencies. <em>However, there is a hard limit of 50MB for compressed deployment package and 250 MB unzipped, including layers.</em></p><p><strong>Reduce Deployment Time</strong> — Smaller package size for quicker deployment to save time and reduce the size of uploaded archives. <em>Bear in mind, AWS Lambda has a soft limit of 75 GB storage space per region for Lambda and Layers.</em></p><p><strong>Custom Runtime</strong> — The application used a language that is not currently part of the supported Lambda runtimes, and a custom runtime is required.</p><h3>Lambda Function</h3><p>This is a simple Lambda function handler written in Java with an S3 event trigger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y4pNT5ltYQ6XyePFakt3_A.png" /><figcaption>Lambda Handler</figcaption></figure><h3>Maven Assembly</h3><p>Utilize Maven assembly to create the Layer zip archive with <strong>java/lib</strong> classpath consisting only of the project’s dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mwjmbiTzi3yZuVPQTjvzGA.png" /></figure><h3>Compile and Package</h3><p><strong>&gt; mvn clean package</strong> generates the following 2 artifacts.</p><ol><li><strong>target/java-lambda-layer-example-1.0.0.jar</strong>, which consists of only the Lambda function code.</li><li>t<strong>arget/java-lambda-layer-example-dependencies.zip</strong>, which is the Lambda layer dependencies zip file.</li></ol><h3>Deployment</h3><p>Deploy the application using AWS SAM Template. The Lambda function refers to the layer for dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ia4bh7Q4JQVB19hnmA5k-w.png" /></figure><h3>GitHub</h3><p><a href="https://github.com/abhdeb/java-lambda-layer-example/tree/master">abhdeb/java-lambda-layer-example</a></p><h3>References</h3><ul><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html">Creating and sharing Lambda layers</a></li><li><a href="https://maven.apache.org/plugin-developers/cookbook/generate-assembly.html">Maven - Cookbook - How To Generate Assembly</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=640de70659f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS DynamoDB: Writing millions of records: Not consuming provisioned throughput: Global Secondary…]]></title>
            <link>https://abhra-deb.medium.com/aws-dynamodb-writing-millions-of-records-not-consuming-provisioned-throughput-global-secondary-6edb4e521b8f?source=rss-ab6ef0efbf8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6edb4e521b8f</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[sharding]]></category>
            <dc:creator><![CDATA[Abhra Prakash Deb]]></dc:creator>
            <pubDate>Wed, 29 Jul 2020 05:44:23 GMT</pubDate>
            <atom:updated>2020-07-30T07:51:49.513Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS DynamoDB: Writing millions of records: Not consuming provisioned throughput: Global Secondary Index and Sharding</h3><p>Are your write requests getting throttled and rejected in DynamoDB? Is your application not hitting the expected write capacity? Are you using Global Secondary Index (GSI)? There could be many reasons but one particular reason could be the structure of GSI, which could limit the write throughput.</p><p><strong>Problem</strong></p><p>In one of my recent projects, there was a requirement of writing 4 million records in DynamoDB within 22 minutes. The solution was implemented using AWS Serverless components which we are going to talk about in an upcoming write up. In today’s section, I would like to focus on the issue that we have faced while implementing the solution, of not achieving expected write throughput in DynamoDB.</p><p>There are 2 tables, the first one is: <em>CustomerGroup</em>, which has <em>GroupId</em> as the hash or primary partition key and the second one is: <em>CustomerAssociation</em>, which has <em>CustomerId </em>as hash or primary partition key. The relationship between these 2 tables are, one group can be associated with one or more customers , that means multiple customers can be part of a group and also, each customer can be part of one or more such groups.</p><blockquote><strong><em>CustomerGroup Table</em></strong></blockquote><blockquote>{<br> “TableName”: “CustomerGroup”,<br> “KeySchema”: [{“AttributeName”: “GroupId”, “KeyType”: “HASH”}],<br> “AttributeDefinitions”: [{“AttributeName”: “GroupId”,“AttributeType”: “S”}]<br>}</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*hbIszEi9zrs9mk_bixpOTw.png" /></figure><blockquote><strong><em>CustomerAssociation Table with GSI</em></strong></blockquote><blockquote>{<br> “TableName”: “CustomerAssociation”,<br> “KeySchema”: [{“AttributeName”: “CustomerId”,“KeyType”: “HASH”}],<br> “AttributeDefinitions”: [{“AttributeName”: “CustomerId”,“AttributeType”: “S”}, {“AttributeName”: “GroupId”,“AttributeType”: “S”}],<br> “GlobalSecondaryIndexes”: [{<br> “IndexName”: “GroupId-index”,<br> “Projection”: {“ProjectionType”: “ALL”},<br> “KeySchema”: [{“KeyType”: “HASH”,“AttributeName”: “GroupId”}]}]<br>}</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*gfhL6PBR-XdcefPmPzf62g.png" /></figure><p><strong>GSI</strong></p><p>The GSI (<em>GroupId-index</em>) is created in the <em>CustomerAssociation </em>table, which has <em>GroupId </em>as hash or partition key. Using this GSI, one can query <em>CustomerAssociation </em>table with the given <em>GroupId </em>to fetch the list of associated customers (CustomerIds).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*uQj6razZzKzkqyBHOsHd3g.png" /></figure><p>So, if 4 million customers need to be written within 22 minutes, in one second the application needs to write: 4 million/(22*60) = around 3000 customer records in the <em>CustomerAssociation </em>table.</p><p>But with this approach, the batch writes from concurrent Lambda’s were not hitting the expected write throughput and write requests for <em>CustomerAssociation</em><strong><em> </em></strong>table<strong><em> </em></strong>were getting throttled and rejected. The provisioned throughput was around 3000 WCU but the actual consumed was around 1000 WCU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*o0bPHuCR60yZ5fTnHSqNVg.png" /></figure><p><strong>Solution</strong></p><p>The <em>CustomerAssociation</em><strong><em> </em></strong>table<strong><em> </em></strong>consists of multiple partitions. The number of partitions in a table depends on the provisioned throughput and the amount of used storage.</p><blockquote>Partitions for write operations = (Provisioned Write Throughput / 1000) = 3000/1000 = 3 Partitions</blockquote><blockquote>In DynamoDB, Provisioned throughput will get evenly distributed among all the shards. Therefore the application can write with a maximum of 1000 Write Capacity Units per second to a single partition. As there are 3 partitions, the total WCU should reach 3000 at least.</blockquote><blockquote>But when the CloudWatch Metrics was verified, the consumed write capacity seems to be limited to 1000 units. This is the maximum write capacity per partition, so for some reason all the writes are going to the same partition.</blockquote><blockquote>The data structure of both the tables look fine, so there must be some sort of throttling happening while syncing the GSI. The GSI uses GroupId as the Hash or Partition Key. So now if you are trying to insert 4 million customers for the same GroupId in the CustomerAssociation table, it also needs to sync GSI and maintain those customers against the GroupId. As GroupId is same for all the 4 million records, it is going to the same partition and hence creating a hot partition for the GSI.</blockquote><blockquote>The way around this problem is to tweak the table structure and introduce Sharding approach.</blockquote><p><strong>Sharding</strong></p><p>A sharding approach was introduced in the <em>CustomerAssociation </em>table by creating <em>GroupId_Shard </em>attribute. The value of this attribute will consist of the <em>GroupId </em>and a random letter from a group of 6 letters (a,b,c,d,e,f).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*mU217YRhr9npocgUBp_OqQ.png" /></figure><p>The GSI is also modified to have Hash/Partition key as <em>GroupId_Shard </em>instead of <em>GroupId </em>that was used earlier.</p><p>With this approach when 4 million customers are written in <em>CustomerAssociation</em> table, an additional column <em>GroupId_Shard </em>will also be populated. As the GSI is created with <em>GroupId_Shard </em>as partition key the 4 million records will be distributed among 6 shards (a,b,c,d,e,f) in the GSI. With this approach the consumed write throughput was matching the provisioned (3000 WCU).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*nVvPcLpRReJKoWrZp1OxiQ.png" /></figure><p><strong>Downside</strong></p><p>But now using this GSI, you can’t query <em>CustomerAssociation </em>table with the given <em>GroupId </em>to fetch the list of associated customers (CustomerIds). Instead you will have to tweak your query to use <em>GroupId_Shard </em>and pass a range of values using the 6 random letters (a,b,c,d,e,f) to fetch individual records for each shard and collating at the end to get the total list.</p><p><strong>Summary</strong></p><p>Analyse the DynamoDB table data structure carefully when designing your solution and especially when creating a Global Secondary Index and selecting the partition key. Basic rule of thumb is to distribute the data among different partitions to achieve desired throughput and avoid hot partitions that will limit the utilization of your DynamoDB table to it’s maximum capacity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6edb4e521b8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>