<?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 Mahesh Dissanayaka on Medium]]></title>
        <description><![CDATA[Stories by Mahesh Dissanayaka on Medium]]></description>
        <link>https://medium.com/@mmkdissa?source=rss-373010b5786a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oBpdniLKGyVUJJgHpoA_pg.png</url>
            <title>Stories by Mahesh Dissanayaka on Medium</title>
            <link>https://medium.com/@mmkdissa?source=rss-373010b5786a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:13:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mmkdissa/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[AWS Lambda Optimizations: Maximizing Performance and Efficiency]]></title>
            <link>https://medium.com/@mmkdissa/aws-lambda-optimizations-maximizing-performance-and-efficiency-84831616486c?source=rss-373010b5786a------2</link>
            <guid isPermaLink="false">https://medium.com/p/84831616486c</guid>
            <category><![CDATA[parallel-processing]]></category>
            <category><![CDATA[batch-processing]]></category>
            <category><![CDATA[lambda-layer]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Mahesh Dissanayaka]]></dc:creator>
            <pubDate>Wed, 19 Jul 2023 12:47:06 GMT</pubDate>
            <atom:updated>2023-07-19T13:09:25.462Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*NgcIc99yR6UWjvNIlszUjg.png" /></figure><p><strong>Introduction</strong></p><p>At <a href="https://www.gotradie.com.au/">GoTradie</a>, our core focus lies in building a large-scale chat platform where the timely and efficient delivery of messages holds utmost importance. Real-time communication is a user expectation, and any delays in message delivery can result in frustration, miscommunication, and a subpar user experience. In a bustling chat environment with a substantial user base, the significance of rapid message delivery is further emphasized. Delays in delivering messages to a large group can lead to significant communication lags, resulting in missed opportunities, project bottlenecks, or even potential financial losses during critical scenarios.</p><p>To power our platform, we heavily rely on AWS managed services, with most of our business logic executed on AWS Lambda. AWS Lambda has transformed the landscape of serverless computing, offering scalability and cost-effectiveness by eliminating the need to manage servers. As more businesses adopt serverless architectures, optimizing AWS Lambda functions becomes indispensable to ensure peak performance and resource efficiency. In this article, I will explore the diverse strategies and best practices we have implemented to ensure the efficient delivery of messages and achieve peak efficiency and cost-effectiveness within AWS Lambda</p><p><strong>Lambda Memory</strong></p><p>One of the most straightforward yet impactful optimizations is right-sizing the memory allocated to Lambda functions. Memory allocation directly affects CPU and network resources available to a function, impacting its overall performance. By closely monitoring the function’s memory usage and adjusting it to meet actual requirements, you can strike a perfect balance between performance and cost efficiency.</p><pre>  WSSendMessageLambda:<br>    Type: AWS::Lambda::Function<br>    Properties:<br>      Description: Send message through WS<br>      Runtime: python3.9<br>      Handler: handlers/messages_handler.on_send_message<br>      Code: <br>        S3Bucket: !Ref S3BucketLocation<br>        S3Key: !Ref CodeArtifactName<br>      Environment:<br>        Variables:<br>          CURRENT_BRANCH: !Ref CurrentBranch<br>          THREADS_TABLE_NAME: !Ref MessageThreadsDataTable<br>          MESSAGES_TABLE_NAME: !Ref MessageDataTable<br>          MESSAGE_CONNECTIONS_TABLE: !Ref MessageWSConnectionsTable<br>          WS_ENDPOINT: !Ref WSEndpoint<br>          IMAGES_TABLE: !Ref ImagesDataTable<br>          IMAGES_S3_BUCKET: !Ref ImagesBucket<br>          DOCUMENTS_S3_BUCKET: !Ref DocumentsBucket<br>          FIREBASE_KEY: !Ref FirebaseKey<br>          PAGINATION_CACHE_TABLE: !Ref PaginationStartKeyTable<br>          REPORTING_STREAM_TOPIC: !Ref ReportingStreamName<br>          PUSH_NOTIFICATIONS_TOPIC: !Ref PushNotificaionsTopic<br>          .............<br>          SEND_MESSAGES_PROCESSING_STREAM: !Ref MessagesSendBulkProcessingStream<br>          MARK_AS_READ_PROCESSING_STREAM: !Ref MessagesMarkAsReadBulkProcessingStream<br>          TODOLISTS_THREAD_TABLE: !Ref TodoListsThreadsTable<br>          BATCH_MESSAGE_DELIVERY_PROCESSING_STREAM: !Ref BatchMessageDeliveryProcessingStream<br>      Layers:<br>        - !Ref ImagesLambdaLayerVersion<br>        - !Ref FirebaseLambdaLayerVersion<br>        - !Ref SearchLambdaLayerVersion<br>        - !Ref BaseLambdaLayerVersion<br>      MemorySize: 2048<br>      Role: !GetAtt MessagesManagementLambdaRole.Arn<br>      Timeout: 600</pre><p><strong>Horizontal Scaling with Parallel Processing</strong></p><p>Parallel processing enables the concurrent execution of tasks, allowing multiple messages to be processed simultaneously across different instances . By distributing the workload across multiple computing resources, parallel processing significantly reduces message processing time, ensuring messages reach all recipients swiftly and consistently.</p><p>Implementing parallel processing not only improves the speed of message delivery but also enhances the overall scalability and performance of the chat application. It ensures that the system can handle a rapidly increasing number of users and messages without compromising on responsiveness or incurring delays.</p><p>AWS Lambda inherently supports horizontal scaling, allowing us to process multiple requests simultaneously across multiple instances. Embrace this capability to boost throughput and reduce processing time by distributing the workload across parallel Lambda instances. Leveraging this approach effectively optimizes performance, especially for applications with varying or unpredictable workloads.</p><p>Here is an CloudFormation configs that I have used to implement parallel processing with support of kinesis stream</p><pre>  BatchMessageDeliveryProcessingStream:<br>    Type: AWS::Kinesis::Stream<br>    Properties: <br>      RetentionPeriodHours: 24<br>      ShardCount: 1<br><br>  BatchMessageDeliveryProcessingStreamEventSourceMapping:<br>    Type: AWS::Lambda::EventSourceMapping<br>    Properties: <br>      BatchSize: 5<br>      ParallelizationFactor: 10<br>      Enabled: true<br>      EventSourceArn: !GetAtt BatchMessageDeliveryProcessingStream.Arn<br>      FunctionName: !GetAtt BatchMessageDeliveryStreamProcessorLambda.Arn<br>      StartingPosition: LATEST <br><br>  BatchMessageDeliveryStreamProcessorLambda:<br>    Type: AWS::Lambda::Function<br>    Properties:<br>      Description: Send message through WS<br>      Runtime: python3.9<br>      Handler: handlers/messages_handler.on_message_batch_delivery<br>      Code: <br>        S3Bucket: !Ref S3BucketLocation<br>        S3Key: !Ref CodeArtifactName<br>      Environment:<br>        Variables:<br>          CURRENT_BRANCH: !Ref CurrentBranch<br>          THREADS_TABLE_NAME: !Ref MessageThreadsDataTable          <br>          PROSPECTIVE_USER_TABLE_NAME: !Ref ProspectiveUserDataTable<br>          INVITE_TABLE_NAME: !Ref InviteDataTable          <br>          SEND_MESSAGES_PROCESSING_STREAM: !Ref MessagesSendBulkProcessingStream<br>          MARK_AS_READ_PROCESSING_STREAM: !Ref MessagesMarkAsReadBulkProcessingStream<br>          .............<br>          TODOLISTS_THREAD_TABLE: !Ref TodoListsThreadsTable<br>      Layers:<br>        - !Ref ImagesLambdaLayerVersion<br>        - !Ref FirebaseLambdaLayerVersion<br>        - !Ref SearchLambdaLayerVersion<br>        - !Ref BaseLambdaLayerVersion<br>      MemorySize: 2048<br>      Role: !GetAtt MessagesManagementLambdaRole.Arn<br>      Timeout: 600</pre><pre>    def submit_message_records_to_batch_message_processing_stream(self, payload, kinesis_stream):<br>        if kinesis_stream:<br>            kinesis_client = AWSResourceBuilder.get_kinesis_client()<br>            data = json.dumps(format_for_json(payload))<br>            hash_val = generate_numeric_hash(data)<br>            record = {}<br>            record[&#39;Data&#39;] = data<br>            record[&#39;ExplicitHashKey&#39;] = hash_val<br>            record[&#39;PartitionKey&#39;] = str(uuid4())<br>            kinesis_client.put_records(<br>                Records=[record],<br>                StreamName=kinesis_stream<br>            )<br>        else:<br>            logger = get_logger()<br>            logger.info(&#39;stream is not configured&#39;)</pre><p>above is the python code to submit records to kinesis stream for parallel processing.</p><p><strong>Cold Start Mitigation</strong></p><p>AWS Lambda functions experience cold starts when they are invoked for the first time or after a prolonged period of inactivity. Cold starts can introduce latency and affect the overall user experience. Implement techniques such as provisioned concurrency, scheduled warm-ups, and asynchronous initialization to reduce cold start times and maintain low-latency, responsive functions.</p><p><strong>Optimize Dependencies and Package Size</strong></p><p>The size of your Lambda deployment package can impact cold start times and increase resource consumption. Minimize the package size by eliminating unnecessary dependencies and libraries. Additionally, consider using Lambda Layers to manage common dependencies efficiently across multiple functions.</p><p>Here is an example that we have used lambda layers.</p><pre>  WSSendMessageLambda:<br>    Type: AWS::Lambda::Function<br>    Properties:<br>      Description: Send message through WS<br>      Runtime: python3.9<br>      Handler: handlers/messages_handler.on_send_message<br>      Code: <br>        S3Bucket: !Ref S3BucketLocation<br>        S3Key: !Ref CodeArtifactName<br>      Environment:<br>        Variables:<br>          CURRENT_BRANCH: !Ref CurrentBranch<br>          THREADS_TABLE_NAME: !Ref MessageThreadsDataTable<br>          MESSAGES_TABLE_NAME: !Ref MessageDataTable<br>          MESSAGE_CONNECTIONS_TABLE: !Ref MessageWSConnectionsTable<br>          WS_ENDPOINT: !Ref WSEndpoint<br>          IMAGES_TABLE: !Ref ImagesDataTable<br>          IMAGES_S3_BUCKET: !Ref ImagesBucket<br>          DOCUMENTS_S3_BUCKET: !Ref DocumentsBucket<br>          FIREBASE_KEY: !Ref FirebaseKey<br>          PAGINATION_CACHE_TABLE: !Ref PaginationStartKeyTable<br>          REPORTING_STREAM_TOPIC: !Ref ReportingStreamName<br>          PUSH_NOTIFICATIONS_TOPIC: !Ref PushNotificaionsTopic<br>          PUSH_NOTIFICATION_STREAM_TOPIC: !Ref PushNotificationStream<br>          .................<br>          SEND_MESSAGES_PROCESSING_STREAM: !Ref MessagesSendBulkProcessingStream<br>          MARK_AS_READ_PROCESSING_STREAM: !Ref MessagesMarkAsReadBulkProcessingStream<br>          TODOLISTS_THREAD_TABLE: !Ref TodoListsThreadsTable<br>          BATCH_MESSAGE_DELIVERY_PROCESSING_STREAM: !Ref BatchMessageDeliveryProcessingStream<br>      Layers:<br>        - !Ref ImagesLambdaLayerVersion<br>        - !Ref FirebaseLambdaLayerVersion<br>        - !Ref SearchLambdaLayerVersion<br>        - !Ref BaseLambdaLayerVersion<br>      MemorySize: 2048<br>      Role: !GetAtt MessagesManagementLambdaRole.Arn<br>      Timeout: 600</pre><p><strong>Conclusion</strong></p><p>Optimizing AWS Lambda functions is essential to achieve high-performance, cost-efficient serverless applications. By implementing the strategies and best practices discussed in this article, you can fine-tune your Lambda functions to deliver faster response times, reduce resource wastage, and enhance the overall user experience. Embracing these optimizations will undoubtedly pave the way for a seamless and scalable serverless architecture, allowing you to harness the full potential of AWS Lambda.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84831616486c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hosting Secured, Cache Enabled Image Server on AWS]]></title>
            <link>https://medium.com/@mmkdissa/hosting-secured-cache-enabled-image-server-on-aws-d54abc3b41d5?source=rss-373010b5786a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d54abc3b41d5</guid>
            <category><![CDATA[cognito]]></category>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[lambda-edge]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloudformation]]></category>
            <dc:creator><![CDATA[Mahesh Dissanayaka]]></dc:creator>
            <pubDate>Wed, 03 Aug 2022 08:05:16 GMT</pubDate>
            <atom:updated>2022-08-03T08:05:16.052Z</atom:updated>
            <content:encoded><![CDATA[<p>At GoTradie, we are building capabilities to manage large volumes of media contents. We want to deliver a great user experience while applying world class security. We use S3 buckets to store the media contents and we wanted to create static cacheable URLs that enable the media access only through authenticated sessions. This article is about how I built a Cache Enabled Secured Image Server on AWS.</p><p><strong>Image Server Features</strong></p><ul><li>Secured with Cognito Authentication</li><li>Server Side Caching</li><li>Image Fallback with Redirection Rules</li><li>Fully automated via CloudFormation</li></ul><p>With this article I hope to provide most of the important points that you need to follow if you are dealing with the same. We have automated all the things via CloudFormation and Code Build. I have shared the CloudFormation scripts at the end of the article.</p><p><strong>Overall Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*LOhZWGLArK_b9s9KZcNsqw.png" /><figcaption>Architecture</figcaption></figure><h3><strong>Implementation Tips</strong></h3><ul><li><strong>S3 Bucket Configuration</strong></li></ul><p>You need to create S3 Bucket and permit access only via CloudFront by setting the bucket policy and make sure to block all public access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*J9rMG3sqhKLiMI3gexhITw.png" /></figure><p>In your image server you may store different resolutions of images.</p><p>For that below is a sample S3 Key structure that you can follow</p><p><em>images/xxxxxyyy</em></p><p><em>images-52x52/xxxxxyyy</em></p><ul><li><strong>Lambda Edge Implementation</strong></li></ul><p>Currently AWS supports Lambda Edges only in us-east-1 (North Virginia) region. So you have to create your Lambda Function in that region.</p><p>MediaManagementAuthLamba : This will intercept the CloudFront <strong>viewer-request</strong> and handle the Cognito Authentication. Specific version of this Lambda should be configured to intercept the CloudFront <strong>viewer-request </strong>event.</p><p>You can have your Cognito configured on any other region and authenticate via that.</p><p>Sample Code : MediaManagementAuthLamba</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*15TvBxF7H7mbL_cayaLZaw.png" /><figcaption>MediaManagementAuthLamba — Python Code</figcaption></figure><p>MediaManagementOriginResponseLambda : This Lambda will intercept CloudFront <strong>origin-response</strong> event and redirect to original image if the requested resolution image is not exists at the requested time. We need to avoid caching these responses as the requested resolution images will be stored later. ( We have background process to create different resolution images from original image)</p><p>Sample Code: MediaManagementOriginResponseLambda</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Phs3fiLI8jvQKJRhh5THOg.png" /><figcaption>MediaManagementOriginResponseLambda — Python Code</figcaption></figure><ul><li><strong>CloudFront Configurations</strong></li></ul><p>You need to create CloudFront distribution with <strong>S3 Origin</strong> type and set up <strong>Origin domain</strong> as s3 bucket domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jNykutKgQtIKPEAqNeOZg.png" /><figcaption>Origin domain Configurations</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*w7ImoDi1Oij_9tC8UBwROg.png" /><figcaption>CloudFront Distribution Origin Settings for S3 Bucket Access</figcaption></figure><p>Then you need to configure function-associations for the above configured behavior.</p><p>You need to intercept <strong>viewer request</strong> with MediaManagementAuthLamba function which we created above to handle Cognito authentication. Here you need to configure the ARN of the specific version of the MediaManagementAuthLamba function.</p><p>You need to intercept <strong>origin response </strong>with MediaManagementOriginResponseLambda function which we created above to handle image redirections. Here you need to configure the ARN of the specific version of the MediaManagementOriginResponseLambda function as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*nQtFJu6KxjusbRaqc2vpXQ.png" /><figcaption>CloudFront Distribution Behavior — Function Associations</figcaption></figure><ul><li><strong>Automation via CloudFormation</strong></li></ul><p>Finally its better to automate all above. You can use AWS CloudFormation to automate above all configurations.</p><p>Below you can find the CloudFormation configurations for the CloudFront Distribution, IAM Roles and Lambda Functions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*76N64BQMxhIws3cJjZIAeA.png" /><figcaption>CloudFront Distribution CloudFormation Script</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*baZUwP4ymRE4tESV41PqeQ.png" /><figcaption>CloudFormation Script for Lambdas and Roles</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*M0M8Y_6VSQX0ILy4x4dF9g.png" /><figcaption>CloudFormation Script For S3 Bucket and Bucket Policy</figcaption></figure><p>Thanks for reading. :)</p><p>You can find the source code @</p><p><a href="https://github.com/opengotradie/gt-media-delivery">https://github.com/opengotradie/gt-media-delivery</a></p><p><strong>References</strong></p><ul><li>CloudFront Events</li></ul><p><a href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-cloudfront-trigger-events.html">CloudFront events that can trigger a Lambda@Edge function</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d54abc3b41d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>