<?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 ScaleSmith on Medium]]></title>
        <description><![CDATA[Stories by ScaleSmith on Medium]]></description>
        <link>https://medium.com/@bhattv93?source=rss-c80476af101d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3DAph6WLomqrPHvj.jpg</url>
            <title>Stories by ScaleSmith on Medium</title>
            <link>https://medium.com/@bhattv93?source=rss-c80476af101d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 16:58:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bhattv93/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ From Blind Book Hunts to Smart Shelf Picks: Scan, Parallel Scan, and Query in DynamoDB]]></title>
            <link>https://medium.com/@bhattv93/from-blind-book-hunts-to-smart-shelf-picks-scan-parallel-scan-and-query-in-dynamodb-2ab0ca51e2c2?source=rss-c80476af101d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ab0ca51e2c2</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-access-patterns]]></category>
            <dc:creator><![CDATA[ScaleSmith]]></dc:creator>
            <pubDate>Sun, 20 Apr 2025 04:45:01 GMT</pubDate>
            <atom:updated>2025-04-20T04:45:01.277Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you walk into a massive, ancient library. No signs, no genre labels, just a sea of books. Your task?</p><blockquote><em>“Find all the books from the </em>Middle-earth<em> series.”</em></blockquote><p>Now what?</p><p>You start flipping through each book. Every. Single. One. This is what <strong>DynamoDB’s </strong><strong>Scan</strong> operation feels like.</p><p>But let’s add a twist. You bring your friends along. Each of you takes a different part of the library and gets to work. That’s kinda <strong>Parallel Scan</strong>.</p><p>Still, you’re scanning the entire library — just faster, not smarter.</p><p>Now picture this: the library has well-organized shelves. Sections are labeled: “Fantasy”, “Sci-fi”, “Biographies”, “J.R.R. Tolkien”. You simply walk to the right shelf and pick the books.</p><p>Boom. That’s your <strong>Query</strong>.</p><h3>🔍 Analogy in a Nutshell</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KhD9-ooKA-9wXVAXZXaraA.png" /></figure><blockquote><em>🔑 Key Takeaway: Just bringing more people (segments) doesn’t reduce the size of the library — it just parallelizes the search.</em></blockquote><h3>🛠️ What Is a Scan in DynamoDB?</h3><p>A Scan operation reads <strong>every item in your table</strong>, regardless of filters. Yes, even if you&#39;re looking for only a few specific attributes.</p><pre>response = table.scan(<br>    FilterExpression=Attr(&#39;genre&#39;).eq(&#39;Fantasy&#39;)</pre><p>This brings <strong>all</strong> items and only <strong>then</strong> applies the filter. Wasteful? Definitely, especially for large tables.</p><h3>🚀 Parallel Scan: Faster But Not Smarter</h3><p>To speed things up, DynamoDB supports <strong>Parallel Scan</strong> — divide the table into segments and scan each one concurrently.</p><p>It’s like calling your friends and saying:</p><blockquote><em>“You take floors 1–3, I’ll take 4–6, and she’ll check 7–9.”</em></blockquote><p>Still scanning everything, just faster.</p><h3>✨ Sample Code</h3><pre>import boto3<br>import threading<br>from boto3.dynamodb.conditions import Attr<br><br>dynamodb = boto3.resource(&#39;dynamodb&#39;)<br>table = dynamodb.Table(&#39;books_table&#39;)<br><br>def scan_segment(segment, total_segments, results):<br>    items = []<br>    response = table.scan(<br>        FilterExpression=Attr(&#39;genre&#39;).eq(&#39;Fantasy&#39;),<br>        Segment=segment,<br>        TotalSegments=total_segments<br>    )<br>    items.extend(response.get(&#39;Items&#39;, []))<br>    results[segment] = items<br><br>TOTAL_SEGMENTS = 3<br>threads = []<br>results = {}<br><br>for i in range(TOTAL_SEGMENTS):<br>    t = threading.Thread(target=scan_segment, args=(i, TOTAL_SEGMENTS, results))<br>    threads.append(t)<br>    t.start()<br><br>for t in threads:<br>    t.join()<br><br>all_books = [item for segment in results.values() for item in segment]</pre><blockquote><em>⚠️ </em><strong><em>Note</em></strong><em>: Performance gains </em><strong><em>aren’t linear</em></strong><em>. You may not get 3× speed with 3 segments due to backend partitioning and resource constraints.</em></blockquote><h3>🎯 Query: The Gold Standard</h3><p>Let’s get smarter.</p><p>If you design your DynamoDB table with a <strong>Primary Key</strong> or <strong>Global Secondary Index (GSI)</strong> that matches your access pattern (e.g., genre or author), you can use Query.</p><pre>response = table.query(<br>    KeyConditionExpression=Key(&#39;genre&#39;).eq(&#39;Fantasy&#39;)<br>)</pre><p>This tells DynamoDB exactly where to go. You’re not flipping through every book. You’re walking to the “Fantasy” shelf and picking what you need.</p><ul><li><strong>Scan</strong>: Slow, reads the whole table.</li><li><strong>Parallel Scan</strong>: Same work, done faster. Still scans entire table.</li><li><strong>Query</strong>: Precision. Speed. Efficiency.</li></ul><h3>💡 Final Thoughts</h3><p>When it comes to DynamoDB, <strong>the smartest librarian is the one who organizes the shelves well</strong>. If you find yourself scanning more often than querying, take a step back:</p><ul><li>Can you refactor your schema?</li><li>Should you add a GSI?</li><li>Is your access pattern predictable?</li></ul><p>Just because you <em>can</em> scan the whole library doesn’t mean you <em>should</em>.</p><p><em>Thanks for reading! If this helped make DynamoDB feel a bit more like your neighborhood library and a bit less like a black box — give it a clap 👏 or leave a comment!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ab0ca51e2c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Automation with DynamoDB Streams and EventBridge Pipes]]></title>
            <link>https://medium.com/@bhattv93/simplifying-automation-with-dynamodb-streams-and-eventbridge-pipes-a019db4fa38d?source=rss-c80476af101d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a019db4fa38d</guid>
            <category><![CDATA[eventbridge]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[eventbridge-pipes]]></category>
            <category><![CDATA[dynamodb-stream]]></category>
            <dc:creator><![CDATA[ScaleSmith]]></dc:creator>
            <pubDate>Sun, 23 Mar 2025 18:00:50 GMT</pubDate>
            <atom:updated>2025-03-23T18:00:50.182Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>“Users are submitting forms, managers are approving them… but nothing happens until our hourly batch job runs. Can we make this real-time?”</em></blockquote><p>Imagine you’re managing an approval workflow system. Your team built a form submission portal where all responses are stored in a DynamoDB table e.g. “test_table.” Each submission has a “status” field that tracks its progress through your approval pipeline.</p><p>When someone finally hits “Approve” on a submission, several things need to happen automatedly — perhaps notifications need to be sent, data needs to be synced to other systems, or subsequent processes need to kick off.</p><p>Instead of building a polling system that constantly checks for changes, we’ll create an event-driven architecture that springs into action the moment a status changes to “Approved.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*I7HwaGI26MlYuebynBJ07w.png" /></figure><p>This architecture has primarily three components that work together seamlessly:</p><ol><li><strong>DynamoDB Streams</strong> captures every change to our approval table</li><li><strong>EventBridge Pipe</strong> filters for just the “status → Approved” changes</li><li><strong>Lambda Function</strong> executes our business logic immediately</li></ol><p><strong>Want to build your own?</strong> Follow along with the step-by-step guide below!</p><h3>Step 1: Create &amp; Enable DynamoDB Streams</h3><p>First, we’ll enable DynamoDB Streams on our table with the “New and Old Images” option. This creates a time-ordered sequence of every change made to our table items. This could also be done directly using AWS Management console. Navigate to the Exports and streams tab in the select DynamoDB table.</p><p>Run this command or use the AWS Console to enable streams on your table:</p><pre>aws dynamodb update-table \<br>    --table-name test_table \<br>    --stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y2ZNikEqLoJU_w4B9MOt_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8fxMTiJWsnw7wlN9ruOBuA.png" /><figcaption>DynamoDB Stream configuration snapshot</figcaption></figure><p>Note: <em>Ensure that the DynamoDB stream is enabled</em>.</p><p>Next, we’ll connect an EventBridge Pipe to this stream. The good catch here is we’ll add a filter that will only forward events where the status field has changed to ‘Approved’. This ensures our downstream processes only trigger for the exact condition we care about and not become a redundant and inefficient invocation step in between.</p><p><strong>EventBridge Pipe</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y4PMF9fbPcOdqQ0L7xFahQ.png" /><figcaption>EventBridge Pipe Components</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*RLcCDpC1nlA4NM0svGSO_w.png" /><figcaption>Useful Parameters for configuring the EventBridge pipe</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*ve3j67Ml8PgnOzBkqOzc_Q.png" /></figure><p>Finally, we’ll configure a Lambda function that receives these filtered events and handles all the business logic we need to execute when an item gets approved.</p><p><strong>Sample Lambda code(in python):</strong></p><pre>import json<br>def lambda_handler(event, context):<br>    try:<br>        # Access the first element of the event list<br>        print(f&quot;Event received is::{event}&quot;)<br>        record = event[0]<br>        if &#39;dynamodb&#39; not in record:<br>            print(&quot;Invalid record, not a dynamodb stream event&quot;)<br>            return {&quot;statusCode&quot;: 400, &quot;body&quot;: &quot;Invalid record&quot;}<br>        if &#39;eventName&#39; not in record:<br>            print(&quot;eventName not in record&quot;)<br>            return {&quot;statusCode&quot;: 400, &quot;body&quot;: &quot;Invalid record&quot;}<br>        if record[&#39;eventName&#39;] != &quot;MODIFY&quot;:<br>            return {&quot;statusCode&quot;: 200, &quot;body&quot;: &quot;Non modify event&quot;}  # Ignore non-modify events<br>        new_image = record[&#39;dynamodb&#39;].get(&#39;NewImage&#39;, {})<br>        old_image = record[&#39;dynamodb&#39;].get(&#39;OldImage&#39;, {})<br>        # Extract status values, handle missing status<br>        new_status = new_image.get(&quot;status&quot;, {}).get(&quot;S&quot;)<br>        old_status = old_image.get(&quot;status&quot;, {}).get(&quot;S&quot;)<br>        # Only proceed if status changed from anything else to &quot;Approved&quot;<br>        if new_status == &quot;Approved&quot; and old_status != &quot;Approved&quot;:<br>            print(f&quot;Status changed from {old_status} to {new_status}. Processing...&quot;)<br>            # Add your logic here (e.g., send notification, update another system)<br>    except Exception as e:<br>        print(f&quot;Error processing event: {e}&quot;)<br>        return {&quot;statusCode&quot;: 500, &quot;body&quot;: f&quot;Error: {e}&quot;} #return error to stop the loop<br>    return {&quot;statusCode&quot;: 200, &quot;body&quot;: &quot;Processed event&quot;}</pre><p>To make this all work seamlessly, we need to configure the right IAM permissions. Our EventBridge Pipe needs permission to read from the DynamoDB stream, and our Lambda needs permission to be invoked by the pipe and write logs to CloudWatch.</p><p><strong>IAM Role Policies</strong></p><p>AWS Lambda Execution Role Policy:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;dynamodb:DescribeStream&quot;,<br>                &quot;dynamodb:GetRecords&quot;,<br>                &quot;dynamodb:GetShardIterator&quot;,<br>                &quot;dynamodb:ListStreams&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:dynamodb:us-east-1:&lt;account_no&gt;:table/&lt;dynamodb_table_name&gt;/stream/*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: &quot;logs:CreateLogGroup&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:logs:us-east-1:&lt;account_no&gt;:*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;logs:CreateLogStream&quot;,<br>                &quot;logs:PutLogEvents&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:logs:us-east-1:&lt;account_no&gt;:log-group:/aws/lambda/&lt;lambda_function_name&gt;:*&quot;<br>        }<br>    ]<br>}</pre><p>EventBridge Pipe Role Policy</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;lambda:InvokeFunction&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:lambda:&lt;aws_region&gt;:&lt;your_aws_account_no&gt;:function:&lt;lambda_function_name&gt;&quot;<br>            ]<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;dynamodb:DescribeStream&quot;,<br>                &quot;dynamodb:GetRecords&quot;,<br>                &quot;dynamodb:GetShardIterator&quot;,<br>                &quot;dynamodb:ListStreams&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:dynamodb:&lt;aws_region&gt;:&lt;your_aws_account_no&gt;:table/&lt;dynamodb_table_name&gt;/stream/*&quot;<br>        }<br>    ]<br>}</pre><p>With this architecture in place, you’ve built a real-time, event-driven approval system that instantly responds when items are approved — no polling required!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a019db4fa38d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advancing Your DynamoDB Skills: Going Beyond Basics with Indexing for Performance and Cost…]]></title>
            <link>https://medium.com/@bhattv93/advancing-your-dynamodb-skills-going-beyond-basics-with-indexing-for-performance-and-cost-a01b0abb1d89?source=rss-c80476af101d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a01b0abb1d89</guid>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[cost-optimization]]></category>
            <category><![CDATA[indexing]]></category>
            <category><![CDATA[performance-tuning]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[ScaleSmith]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 18:31:23 GMT</pubDate>
            <atom:updated>2024-09-16T18:31:23.947Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advancing Your DynamoDB Skills: Going Beyond Basics with Indexing for Performance and Cost Efficiency</h3><p>In my previous post, we covered the basics of DynamoDB’s <strong>Scan</strong>, <strong>Query</strong>, and <strong>GetItem</strong> APIs. Now, let’s go one step further and explore a key technique that can truly unlock DynamoDB’s power: <strong>Indexing</strong>.</p><p>As your application grows, sticking to the default primary key for every query won’t cut it. Indexing helps you efficiently query non-primary key attributes without causing expensive and time-consuming table scans. This means faster queries and, even better, reduced costs.</p><h3>Why Indexing is a Game Changer in DynamoDB</h3><p>In DynamoDB, your queries are typically based on the <strong>primary key</strong>. But what if you need to search for data based on attributes that aren’t part of the primary key? Without indexing, you’ll be forced into a full table scan — slow, inefficient, and costly.</p><p>Indexes let you create alternative query paths for non-primary key attributes, ensuring fast retrievals even as your data volume grows.</p><h3>Types of Indexes in DynamoDB</h3><ol><li><strong>Global Secondary Index (GSI)</strong>: This allows you to define a new partition key and optional sort key for queries beyond your table’s primary key. <strong>Example</strong>: Think of a healthcare app managing patient records. The primary key is patientID, but you also want to query patient data based on diagnosisDate. A GSI on diagnosisDate allows you to do this efficiently.</li><li><strong>Local Secondary Index (LSI)</strong>: An LSI uses the same partition key as the main table but allows a different sort key, making it perfect for more specific queries. <strong>Example</strong>: In the same healthcare app, you might need to query treatments for a patient, sorted by treatmentDate. An LSI on treatmentDate gives you that flexibility while keeping patientID as the partition key.</li></ol><h3>How Indexing Impacts Performance and Cost</h3><ul><li><strong>Speed</strong>: With indexes, DynamoDB can quickly locate the data you’re after, without having to scan the whole table. This significantly speeds up query times.</li><li><strong>Cost Efficiency</strong>: Indexes cut down on <strong>Read Capacity Units (RCUs)</strong> used in queries by limiting the number of items that need to be scanned, reducing overall costs. While GSIs do add write costs, the savings from avoiding table scans usually make it a net positive.</li></ul><h3>A Real-World Example: Optimizing Healthcare Data Retrieval</h3><p>Let’s say you’re working for a pharmaceutical company managing patient records. You have a DynamoDB table with patientID as the partition key. But as the project grows, you realize that you’re frequently querying data based on diagnosisDate and treatmentType.</p><p>Here’s how you can solve this with indexes:</p><ul><li><strong>GSI on </strong><strong>diagnosisDate</strong>: This helps retrieve all patient records within a specific date range without a full table scan.</li><li><strong>LSI on </strong><strong>treatmentType</strong>: This lets you efficiently retrieve all treatments for a particular patient, sorted by treatment date.</li></ul><p>These indexes not only improve performance but also keep costs under control by targeting queries to specific subsets of data rather than scanning the entire table.</p><h3>Best Practices for Using Indexes</h3><ol><li><strong>Plan Your Access Patterns</strong>: Before creating your table, think through how you’ll be querying the data. Build indexes for those key patterns.</li><li><strong>Optimize GSI Usage</strong>: GSIs can add to your write costs, so make sure you’re indexing attributes that you’ll query often.</li><li><strong>Monitor and Adjust</strong>: Use CloudWatch to track how your indexes are performing. If an index isn’t pulling its weight, consider removing it to avoid unnecessary costs.</li></ol><h3>Conclusion</h3><p>Indexing is your secret weapon for scaling DynamoDB efficiently. It gives you the flexibility to query non-key attributes quickly while keeping costs in check. Whether you’re managing healthcare records or any other data-heavy project, leveraging GSIs and LSIs can make all the difference.</p><p>This post is a deeper dive into DynamoDB optimization, building on the basics we discussed earlier. Keep experimenting, and soon, you’ll be mastering more advanced NoSQL database concepts!Advancing Your DynamoDB Skills: Going Beyond Basics with Indexing for Performance and Cost Efficiency</p><p>In our last post, we explored how DynamoDB’s <strong>Scan</strong>, <strong>Query</strong>, and <strong>GetItem</strong> APIs work for different use cases. Now, we’re going a step further to explore <strong>Indexing</strong> — a powerful feature that can drastically improve query performance and reduce costs.</p><p>As your data grows, relying solely on the primary key for every query can become inefficient. <strong>Indexes</strong> allow you to retrieve data faster by targeting attributes that aren’t part of the primary key, avoiding the need for costly full table scans. Let’s break down the types of indexes in DynamoDB and how they can enhance both performance and cost-efficiency.</p><h3>Why Indexing Matters in DynamoDB</h3><p>In DynamoDB, your data is partitioned and stored based on a <strong>primary key</strong>. But when you need to query on attributes that aren’t part of this key, things get tricky. Without indexes, you’d be forced into a full table scan, which can be both slow and expensive.</p><p>Indexes give you a way around this, allowing you to query efficiently without having to search through every item in the table.</p><h3>Types of Indexes in DynamoDB</h3><h4>Global Secondary Index (GSI)</h4><p>A <strong>GSI</strong> allows you to create an alternative partition key and optional sort key for querying. This means you can query on attributes that are different from the table’s primary key.</p><ul><li><strong>Example</strong>: Let’s say you’re building a healthcare app that stores patient data. Your primary table uses patientID as the partition key, but you also want to query data based on diagnosisDate to find all diagnoses within a certain timeframe. Creating a GSI on diagnosisDate allows you to efficiently run these queries.</li><li><strong>Flexibility</strong>: GSIs can be created <strong>at any time</strong> after the table is created and can query across all partitions, giving you the flexibility to adjust your query patterns as your app evolves.</li><li><strong>Cost</strong>: GSIs replicate data across different partition key spaces, which means they can incur higher write costs. However, this is often worth it for the increased query speed and flexibility.</li></ul><h4>Local Secondary Index (LSI)</h4><p>An <strong>LSI</strong> allows you to use the <strong>same partition key</strong> as the base table but lets you define a different sort key. This is helpful when you want to query different aspects of data <strong>within the same partition</strong>.</p><ul><li><strong>Example</strong>: In the healthcare app, your main table’s partition key is still patientID, but now you want to query all treatments sorted by treatmentDate. Creating an LSI on treatmentDate allows you to efficiently retrieve all treatments for a patient while keeping the partition key as patientID.</li><li><strong>Limitations</strong>: LSIs must be created <strong>when the table is created</strong> and cannot be added later, so planning your access patterns early is key.</li><li><strong>Cost</strong>: LSIs are generally cheaper than GSIs because they only index data within a specific partition. However, they’re more restrictive in terms of querying flexibility.</li></ul><h3>How Indexing Affects Performance and Cost</h3><ul><li><strong>Faster Queries</strong>: By using indexes, DynamoDB can quickly access the data you need based on non-primary key attributes, avoiding costly full table scans.</li><li><strong>Cost Efficiency</strong>: Indexes reduce the number of items scanned during queries, which in turn reduces the <strong>Read Capacity Units (RCUs)</strong> consumed. GSIs can add write costs due to data replication, but the reduction in scan operations usually outweighs the extra expense.</li></ul><h3>Real-World Example: Optimizing Healthcare Data Retrieval</h3><p>Let’s imagine you’re working for a pharmaceutical company managing patient data. Your primary DynamoDB table has patientID as the partition key. Over time, you realize that you’re frequently querying data by diagnosisDate and treatmentType.</p><p>Here’s how indexes can help:</p><ul><li><strong>GSI on </strong><strong>diagnosisDate</strong>: This allows you to quickly retrieve all patient records within a specific diagnosis date range without scanning the entire table.</li><li><strong>LSI on </strong><strong>treatmentType</strong>: This enables you to retrieve treatments for a patient sorted by treatmentDate, improving the query efficiency within the same partition (patientID).</li></ul><p>By adding these indexes, you reduce both query time and operational costs, ensuring that you retrieve only the data you need, when you need it.</p><h3>Best Practices for Indexing</h3><ol><li><strong>Plan Your Access Patterns Early</strong>: When designing your DynamoDB table, think about the most common query patterns and design indexes around them.</li><li><strong>Use GSIs Wisely</strong>: GSIs are powerful but can increase write costs. Use them strategically for queries that hit a large number of partitions.</li><li><strong>Monitor and Adjust</strong>: Track index usage and costs with CloudWatch. If an index isn’t being used, consider removing it to cut down on costs.</li></ol><h3>Conclusion</h3><p>Indexing is essential for scaling DynamoDB efficiently, allowing you to query non-primary key attributes with speed and lower costs. Whether you’re working on a healthcare project or another large-scale application, <strong>Global Secondary Indexes</strong> and <strong>Local Secondary Indexes</strong> provide the flexibility you need to retrieve data quickly without breaking the bank.</p><p>This post continues where we left off in our last article, diving deeper into how to make DynamoDB even more powerful by leveraging indexing. Stay tuned for more tips and tricks as we continue to explore NoSQL database optimization!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a01b0abb1d89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing DynamoDB Data Retrieval with Python: Efficient Use of Scan, Query, and GetItem APIs]]></title>
            <link>https://medium.com/@bhattv93/optimizing-dynamodb-data-retrieval-with-python-efficient-use-of-scan-query-and-getitem-apis-ab13ea4c046b?source=rss-c80476af101d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab13ea4c046b</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[boto3]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <dc:creator><![CDATA[ScaleSmith]]></dc:creator>
            <pubDate>Sat, 14 Sep 2024 17:56:49 GMT</pubDate>
            <atom:updated>2024-09-14T17:56:49.669Z</atom:updated>
            <content:encoded><![CDATA[<p>Amazon DynamoDB is a powerhouse when it comes to fully managed NoSQL databases. It offers low-latency data access and seamless scalability, which makes it ideal for modern applications. However, efficiently retrieving data from DynamoDB requires a clear understanding of its three primary data retrieval methods: <strong>Scan</strong>, <strong>Query</strong>, and <strong>GetItem</strong>.</p><p>Each of these methods serves a distinct purpose, and selecting the right one can drastically improve the performance and cost-effectiveness of your solution. In this article, we’ll dive into these operations using a <strong>real-world healthcare use case</strong> to illustrate when and how to use each. Along the way, we’ll enhance performance with optimization strategies and best practices.</p><h3>Scenario: Patient Monitoring System</h3><p>Imagine you’re a data engineer tasked with building a <strong>patient monitoring system</strong> for a healthcare provider. This system stores patient health data, including multiple health check-ups, in a DynamoDB table.</p><p>The table structure for PatientHealthRecords is as follows:</p><ul><li><strong>Partition Key (patientId)</strong>: Unique identifier for each patient.</li><li><strong>Sort Key (visitDate)</strong>: Timestamp for patient visits to track historical data.</li><li>Other fields include: vitalSigns, adverseEvents, and medicationAdherence.</li></ul><p>Your tasks are to:</p><ol><li>Retrieve all patient records for a batch analysis (Scan).</li><li>Query the data of a specific patient based on their unique ID (Query).</li><li>Fetch a single record for a patient’s specific visit (GetItem).</li></ol><h3>Understanding the Three DynamoDB Operations</h3><p>Before we dive into code, it’s essential to understand what each operation does and when to use them:</p><ul><li><strong>Scan</strong>: Reads the entire table, optionally applying a filter to refine the result. It’s broad and potentially costly.</li><li><strong>Query</strong>: Fetches data based on a partition key, making it more efficient than Scan.</li><li><strong>GetItem</strong>: Retrieves a single record using both the partition key and sort key, offering the most efficient and low-latency retrieval.</li></ul><h3>1. Scan: Retrieving All Data</h3><p>The <strong>Scan</strong> operation scans the entire table and retrieves all items. This is useful when you don’t know the partition key ahead of time but need to filter data. However, this comes at the cost of reading all items in the table, even those that don’t match your filter criteria.</p><p>Here’s how to use Scan in Python to retrieve all patient records for batch processing:</p><pre>import boto3<br><br># Initialize DynamoDB resource<br>dynamodb = boto3.resource(&#39;dynamodb&#39;)<br>table = dynamodb.Table(&#39;PatientHealthRecords&#39;)<br><br># Scan all items from the table<br>response = table.scan()<br><br># Handle pagination if the result exceeds 1MB<br>items = response[&#39;Items&#39;]<br><br># Print patient data<br>for item in items:<br>    print(f&quot;Patient ID: {item[&#39;patientId&#39;]}, Visit Date: {item[&#39;visitDate&#39;]}, Vital Signs: {item[&#39;vitalSigns&#39;]}&quot;)<br>    <br># Check if more items need to be fetched<br>while &#39;LastEvaluatedKey&#39; in response:<br>    response = table.scan(ExclusiveStartKey=response[&#39;LastEvaluatedKey&#39;])<br>    items.extend(response[&#39;Items&#39;])</pre><p><strong>Optimization Tips for Scan:</strong></p><ul><li><strong>Limit the scan size</strong> by using the Limit parameter and paginate using LastEvaluatedKey to avoid reading the whole table at once.</li><li><strong>Use </strong><strong>ProjectionExpression</strong> to retrieve only the attributes you need.</li><li><strong>Avoid Scan for large tables</strong> in production; instead, consider it for analytics or occasional maintenance jobs.</li></ul><h3>2. Query: Efficiently Fetching Targeted Data</h3><p>The <strong>Query</strong> operation is optimized for retrieving items based on the partition key and optionally filtering with a sort key or other attributes. In our patient monitoring system, you can use Query to fetch a specific patient’s medical history by their patientId.</p><pre>from boto3.dynamodb.conditions import Key<br><br># Query data for a specific patient based on their patientId<br>response = table.query(<br>    KeyConditionExpression=Key(&#39;patientId&#39;).eq(&#39;P12345&#39;)<br>)<br><br># Get all patient visits<br>visits = response[&#39;Items&#39;]<br><br># Print each visit&#39;s data<br>for visit in visits:<br>    print(f&quot;Patient ID: {visit[&#39;patientId&#39;]}, Visit Date: {visit[&#39;visitDate&#39;]}, Vital Signs: {visit[&#39;vitalSigns&#39;]}&quot;)</pre><p><strong>Optimization Tips for Query:</strong></p><ul><li><strong>Use the sort key</strong> to filter results further (e.g., visits within a specific date range) by applying conditions like begins_with, between, or comparison operators.</li><li><strong>Limit the response size</strong> using Limit if you don’t need all results.</li><li><strong>Use </strong><strong>ConsistentRead=False</strong> for faster read times when eventual consistency is acceptable, especially in read-heavy applications.</li></ul><h3>3. GetItem: Fetching a Single Record</h3><p>The <strong>GetItem</strong> operation is the most efficient when you need to retrieve a single record using both the partition key and sort key. It’s ideal for low-latency scenarios, such as fetching a specific patient visit.</p><pre># Get a specific patient visit based on patientId and visitDate<br>response = table.get_item(<br>    Key={<br>        &#39;patientId&#39;: &#39;P12345&#39;,<br>        &#39;visitDate&#39;: &#39;2024-09-10&#39;<br>    }<br>)<br><br># Extract the item<br>patient_record = response.get(&#39;Item&#39;)<br><br>if patient_record:<br>    print(f&quot;Patient ID: {patient_record[&#39;patientId&#39;]}, Visit Date: {patient_record[&#39;visitDate&#39;]}, Vital Signs: {patient_record[&#39;vitalSigns&#39;]}&quot;)<br>else:<br>    print(&quot;Patient record not found&quot;)</pre><p><strong>Optimization Tips for GetItem:</strong></p><ul><li><strong>Use when exact keys are known</strong>: GetItem should be your go-to for fetching individual records by their unique keys.</li><li><strong>Leverage caching</strong> with DynamoDB Accelerator (DAX) for high-frequency GetItem requests to reduce response times.</li></ul><h3>When to Use Scan, Query, and GetItem</h3><p>Understanding when to use each operation is essential for building performant applications:</p><p><strong>Scan</strong>:</p><ul><li>Best used for <strong>analytics or batch operations</strong>.</li><li>Avoid in production for frequent or real-time requests due to its resource intensity.</li><li>Filters are applied post-scan, so all items are read, increasing the read cost.</li></ul><p><strong>Query</strong>:</p><ul><li>Ideal for <strong>targeted data retrieval</strong> when you know the partition key.</li><li>It’s faster and more cost-efficient than Scan as it only reads the matching items.</li><li>Use the sort key to further refine results (e.g., fetching records within a specific date range).</li></ul><p><strong>GetItem</strong>:</p><ul><li>Perfect for <strong>low-latency retrieval</strong> of a single record when both partition and sort keys are available.</li><li>Highly efficient and recommended for read-intensive, real-time applications.</li></ul><h3>Conclusion</h3><p>Choosing the right data retrieval method in DynamoDB is crucial to optimize both performance and cost. Use <strong>Scan</strong> sparingly and focus on <strong>Query</strong> for fetching targeted data. For single-record lookups, always prefer <strong>GetItem</strong>. By understanding the strengths and limitations of each operation, you can build scalable and cost-effective solutions tailored to your application’s needs.</p><p>Now that you’ve mastered Scan, Query, and GetItem with DynamoDB, go ahead and apply these best practices to your projects, and let me know how it improves your workflow!</p><p><strong>What’s Next?</strong></p><ul><li>Explore <strong>DynamoDB Streams</strong> for real-time event processing.</li><li>Optimize your data retrieval patterns with <strong>DynamoDB Global Tables</strong> for multi-region applications.</li><li>Look into <strong>DynamoDB Partitioning and Hotspot Avoidance</strong> for advanced scaling techniques.</li></ul><p>Feel free to share your thoughts, questions, or additional optimizations you’ve come across while working with DynamoDB in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab13ea4c046b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>