<?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 guraycintir on Medium]]></title>
        <description><![CDATA[Stories by guraycintir on Medium]]></description>
        <link>https://medium.com/@guraycintir?source=rss-212cba9beec7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QEdBYi2r_nXsZ7qViA7Olg.jpeg</url>
            <title>Stories by guraycintir on Medium</title>
            <link>https://medium.com/@guraycintir?source=rss-212cba9beec7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:59:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@guraycintir/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[Setup Vite Project for React with Tailwind CSS]]></title>
            <link>https://medium.com/@guraycintir/setup-vite-project-for-react-with-tailwind-css-856a4ff5f902?source=rss-212cba9beec7------2</link>
            <guid isPermaLink="false">https://medium.com/p/856a4ff5f902</guid>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[vitejs]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <dc:creator><![CDATA[guraycintir]]></dc:creator>
            <pubDate>Mon, 07 Apr 2025 20:30:09 GMT</pubDate>
            <atom:updated>2025-04-07T21:20:54.287Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post we will use Vite to create React with Tailwind CSS. First, we will create React project with Vite and then we will add Tailwind CSS to our project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*Ok8bLejJaVqiUvaRnZd0OQ.png" /></figure><blockquote><strong>What is Vite ?</strong></blockquote><p><em>Vite </em>is build tool and development server which aims to provide faster and leaner development experience for modern web projects.</p><p>It has following benefits:</p><ul><li><em>Instant dev server start</em>: Vite serves your code via native ES Modules, so it starts vert fast — no bundling on startup</li><li><em>HMR (Hot Module Replacement)</em>: Updates just the changed module in the browser, making development very smooth and snappy.</li><li><em>Optimized Build</em>: When you build for production, Vite uses Rollup under the hood for efficient bundling and code splitting.</li></ul><blockquote><strong>Create React project with Vite</strong></blockquote><ul><li>Create project with following npm command.</li></ul><pre>npm create vite@latest</pre><p>It will ask following questions:</p><p><em>Project name</em>: react-tailwindcss-vite-project-template</p><p><em>Select a framework</em>: React</p><p><em>Select a variant</em>: JavaScript</p><ul><li>Then change directory to your project folder and run your project.</li></ul><pre>cd react-tailwindcss-vite-project-template<br>npm install<br>npm run dev</pre><ul><li>Open your project in browser: <a href="http://localhost:5173/">http://localhost:5173</a></li></ul><blockquote><strong>What is Tailwind CSS ?</strong></blockquote><p><em>Tailwind CSS</em> is <em>utility-first CSS framewor</em>k packed with classes like flex, text-center, rotate-90 that can be composed to build any design, directly in your markup. It works by scanning all of your HTML files, JavaScript components, and any other templates for class names, generating the corresponding styles and then writing them to a static CSS file.</p><blockquote><strong>Add Tailwind CSS to Project</strong></blockquote><ul><li>Install Tailwind CSS via npm</li></ul><pre>npm install tailwindcss @tailwindcss/vite</pre><ul><li>Configure Vite plugin</li></ul><pre>import { defineConfig } from &#39;vite&#39;<br>import react from &#39;@vitejs/plugin-react&#39;<br>import tailwindcss from &#39;@tailwindcss/vite&#39;<br><br>// https://vite.dev/config/<br>export default defineConfig({<br>  plugins: [react(), tailwindcss()],<br>})</pre><ul><li>Import Tailwind CSS in index.css file</li></ul><pre>@import &quot;tailwindcss&quot;;</pre><ul><li>Start your build process</li></ul><pre>npm run dev</pre><p>If you use Visual Studio Code as IDE, you can install <strong><em>Tailwind CSS IntelliSense extension</em></strong>. It enhances the Tailwind development experience by providing Visual Studio Code users with advanced features such as autocomplete, syntax highlighting, and linting.</p><p>This post can be useful to create initial React project with Tailwind CSS based on Vite build tool. If you want to have the source code, you can download this sample project from my <a href="https://github.com/gcintir/react-tailwindcss-projects/tree/main/react-tailwindcss-vite-project-template">github repo</a>. If this article is helpful for you, please share it so that more people can use this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=856a4ff5f902" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connecting AWS ElastiCache Serverless in Private Subnet via Bastion Host with Spring Boot]]></title>
            <link>https://medium.com/@guraycintir/connecting-aws-elasticache-serverless-in-private-subnet-via-bastion-host-with-spring-boot-e7f566bfca08?source=rss-212cba9beec7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7f566bfca08</guid>
            <category><![CDATA[aws-elasticache]]></category>
            <category><![CDATA[aws-security-group]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[bastion-host]]></category>
            <category><![CDATA[subnet]]></category>
            <dc:creator><![CDATA[guraycintir]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 21:14:46 GMT</pubDate>
            <atom:updated>2024-12-19T21:14:46.610Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*ur8CyW5meAnQrX34069PPg.jpeg" /><figcaption>Bastion Host to AWS ElastiCache</figcaption></figure><p>In modern cloud-based applications, ensuring secure access to private resources is a critical aspect of system architecture. <strong><em>AWS ElastiCache Serverless</em></strong>, often deployed within private subnets for enhanced security, requires careful configuration when accessed from external systems or local environments.</p><p>One effective way to achieve secure access is by using a <strong><em>bastion host</em></strong> — a gateway server that bridges external connections to private resources within a VPC. In this blog post, I’ll walk you through the process of connecting to an AWS ElastiCache Serverless located in a private subnet using a bastion host, all within the context of a <strong><em>Spring Boot application</em></strong>.</p><p>Whether you’re looking to integrate ElastiCache for caching, session management, or real-time data processing, this guide will help you overcome the challenge of securely accessing private cloud resources without exposing them to the public internet. Let’s dive in!</p><p>First, we need to create an EC2 instance, bastion host, in the VPC in which ElasticCache Serverless is created. Then, we need to verify that security group of bastion host has an inbound rule entry allowing incoming TCP traffic on port 22 because we upload our spring boot application jar to bastion host via SSH connection. You could set your computer’s IP address as a source instead of setting 0.0.0.0/0 to allow SSH connection from only your computer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P0sNJceZGL7HpaN5ZQpAlw.png" /><figcaption>Bastion Host Security group Inbound rule</figcaption></figure><p>Secondly, we need to allow communication from bastion host to ElastiCache Serverless. To do that, we add inbound rule entry of security group of ElastiCache Serverless allowing incoming TCP traffic on port 6379 because redis or valkey cache engines communicates on port 6379. Security group of bastion host is set as source in this inbound rule entry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVSU2msE5APzQHp7RkgR7A.png" /><figcaption>ElastiCache Security group Inbound rule</figcaption></figure><p>After configuring inbound rules of security groups of both ElastiCache and bastion host, we setup our spring boot application connecting to ElastiCache.</p><p>We add spring-boot-starter-data-redis maven dependency in pom.xml file.</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-data-redis&lt;/artifactId&gt;<br>   &lt;version&gt;3.4.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Jedis and Lettuce are two different client libraries to connect to Redis. We use Lettuce in our application. As ElastiCache requires SSL based connection, we configure LettuceConnection to use SSL as seen on below configuration.</p><pre>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.data.redis.connection.RedisStandaloneConfiguration;<br>import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;<br>import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;<br>import org.springframework.data.redis.core.RedisTemplate;<br>import java.time.Duration;<br><br>@Configuration<br>public class ElasticCacheRedisConfig {<br>    private static String host = &quot;AWS_ELASTICACHE_SERVERLESS_ENDPOINT&quot;;<br>    private static Integer port = 6379;<br>    <br>    @Bean<br>    public LettuceConnectionFactory lettuceConnectionFactory(){<br>        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(host, port);<br>        LettuceClientConfiguration lettuceClientConfiguration = LettuceClientConfiguration.builder()<br>                .useSsl() // SSL connection is required for ElastiCache<br>                .and()<br>                .commandTimeout(Duration.ofSeconds(10))<br>                .build();<br>        return new LettuceConnectionFactory(redisStandaloneConfiguration, lettuceClientConfiguration);<br>    }<br><br>    @Bean<br>    public RedisTemplate&lt;String, Object&gt; redisTemplate(LettuceConnectionFactory lettuceConnectionFactory){<br>        RedisTemplate&lt;String, Object&gt; template = new RedisTemplate&lt;&gt;();<br>        template.setConnectionFactory(lettuceConnectionFactory);<br>        return template;<br>    }<br>}</pre><p>Then, we implement our simple cache service class which autowires RedisTemplate for caching operations.</p><pre>import lombok.RequiredArgsConstructor;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.data.redis.core.RedisTemplate;<br>import org.springframework.stereotype.Service;<br>import java.util.Objects;<br><br>@Slf4j<br>@Service<br>@RequiredArgsConstructor<br>public class CacheService {<br>    @Autowired<br>    private RedisTemplate&lt;String, Object&gt; redisTemplate;<br><br>    public void cacheData (String key, String value) {<br>        redisTemplate.opsForValue().set(key, value);<br>        System.out.println(&quot;data cached&quot;);<br>    }<br><br>    public String getData (String key) {<br>        Object rawValue = redisTemplate.opsForValue().get(key);<br>        if (Objects.nonNull(rawValue)) {<br>            return (String) rawValue;<br>        } else {<br>            return null;<br>        }<br>    }<br>    <br>    public Boolean removeData (String key) {<br>        return redisTemplate.delete(key);<br>    }<br>}</pre><p>Finally, we upload our Spring boot application jar file to bastion host via scp command and we connect to bastion host via SSH connection.</p><pre>scp -i ec2-keypair.pem app.jar ec2-user@&lt;bastion_host_public_ip_address&gt;:/home/ec2-user/.<br><br>ssh -i ec2-keypair.pem ec2-user@&lt;bastion_host_public_ip_address&gt;</pre><p>In this post, we explored how to securely connect to an AWS ElastiCache Serverless in a private subnet using a bastion host and integrated it with a Spring Boot application. By leveraging a bastion host, we ensure that private resources remain protected while still being accessible for legitimate use cases.</p><p>This setup not only strengthens your application’s security but also adheres to best practices for cloud architecture. While the process might seem complex at first, understanding the underlying principles can empower you to design robust and secure systems.</p><p>As you implement this solution, remember to regularly audit your security groups, keep your bastion host minimal and updated, and explore alternative solutions like AWS Systems Manager for even tighter control. With the right tools and configurations, you can build scalable, secure, and high-performing applications.</p><p>Thank you for reading! If you found this guide helpful, feel free to share it or drop a comment below with your thoughts or questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7f566bfca08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering AWS SQS Integration with Spring Cloud AWS: Hands-On Examples and Testcontainers-Powered…]]></title>
            <link>https://medium.com/@guraycintir/mastering-aws-sqs-integration-with-spring-cloud-aws-hands-on-examples-and-testcontainers-powered-eab974508498?source=rss-212cba9beec7------2</link>
            <guid isPermaLink="false">https://medium.com/p/eab974508498</guid>
            <category><![CDATA[sqs]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[testcontainer]]></category>
            <category><![CDATA[localstack]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <dc:creator><![CDATA[guraycintir]]></dc:creator>
            <pubDate>Mon, 09 Dec 2024 21:33:22 GMT</pubDate>
            <atom:updated>2024-12-09T21:33:22.823Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering AWS SQS Integration with Spring Cloud AWS: Hands-On Examples and Testcontainers-Powered Testing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*yiRuPoI1xSgEyJwiFmRhAg.png" /><figcaption>Spring Cloud AWS Amazon SQS Messaging</figcaption></figure><p>Spring Cloud AWS is a powerful library designed to simplify interactions with AWS services in Spring and Spring Boot applications. Among its many features, the <strong>Spring Cloud AWS SQS Integration framework</strong> stands out by offering seamless abstractions for working with Amazon Simple Queue Service (SQS). Key tools like the <strong><em>SqsTemplate </em></strong>interface and <strong><em>@SqsListener</em></strong> annotation make it easy to integrate messaging into your applications with minimal boilerplate code.</p><p><a href="https://medium.com/@guraycintir/a-comprehensive-guide-to-amazon-sqs-messaging-for-scalable-systems-e0909dde9d8b">In the previous article</a> we deep dive into Amazon SQS comprehensively.In this article, we will:</p><ul><li>Explore various scenarios for sending and receiving messages with Amazon SQS.</li><li>Use <strong>integration tests powered by Testcontainers</strong> to ensure our implementations are robust and reliable.</li><li>Leverage <strong>LocalStack</strong>, a fully functional local AWS cloud emulator, to simulate Amazon SQS and create a safe and cost-effective testing environment.</li></ul><p>By the end of this guide, you’ll have hands-on experience with Spring Cloud AWS SQS integration and understand how to build and test reliable messaging solutions effectively. Let’s dive in!</p><p><em>Step — 1</em>: We add required following dependencies.</p><ul><li>spring-cloud-aws-starter-sqs</li><li>spring-boot-starter-test</li><li>spring-boot-testcontainers</li><li>localstack</li><li>awaitility</li></ul><pre>&lt;!-- Amazon SQS messaging dependency --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.awspring.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-aws-starter-sqs&lt;/artifactId&gt;<br>    &lt;version&gt;3.2.1&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;!-- Test dependencies --&gt;<br>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-testcontainers&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;<br>   &lt;artifactId&gt;localstack&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;<br>   &lt;artifactId&gt;junit-jupiter&lt;/artifactId&gt;<br>   &lt;version&gt;1.20.4&lt;/version&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.awaitility&lt;/groupId&gt;<br>   &lt;artifactId&gt;awaitility&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;</pre><p><em>Step — 2</em>: We define sqs message producer class and autowiring SqsTemplate class.</p><pre>public class MessageProducerService {<br><br>    @Autowired<br>    private SqsTemplate sqsTemplate;<br>}</pre><p><em>Step — 3</em>: We define sqs message consumer class will include our consumer methods.</p><pre>public class MessageConsumerService {<br><br><br>    @SqsListener(value = &quot;${queue_1.name}&quot;)<br>    public void consumeStringMessage(String stringMessage) {<br>        receivedStringMessageList.add(stringMessage);<br>    }<br><br>.......<br>}</pre><p><em>Step — 4</em>: We define sqs queue names and required sqs configuration in application-test.properties file.</p><pre>queue_1.name=queue-1<br>queue_2.name=queue-2<br>queue_3.name=queue-3<br>queue_4.name=queue-4<br>queue_5.name=queue-5<br>queue_6.name=fifo-queue.fifo<br>queue_7.name=queue-7<br>spring.cloud.aws.credentials.access-key=test<br>spring.cloud.aws.credentials.secret-key=test<br>spring.cloud.aws.region.static=us-east-1<br>spring.cloud.aws.sqs.endpoint=http://localhost:4566</pre><p><em>Step — 5</em>: We define integration test class and setup localstack container.</p><pre>@SpringBootTest<br>@Testcontainers<br>@ActiveProfiles(&quot;test&quot;)<br>public class MessagingServiceIT {<br><br>    @Autowired<br>    private MessageProducerService messageProducerService;<br><br>    static SqsClient sqsClient;<br><br>    static final String FIFO_QUEUE_NAME = &quot;fifo-queue.fifo&quot;;<br><br>    @Container<br>    static LocalStackContainer localStack = new LocalStackContainer(<br>            DockerImageName.parse(&quot;localstack/localstack:3.4.0&quot;)<br>    ).withServices(SQS);<br><br>    @BeforeAll<br>    static void beforeAll() {<br>        localStack.start();<br><br>        sqsClient = SqsClient.builder()<br>                .endpointOverride(localStack.getEndpointOverride(SQS))<br>                .credentialsProvider(StaticCredentialsProvider.create(<br>                        AwsBasicCredentials.create(localStack.getAccessKey(), localStack.getSecretKey())<br>                ))<br>                .region(Region.of(localStack.getRegion()))<br>                .build();<br><br>        Map&lt;QueueAttributeName, String&gt; attributes = new HashMap&lt;&gt;();<br>        attributes.put(QueueAttributeName.FIFO_QUEUE, &quot;true&quot;);<br>        attributes.put(QueueAttributeName.CONTENT_BASED_DEDUPLICATION, &quot;true&quot;);<br>        CreateQueueRequest createQueueRequest = CreateQueueRequest.builder()<br>                .queueName(FIFO_QUEUE_NAME)<br>                .attributes(attributes)<br>                .build();<br>        sqsClient.createQueue(createQueueRequest);<br>    }</pre><blockquote><strong>Example Scenarios</strong></blockquote><ul><li><em>Scenario — 1</em>: We send string message content to queue-1 and we consume that string message from queue-1</li></ul><pre>public void sendStringMessage(String stringMessage) { // string message producer<br>  sqsTemplate.send(queue1Name, stringMessage);<br>}</pre><pre>import io.awspring.cloud.sqs.annotation.SqsListener;<br><br>@SqsListener(value = &quot;${queue_1.name}&quot;)<br>public void consumeStringMessage(String stringMessage) { // string message consumer<br>  receivedStringMessageList.add(stringMessage);<br>}</pre><ul><li><em>Scenario — 2</em>: We send string message content to queue-2 with unique identifier in header and we consume that string message from queue-2 and extract unique identifier value from header</li></ul><pre>public void sendStringMessageWithUniqueIdInHeader(String stringMessage, String uniqueId) {<br>   sqsTemplate.send(queue2Name,<br>           MessageBuilder.withPayload(stringMessage)<br>           .setHeader(&quot;uniqueId&quot;, uniqueId)<br>           .build());<br>}</pre><pre>import io.awspring.cloud.sqs.annotation.SqsListener;<br>import org.springframework.messaging.Message;<br><br>@SqsListener(value = &quot;${queue_2.name}&quot;)<br>public void consumeStringMessageWithUniqueIdInHeader(Message&lt;String&gt; message) {<br>  receivedStringMessageList.add(message.getPayload());<br>  lastReceivedId = (String) message.getHeaders().get(&quot;uniqueId&quot;);<br>}</pre><ul><li><em>Scenario — 3</em>: We send list of string messages to queue-3 and we consume that list of string messages from queue-3</li></ul><pre>public void sendStringMessageList(List&lt;String&gt; stringMessageList) {<br>    sqsTemplate.sendMany(queue3Name, stringMessageList.stream().map(message -&gt; MessageBuilder.withPayload(message).build()).toList());<br>}</pre><pre>import io.awspring.cloud.sqs.annotation.SqsListener;<br>import org.springframework.messaging.Message;<br><br>@SqsListener(value = &quot;${queue_3.name}&quot;)<br>public void consumeStringMessageList(List&lt;Message&lt;String&gt;&gt; messageList) {<br>  receivedStringMessageList.addAll(messageList.stream().map(Message::getPayload).toList());<br>}</pre><ul><li><em>Scenario — 4</em>: We send string message with specific delay to queue-4 and we consume that string message from queue-4 after that specific delay duration</li></ul><pre>public void sendStringMessageWithDelay(String stringMessage, Integer delayInSeconds) {<br>    sqsTemplate.send(sqsSendOptions -&gt; {<br>        sqsSendOptions<br>                .queue(queue4Name)<br>                .payload(stringMessage)<br>                .delaySeconds(delayInSeconds);<br>    });<br>}</pre><pre>import io.awspring.cloud.sqs.annotation.SqsListener;<br>import org.springframework.messaging.Message;<br><br>@SqsListener(value = &quot;${queue_4.name}&quot;)<br>public void consumeStringMessageWithDelay(Message&lt;String&gt; message) {<br>  receivedStringMessageList.add(message.getPayload());<br>}</pre><ul><li><em>Scenario — 5</em>: We send string message to queue-5 and we consume that string message from queue-5 with specified maxConcurrentMessages and maxMessagesPerPoll setting</li></ul><pre>public void sendStringMessagetoQueue5(String stringMessage) {<br>    sqsTemplate.send(queue5Name, stringMessage);<br>}</pre><pre>import io.awspring.cloud.sqs.annotation.SqsListener;<br><br>/**<br>* maxConcurrentMessages (for concurrency control): controls the maximum number of messages that can be processed concurrently<br>* by a single @SqsListener (default: 10)<br>*  If you want to increase or decrease parallel processing, adjust this value.<br>*<br>* maxMessagesPerPoll (for pooling control): defines how many messages should be retrieved in a single poll from the queue (default: 10)<br>* Helps in reducing the number of API calls and improving performance if batching messages is more efficient.<br>*/<br><br>@SqsListener(value = &quot;${queue_5.name}&quot;, maxConcurrentMessages = &quot;5&quot;, maxMessagesPerPoll = &quot;2&quot;)<br>public void consumeStringMessageInParallel(String stringMessage) {<br>  receivedStringMessageList.add(stringMessage);<br>  consumerThreadIdList.add(Thread.currentThread().getId());<br>}</pre><ul><li><em>Scenario — 6</em>: We create FIFO queue with content based deduplication enabled and with name fifo-queue.fifo. We send duplicate string messages and we consume string messages having unique payload.</li></ul><pre>Map&lt;QueueAttributeName, String&gt; attributes = new HashMap&lt;&gt;();<br>        attributes.put(QueueAttributeName.FIFO_QUEUE, &quot;true&quot;);<br>        attributes.put(QueueAttributeName.CONTENT_BASED_DEDUPLICATION, &quot;true&quot;);<br>        CreateQueueRequest createQueueRequest = CreateQueueRequest.builder()<br>                .queueName(&quot;fifo-queue.fifo&quot;)<br>                .attributes(attributes)<br>                .build();<br>        sqsClient.createQueue(createQueueRequest);</pre><pre>@Test<br>public void givenDuplicateStringMessage_whenSendStringMessageToFifoQueue_thenConsumeDuplicateStringMessageFromFifoQueue () {<br>    String validStringMessage = &quot;valid sqs message&quot;;<br><br>    for (int i = 0; i &lt; 5; i++) {<br>        messageProducerService.sendStringMessageToFifoQueue(validStringMessage);<br>    }<br>    messageProducerService.sendStringMessageToFifoQueue(validStringMessage.toUpperCase());<br><br>    Awaitility.await().atMost(2, SECONDS).untilAsserted(() -&gt; {<br>        Assertions.assertEquals(2, MessageConsumerService.receivedStringMessageList.size());<br>    });<br>}</pre><pre>import io.awspring.cloud.sqs.annotation.SqsListener;<br><br>// content-based deduplication enabled<br>@SqsListener(value = &quot;${queue_6.name}&quot;)<br>public void consumeDuplicateStringMessageFromFifoQueue(String stringMessage) {<br>    receivedStringMessageList.add(stringMessage);<br>}</pre><ul><li><em>Scenario — 7</em>: We send device temperature message to queue-7 and we consume that device temperature message from queue-7</li></ul><pre>@Test<br>public void givenValidDeviceTemperature_whenSendDeviceTemperature_thenConsumeDeviceTemperatureMessage () throws InterruptedException {<br>    for (int i = 0; i &lt; 5; i++) {<br>        DeviceTemperature validDeviceTemperature = DeviceTemperature.builder()<br>                .deviceId(new Random().nextInt(50) + &quot;&quot;)<br>                .temperature(new Random().nextInt(5, 50))<br>                .build();<br>        messageProducerService.sendDeviceTemperature(validDeviceTemperature);<br>    }<br><br>    Awaitility.await().atMost(2, SECONDS).untilAsserted(() -&gt; {<br>        Assertions.assertEquals(5, MessageConsumerService.deviceTemperatureList.size());<br>    });<br>}</pre><pre>/**<br>* Producer side: Object Serialization:If you&#39;re sending an object (like a Java POJO), it is serialized into a JSON string before being sent to the SQS queue.<br>* This can be done manually or automatically using libraries like Jackson.<br>*/<br>public void sendDeviceTemperature(DeviceTemperature deviceTemperature) {<br>  sqsTemplate.send(queue7Name, deviceTemperature);<br>}</pre><pre>import io.awspring.cloud.sqs.annotation.SqsListener;<br><br>/**<br> * consumer side: Message Deserialization: When an SQS message is received, it arrives as a JSON string<br> * The message is then deserialized back into a Java object using the appropriate deserialization logic (e.g., Jackson).<br> */<br>@SqsListener(value = &quot;${queue_7.name}&quot;,pollTimeoutSeconds = &quot;5&quot;)<br>public void consumeDeviceTemperatureMessage(List&lt;Message&lt;DeviceTemperature&gt;&gt; deviceTemperatureMessageList) {<br>    deviceTemperatureMessageList.forEach(deviceTemperatureMessage -&gt; deviceTemperatureList.add(deviceTemperatureMessage.getPayload()));<br>}</pre><p>Integrating Amazon SQS into your Spring Boot application using Spring Cloud AWS makes working with messaging queues intuitive and efficient. By leveraging abstractions like <strong><em>SqsTemplate </em></strong>and <strong><em>@SqsListener</em></strong> you can streamline message handling while maintaining clean and readable code. Using <strong><em>Testcontainers</em></strong><em> </em>for integration tests ensures your solution is reliable in real-world scenarios, and tools like <strong><em>LocalStack</em></strong><em> </em>enable safe, cost-effective testing environments that closely mimic AWS services.</p><p>By following the examples and scenarios discussed in this guide, you now have a solid foundation for building robust, scalable, and thoroughly tested messaging systems. As you continue exploring Spring Cloud AWS, consider expanding your knowledge to other AWS services, further unlocking the potential of cloud-native development. You can clone project from my <a href="https://github.com/gcintir/spring-cloud-aws-sqs-messaging">github repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eab974508498" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Guide to Amazon SQS: Messaging for Scalable Systems]]></title>
            <link>https://medium.com/@guraycintir/a-comprehensive-guide-to-amazon-sqs-messaging-for-scalable-systems-e0909dde9d8b?source=rss-212cba9beec7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0909dde9d8b</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[messaging]]></category>
            <category><![CDATA[sqs]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[guraycintir]]></dc:creator>
            <pubDate>Wed, 27 Nov 2024 15:34:13 GMT</pubDate>
            <atom:updated>2024-11-27T15:34:13.099Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*RcwpIrPzbjPfEv63_ApKnw.png" /><figcaption>Amazon SQS</figcaption></figure><p>Amazon SQS is scalable, reliable, cost-effective and fully managed message queuşng service for managing asynchronous communication between distributed systems, making it a cornerstone of modern cloud-native architectures. We can decouple processes which handle heavy operations in order to buffer messages and to process those messages in a batch. Messages are stored in SQS queue until they are processed by consumer systems.</p><blockquote><strong>How it works</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*qy1upF4cClCJ-B05WWfroA.png" /><figcaption>AWS SQS Work Flow</figcaption></figure><p>Basically, there are three actors for Amazon SQS: Producers, Consumers and Queue.</p><p><strong>Producers</strong>: services which send messages to SQS queue. Messages can be sent in either as a batch or as a single. Producers can be applications, microservices and AWS services.</p><p><strong>Consumers</strong>: services which consume messages from SQS queue. Consuming flow works with pooling approach meaning that consumers periodically pool SQS queue to consume messages. Consumers can be applications, microservices and AWS services such as Lambda functions.</p><p><strong>Queue</strong>: persistence component to store messages, sent by producers.</p><blockquote><strong>Features</strong></blockquote><ul><li><strong>Durability and Availability</strong>: SQS messages are stored in multiple Availability Zones (AZs). This built-in redundancy ensures high availability and durability of messages.</li><li><strong>Scalability</strong>: Amazon SQS queues scale elastically. It offers two type of queues: Standard Queue provides nearly unlimited throughput and at-least-once delivery. FIFO (First-In-First-Out) Queue provides exactly once delivery and message ordering. FIFO queue also provides message deduplication.</li><li><strong>Security</strong>: Amazon SQS integrates with AWS IAM service so that you can define access policy for both who can send messages and who can consume messages. Amazon SQS provides in-transit encryption by default. You can enable server-side encryption in order to add at-rest encryption to queue. Encryption key can be Amazon SQS key (SSE-SQS) or AWS Key Management Service key (SSE-KMS). <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-internetwork-traffic-privacy.html"><em>VPC Endpoint</em></a> is supported by SQS so that queues are accessed by Virtual Private Cloud (VPC) privately without traversing public internet.</li><li><strong>Message Storage</strong>: Messages are stored in SQS queue by default 4 days. This time duration can be configured with message retention period (min: 1 minute, max: 14 days) configuration property. Messages are removed from queue by SQS service itself after retention period passes.</li><li><strong>Monitoring and Logging</strong>: CloudWatch metrics provides performance insights related to your queue such as number of messages in queue, number of messages deleted, etc. CloudTrail logs provide information for SQS API calls for auditing and troubleshooting.</li></ul><blockquote><strong>Configuration</strong></blockquote><p>There are several configuration parameters you can set during Amazon SQS queue creation. You can also update those parameters after queue creation.</p><ul><li><strong>Type</strong>: queue can be standard type or FIFO type.</li><li><strong>Visibility timeout</strong>: time duration that a message from a queue will not be visible to other message consumers.</li><li><strong>Message retention period</strong>: amount of time that Amazon SQS retains a message in the queue.</li><li><strong>Delivery delay</strong>: amount of time to delay the first delivery of each message added to queue.</li><li><strong>Maximum message size</strong>: the size of message which can be sent to the queue. Maximum value can be 256 KB</li><li><strong>Receive message wait time</strong>: maximum amount of time that polling will wait for messages to become available.</li><li><strong>Encryption (Server-side encryption)</strong>: encryption at rest can be enabled via using Amazon SQS key or AWS Key Management Service key</li><li><strong>Access policy</strong>: defining the accounts, users and roles that can access this queue, and the actions that are allowed. You can configure basic and advanced settings.</li><li><strong>Redrive allow policy</strong>: allowing policy defines which source queues can use this queue as the dead-letter queue. It is disabled, by default.</li><li><strong>Dead-letter queue</strong>: if a message can not be consumed successfully, this message can be sent to a DLQ for troubleshooting. If you configure a DLQ, you also need to set maximum receives configuration parameter, determining when a message will be sent to the DLQ.</li><li><strong>Content-based deduplication</strong> (FIFO queue setting): if it is enabled Amazon SQS generates MessageDeduplicationId by calculating SHA-256 hash of the message body.</li><li><strong>High throughput FIFO queue</strong> (FIFO queue setting): it can be enabled explicitly. While standard FIFO queues support 300 transactions per second (TPS), high throughput FIFO queues support up to 3000 TPS with batching or 3000 messages per second.</li><li><strong>Deduplication scope</strong> (FIFO queue setting): it can be queue (deduplication is applied at queue level) or message group (deduplication is applied at message group level)</li><li><strong>FIFO throughput limit</strong> (FIFO queue setting): it can be per queue (throughput is limited across entire queue)or per message group ID (throughput is managed at the level of each MessageGroupId)</li></ul><blockquote><strong>Cost</strong></blockquote><p>AWS Free Tier offers<em> Always Free</em> services with some quotas meaning that always free offers do not automatically expire at the end of your 12 month AWS Free Tier term, but are available to both existing and new AWS customers indefinitely. In this scope, Amazon SQS offers first 1 million SQS API requests for free. You can reach other Always Free services offered by AWS Free Tier via this <a href="https://aws.amazon.com/free/?all-free-tier.sort-by=item.additionalFields.SortRank&amp;all-free-tier.sort-order=asc&amp;awsf.Free%20Tier%20Types=tier%23always-free&amp;awsf.Free%20Tier%20Categories=*all"><em>link</em></a>.</p><p>Amazon SQS queue charges based on following factors:</p><ul><li><strong>Region</strong>: AWS region at which you create SQS queue</li><li><strong>Queue Type</strong>: API requests to FIFO queues are more expensive than those to Standard queues</li><li><strong>API request</strong>: number of API calls such as ReceiveMessage, DeleteMessage etc.</li><li><strong>Outbound Data Transfer</strong>: While Inbound data transfer is free, outbound data transfer costs if queue data (message) is transferred from the regions other than queue region and also internet.</li></ul><p>Example cost calculation scenario:</p><p>Suppose that I have producer application, consumer application and standard SQS queue. Applications are running and SQS queue is located in us-east-1 region. Producer application sends 20 million messages to queue per month and all these messages are consumed by consumer application successfully. What is the cost estimation of using Amazon SQS queue in our solution ?</p><p>AWS offers <a href="https://calculator.aws/#/"><em>Pricing Calculator</em></a> to estimate cost for our architecture solution. We use this web based tool to estimate cost for SQS queue.</p><p>Cost factors:</p><ul><li>region: us-east-1</li><li>queue type: standard queue</li><li>API request: 20 million SendMessage API call (by producer application) + 20 million ReceiveMessage API call (by consumer application) + 20 million DeleteMessage API call (by consumerapplication) = 60 million API call to SQS queue</li></ul><p>As seen on below picture, when we input cost factor inputs into Pricing Calculator, it gives us <em>23.60 USD total SQS cost monthly</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hmlTwNObXP6PzE0Ye-CWng.png" /><figcaption>AWS Cost Calculator</figcaption></figure><blockquote><strong>Message Lifecycle</strong></blockquote><p>Following picture shows lifecycle of a message from creation to deletion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*lMqhMSRi-vUmY7fAlga3dw.png" /><figcaption>Message Lifecycle</figcaption></figure><p>Step — 1: Producer (Component 1) sends message A to queue and thr message is distributed across SQS servers in multiple Availability Zones (AZs)</p><p>Step — 2: When Consumer (Component 2) is ready, it pools the messages from queue and SQS returns message A to consumer. During the processing time, message A remains in the queue but not visible to another consumers for the duration of visibility timeout.</p><p>Step — 3: When Consumer (Component 2) processes message A, it deletes message A from queue.</p><blockquote><strong>Message Delivery Concepts</strong></blockquote><ul><li><strong>at-least-once delivery</strong>: Standards queues provide at-least-once delivery. It means that a message may be consumed from queue at least once. The reason behind this behaviours is that the when a message is sent to queue, that message is stored in multiple servers redundantly. In some situations, one of these servers may not be available when you receive or delete the message. In this situation, copy of the message which is already processed is not deleted from the unavailable server and you may be received the copy of the message again.</li><li><strong>exactly-once-delivery</strong>: FIFO queues provide exactly-once-delivery via supporting to avoid sending duplicate messages. If the message is retried to send within 5-minute deduplication interval, Amazon SQS does not introduce any duplicates into queue. There are two types of deduplication for FIFO queue: 1-) content-based deduplication: it makes Amazon SQS generates SHA-256 hash based on message content. 2-) message deduplication ID: it requires producer set a unique token in sending message so that retried messages having same token will not be introduced to queue. Please note that Amazon SQS continues to track of message deduplication ID even after the message is received and deleted.</li></ul><blockquote><strong>FIFO Queue Delivery Flow</strong></blockquote><ul><li><strong>Order preservation</strong>: When multiple messages are sent in order to a FIFO queue with unique message deduplication IDs, Amazon SQS stores them. These messages are then received and processed in the exact order.</li><li><strong>Message Group ID</strong>: FIFO queues guarantees that messages are ordered based on their message group ID.</li><li><strong>Receiving message</strong>: FIFO queues handle message retrieval, including batch processing, FIFO order guarantees, and limitations on requesting specific message group IDs. When receiving messages from a FIFO queue with multiple message group IDs, Amazon SQS attempts to return as many messages as possible with the same message group ID in a single call and it allows other consumers to process messages from different message group IDs concurrently.</li><li><strong>High throughput</strong>: High throughput FIFO queues in Amazon SQS efficiently manage high message throughput while maintaining strict message order, ensuring reliability and scalability for applications processing numerous messages. As the messages having unique message group IDs are processed concurrently, increasing number of message groups is recommended to enhance request capacity in FIFO queues.</li></ul><blockquote><strong>Short and Long Pooling</strong></blockquote><p>SQS offers short pooling and long pooling options for receiving messages from queue.</p><ul><li><strong>short pooling (default)</strong>: ReceiveMessage request queries a subset of servers (based on a weighted random distribution) to find available messages and sends an immediate response, even if no messages are found.</li><li><strong>long pooling</strong>: ReceiveMessage request queries all servers for messages, sending a response once at least one message is available, up to the specified maximum. An empty response is sent only if the polling wait time expires. This option can reduce the number of empty responses and potentially lower costs.</li></ul><p>Short pooling occurs when WaitTimeSeconds parameter of ReceiveMessage request is set to 0 in one of two ways:</p><ul><li>ReceiveMessage call sets WaitTimeSeconds to 0</li><li>ReceiveMessage does not set WaitTimeSeconds, but queue attribute ReceiveMessageWaitTimeSeconds is set to 0</li></ul><p><strong><em>ReceiveMessageWaitTimeSeconds </em></strong>parameter is set at the queue level and acts as the default polling timeout for long polling when consumers do not specify WaitTimeSeconds in their ReceiveMessage call.</p><p><strong><em>WaitTimeSeconds</em></strong> parameter is set in individual ReceiveMessage call and overrides queue’s default ReceiveMessageWaitTimeSeconds.</p><blockquote><strong>Visibility Timeout, Delay Queues, Message Timers</strong></blockquote><ul><li><strong>Visibility timeout</strong>: when you receive a message from SQS queue, that message is not visible to other consumers for a time duration. This time duration is controlled by visibility timeout duration configuration parameter. This configuration is useful to set proper visiblity timeout duration for the messages which require extended processing time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*Ul5LvGkR2p3GVAnHw73J4g.png" /><figcaption>Amazon SQS queue Visibility timeout</figcaption></figure><ul><li><strong>Delay queues</strong>: it allows to postpone delivery of new messages to consumers for a duration. This time duration is configured with Delivery delay configuration parameter. For standard queues, queue delay setting does not affect the delay of messages already in the queue while changing queue delay setting affects the delay of messages in FIFO queue.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*hx6cSf0OBCI43zZTeIJIsQ.png" /><figcaption>Amazon SQS queue Delay time</figcaption></figure><ul><li><strong>Message timers</strong>: it allows to set initial invisibility period for a message which is sent to queue. Minimum delay for a message is 0 seconds and maximum value is 15 minutes. FIFO queues dont support message timers, rather they support queue-level delaying.</li></ul><p>In this post, we provided a comprehensive introduction to Amazon SQS, starting with its core functionality and how it serves as a fully managed message queuing service to facilitate communication between distributed systems. We discussed how to configure SQS queues with various parameters, enabling fine-tuned control over message handling, delivery, and processing. Additionally, we explored the interaction between producers and consumers through the queue, demonstrating how messages can be sent, stored, and retrieved reliably. We also covered several key concepts, including message retention, dead-letter queues, and scalability, to ensure a deeper understanding of how SQS can be leveraged for building fault-tolerant, scalable, and decoupled systems. Whether you’re designing a microservices architecture or building event-driven workflows, SQS provides the tools to streamline messaging between system components, offering both flexibility and reliability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0909dde9d8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Realize A Simple CRUD API on Amazon DynamoDB]]></title>
            <link>https://medium.com/@guraycintir/realize-a-simple-crud-api-on-amazon-dynamodb-1457a5e124b7?source=rss-212cba9beec7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1457a5e124b7</guid>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[crud-operations]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <dc:creator><![CDATA[guraycintir]]></dc:creator>
            <pubDate>Mon, 06 May 2024 21:27:15 GMT</pubDate>
            <atom:updated>2024-05-06T21:32:27.293Z</atom:updated>
            <content:encoded><![CDATA[<p>Basically, most of software applications consist of a view layer, business logic layer and persistence layer. CRUD refers to creating, reading, updating and deleting operations and software application use cases are mainly created around CRUD operations. In this post, I will explain how to design and implement a simple CRUD API on Amazon DynamoDB. I will use AWS CDK framework to define cloud infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*BqwohlNgV0uKTgXdK6KguA.png" /></figure><blockquote><strong><em>Use cases</em></strong></blockquote><p>As I user, I want to have an API so that I am able to keep my product information, to retrieve product information, to update product with new information and to remove product information. All operations will be handled by using product identifier parameter and other required parameters.</p><blockquote><strong><em>DynamoDB Attribute Types</em></strong></blockquote><p>DynamoDB provides several attribute types for different data types. We need to know and use them properly in order to model any data structure efficiently.</p><ul><li><strong><em>String type (S)</em></strong> : representing a Unicode string with UTF-8 encoding. We can handle sorting and comparison operations on string types. Example: Give me all last names, sorted alphabetically</li><li><strong><em>Number type (N)</em></strong> : represents positive and negative numbers and zero. It can be used for precision up to 38 digits</li><li><strong><em>Binary type (B)</em></strong> : used to store binary data, encoded with base64</li><li><strong><em>Boolean type (BOOL)</em></strong> : used to store true or false</li><li><strong><em>Null type (NULL)</em></strong><em> </em>: stores true or false to indicate null value</li><li><strong><em>List type (L)</em> </strong>: used to store collection of values. The elements are ordered and do not have be of same type</li><li><strong><em>Map type (M)</em></strong><em> </em>: used to store collection of values as key-value pairs</li><li><strong><em>String Set type (SS)</em> </strong>: used to store set of unique strings</li><li><strong><em>Number Set type (NS)</em></strong> : used to store set of unique numbers</li><li><strong><em>Binary Set type (BS)</em></strong> : used to store set of unique binaries</li></ul><blockquote><strong><em>Product Table Data Modeling</em></strong></blockquote><p>First we need to define primary key for product table as all use cases will be handled by using product identifier. As each product is unified with an identifier attribute, we define <em>productId </em>as primary key. The other attributes are defined as shown below.</p><ul><li>title: String type (S)</li><li>category: String type (S)</li><li>price: Number type (N)</li><li>allowedCreditCards: String set type (SS)</li><li>existingSizes: Number set type (NS)</li><li>stockAmount: Number type (N)</li><li>active: Boolean type (BOOL)</li><li>features: Map type (M)</li><li>createdAt: Number type (N)</li></ul><pre>public class Product {<br>    private String productId; // (S) partition key<br>    private String title; // (S)<br>    private String category; // (S)<br>    private float price; // (N)<br>    private Set&lt;String&gt; allowedCreditCards = new HashSet&lt;&gt;(); // (SS)<br>    private Set&lt;Integer&gt; existingSizes = new HashSet&lt;&gt;(); // (NS)<br>    private int stockAmount; // (N)<br>    private boolean active = true; // (BOOL)<br>    private Map&lt;String, String&gt; features; // (M)<br>    private long createdAt; // (N)<br>}</pre><blockquote><strong><em>Product Table Definition with AWS CDK</em></strong></blockquote><p>We use<strong><em> </em></strong><em>CDK L2 construct</em> to define products DynamoDB table as shown below.</p><pre>Table productsDynamoDbTable = Table.Builder.create(this, &quot;products-dynamodb-table&quot;)<br>                .tableName(&quot;products&quot;)<br>                .partitionKey(Attribute.builder().name(&quot;product_id&quot;).type(AttributeType.STRING).build())<br>                .billingMode(BillingMode.PAY_PER_REQUEST)<br>                .removalPolicy(RemovalPolicy.DESTROY)<br>                .build();</pre><blockquote><strong><em>Create and Update Product Implementation</em></strong></blockquote><p>We can implement product information create and update use cases based on upsert logic, meaning that if product information record does not exist with given product identifier on DynamoDB, the product information will be persisted, otherwise record will be updated with new values.</p><p><strong><em>Put Item</em></strong>: It is used to persist an item into table. If an item already exists with given primary key, this command overwrites existing item with new values. If you want to update specific attributes of an item, you can use Update Item command.</p><p>As seen below, we first populate a HashMap&lt;String, AttributeValue&gt; data structure with attribute names and their values. Then, we create PutItemRequest class and set tableName, item methods on it. Finally, we send PutItemRequest via using DynamoDbClient class.</p><pre>private Product updateProduct (Product product) {<br>        try {<br>            HashMap&lt;String, AttributeValue&gt; itemMap = new HashMap&lt;&gt;();<br>            itemMap.put(&quot;product_id&quot;, AttributeValue.builder().s(product.getProductId()).build());<br>            itemMap.put(&quot;title&quot;, AttributeValue.builder().s(product.getTitle()).build());<br>            itemMap.put(&quot;category&quot;, AttributeValue.builder().s(product.getCategory()).build());<br>            itemMap.put(&quot;price&quot;, AttributeValue.builder().n(String.valueOf(product.getPrice())).build());<br>            itemMap.put(&quot;allowed_credit_cards&quot;, AttributeValue.builder().ss(product.getAllowedCreditCards()).build());<br>            itemMap.put(&quot;existing_sizes&quot;, AttributeValue.builder().ns(product.getExistingSizes().stream().map(Object::toString).collect(Collectors.toList())).build());<br>            itemMap.put(&quot;stock_amount&quot;, AttributeValue.builder().n(String.valueOf(product.getStockAmount())).build());<br>            itemMap.put(&quot;active&quot;, AttributeValue.builder().bool(product.isActive()).build());<br>            itemMap.put(&quot;features&quot;, AttributeValue.builder().m(product.getFeatures().entrySet().stream().collect(<br>                            Collectors.toMap(Map.Entry::getKey, entry -&gt; AttributeValue.builder().s(entry.getValue()).build())))<br>                    .build());<br>            itemMap.put(&quot;created_at&quot;, AttributeValue.builder().n(String.valueOf(new Date().getTime())).build());<br><br>            PutItemRequest putItemRequest = PutItemRequest.builder()<br>                    .tableName(DDB_TABLE_NAME)<br>                    .item(itemMap)<br>                    .build();<br><br>            PutItemResponse putItemResponse = dynamoDbClient.putItem(putItemRequest);<br>            logger.info(&quot;Product updated with id:{} statusCode:{} requestId:{}&quot;, product.getProductId(), putItemResponse.sdkHttpResponse().statusCode(), putItemResponse.responseMetadata().requestId());<br><br>            return product;<br>        } catch (DynamoDbException e) {<br>            logger.error(&quot;DynamoDB exception&quot;, e);<br>            throw new RuntimeException(e);<br>        }<br>    }</pre><blockquote><strong><em>Get Product Implementation</em></strong></blockquote><p>In order to retrieve product information from DynamoDB, we need to use primary key which is <em>productId </em>attribute.</p><p><strong><em>Get Item</em></strong>: It can be used to retrieve an item you want. It receives table name and primary key as parameters.</p><p>As seen below, we first populate a HashMap&lt;String, AttributeValue&gt; data structure with primary key attribute name and it’s value. Then, we create GetItemRequest class and set tableName, key methods on it. Finally, we send GetItemRequest via using DynamoDbClient class. After retrieving product information, we need to extract attribute values and set them to product domain class attributes.</p><pre>private Optional&lt;Product&gt; getProductById (String productId) {<br>        try {<br>            HashMap&lt;String, AttributeValue&gt; keyMap = new HashMap&lt;&gt;();<br>            keyMap.put(&quot;product_id&quot;, AttributeValue.builder().s(productId).build());<br><br>            GetItemRequest getItemRequest = GetItemRequest.builder()<br>                    .tableName(DDB_TABLE_NAME)<br>                    .key(keyMap)<br>                    .build();<br><br>            GetItemResponse getItemResponse = dynamoDbClient.getItem(getItemRequest);<br>            logger.info(&quot;Product retrieve operation completed with statusCode:{} requestId:{}&quot;, getItemResponse.sdkHttpResponse().statusCode(), getItemResponse.responseMetadata().requestId());<br><br>            if (!getItemResponse.hasItem()) {<br>                logger.info(&quot;Product record not found with productId:{}&quot;, productId);<br>                return Optional.empty();<br>            }<br><br>            Map&lt;String, AttributeValue&gt; item = getItemResponse.item();<br>            Product product = new Product();<br>            product.setProductId(item.get(&quot;product_id&quot;).s());<br>            product.setTitle(item.get(&quot;title&quot;).s());<br>            product.setCategory(item.get(&quot;category&quot;).s());<br>            product.setPrice(Float.parseFloat(item.get(&quot;price&quot;).n()));<br>            product.setAllowedCreditCards(new HashSet&lt;&gt;(item.get(&quot;allowed_credit_cards&quot;).ss()));<br>            product.setExistingSizes(new HashSet&lt;&gt;(item.get(&quot;existing_sizes&quot;).ns().stream().map(Integer::valueOf).collect(Collectors.toList())));<br>            product.setStockAmount(Integer.parseInt(item.get(&quot;stock_amount&quot;).n()));<br>            product.setActive(item.get(&quot;active&quot;).bool());<br>            product.setFeatures(item.get(&quot;features&quot;).m().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -&gt; entry.getValue().s())));<br>            product.setCreatedAt(Long.parseLong(item.get(&quot;created_at&quot;).n()));<br><br>            return Optional.of(product);<br><br>        } catch (DynamoDbException e) {<br>            logger.error(&quot;DynamoDB exception&quot;, e);<br>            throw new RuntimeException(e);<br>        }<br>    }</pre><blockquote><strong><em>Delete Product Implementation</em></strong></blockquote><p>In order to delete product information from DynamoDB, we need to use primary key which is <em>productId </em>attribute.</p><p><strong><em>Delete Item</em></strong>: It is used to remove an existing item from table. You need to pass primary key to command as parameter.</p><p>As seen below, we first populate a HashMap&lt;String, AttributeValue&gt; data structure with primary key attribute name and it’s value. Then, we create DeleteItemRequest class and set tableName, key methods on it. Finally, we send DeleteItemRequest via using DynamoDbClient class.</p><pre>private void deleteProductById (String productId) {<br>        try {<br>            HashMap&lt;String, AttributeValue&gt; keyMap = new HashMap&lt;&gt;();<br>            keyMap.put(&quot;product_id&quot;, AttributeValue.builder().s(productId).build());<br><br>            DeleteItemRequest deleteItemRequest = DeleteItemRequest.builder()<br>                    .tableName(DDB_TABLE_NAME)<br>                    .key(keyMap)<br>                    .build();<br><br>            DeleteItemResponse deleteItemResponse = dynamoDbClient.deleteItem(deleteItemRequest);<br>            logger.info(&quot;Product deleted with statusCode:{} requestId:{}&quot;, deleteItemResponse.sdkHttpResponse().statusCode(), deleteItemResponse.responseMetadata().requestId());<br><br>        } catch (DynamoDbException e) {<br>            logger.error(&quot;DynamoDB exception&quot;, e);<br>            throw new RuntimeException(e);<br>        }<br>    }</pre><blockquote><strong><em>Lambda Function Definition with AWS CDK</em></strong></blockquote><p>We use <em>CDK L2 construct</em> to define product handler lambda function as shown below. Please note that we need to grant access to product handler lambda function on products dynamodb table via using productsDynamoDbTable variable.</p><pre>Role productHandlerLambdaexecutionRole = Role.Builder.create(this, id + &quot;-ProductHandlerLambdaRole&quot;)<br>                .assumedBy(new ServicePrincipal(&quot;lambda.amazonaws.com&quot;))<br>                .roleName(id + &quot;-ProductHandlerLambdaRole&quot;)<br>                .build();<br>        productHandlerLambdaexecutionRole.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(&quot;service-role/AWSLambdaBasicExecutionRole&quot;));<br><br>String productHandlerLambdaFunctionName = id + &quot;-ProductHandlerLambda&quot;;<br>        Function productHandlerLambda = Function.Builder.create(this, productHandlerLambdaFunctionName)<br>                .runtime(Runtime.JAVA_21)<br>                .code(Code.fromAsset(&quot;../function/product-handler-lambda/target/product-handler-lambda.jar&quot;))<br>                .handler(&quot;com.awscloudprojects.lambda.ProductHandlerLambda::handleRequest&quot;)<br>                .functionName(productHandlerLambdaFunctionName)<br>                .role(productHandlerLambdaexecutionRole)<br>                .timeout(Duration.seconds(30L))<br>                .memorySize(512)<br>                .logGroup(LogGroup.Builder.create(this, productHandlerLambdaFunctionName + &quot;-logGroup&quot;)<br>                        .logGroupName(&quot;/aws/lambda/&quot; + productHandlerLambdaFunctionName)<br>                        .retention(RetentionDays.ONE_DAY)<br>                        .removalPolicy(RemovalPolicy.DESTROY)<br>                        .build())<br>                .build();<br><br>// grant products dynamodb table access to product handler lambda function<br>productsDynamoDbTable.grantFullAccess(productHandlerLambda);</pre><blockquote><strong><em>Lambda Function Definition with AWS CDK</em></strong></blockquote><p>In order to expose our CRUD functionality through API, we can use <em>AWS API Gateway HTTP API</em>. We define that resource via using <em>CDK L2 construct</em> as shown below. HTTP API is enough for our use case and is cheaper than REST API.</p><pre>HttpApi httpApi = HttpApi.Builder.create(this, &quot;http-api-gateway&quot;)<br>                .apiName(id + &quot;-http-api-gateway&quot;)<br>                .description(&quot;HTTP API Gateway&quot;)<br>                .build();<br><br>        httpApi.addRoutes(AddRoutesOptions.builder()<br>                        .path(&quot;/product&quot;)<br>                        .integration(HttpLambdaIntegration.Builder.create(&quot;product-handler-lambda-integration&quot;, productHandlerLambda)<br>                                .payloadFormatVersion(PayloadFormatVersion.VERSION_1_0)<br>                                .build())<br>                .methods(List.of(HttpMethod.POST))<br>                .build());<br><br>        httpApi.addRoutes(AddRoutesOptions.builder()<br>                .path(&quot;/product&quot;)<br>                .integration(HttpLambdaIntegration.Builder.create(&quot;product-handler-lambda-integration&quot;, productHandlerLambda)<br>                        .payloadFormatVersion(PayloadFormatVersion.VERSION_1_0)<br>                        .build())<br>                .methods(List.of(HttpMethod.PUT))<br>                .build());<br>        <br>        httpApi.addRoutes(AddRoutesOptions.builder()<br>                .path(&quot;/product&quot;)<br>                .integration(HttpLambdaIntegration.Builder.create(&quot;product-handler-lambda-integration&quot;, productHandlerLambda)<br>                        .payloadFormatVersion(PayloadFormatVersion.VERSION_1_0)<br>                        .build())<br>                .methods(List.of(HttpMethod.GET))<br>                .build());<br><br>        httpApi.addRoutes(AddRoutesOptions.builder()<br>                .path(&quot;/product/{productId}&quot;)<br>                .integration(HttpLambdaIntegration.Builder.create(&quot;product-handler-lambda-integration&quot;, productHandlerLambda)<br>                        .payloadFormatVersion(PayloadFormatVersion.VERSION_1_0)<br>                        .build())<br>                .methods(List.of(HttpMethod.DELETE))<br>                .build());</pre><p>In this post, first we learned DynamoDB attribute types. Then, we defined Product DynamoDB table via using different attribute types and AWS CDK L2 construct. Also, we learned how to use DynamoDB commands inside lambda function to realize a simple CRUD API. Finally, we exposed our API through AWS API Gateway. You can reach source code on my <a href="https://github.com/gcintir/api-gateway-lambda-dynamodb-crud-flow/tree/main/function/product-handler-lambda">Github repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1457a5e124b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon DynamoDB — Basic concepts]]></title>
            <link>https://medium.com/@guraycintir/amazon-dynamodb-basic-concepts-088e072f5f80?source=rss-212cba9beec7------2</link>
            <guid isPermaLink="false">https://medium.com/p/088e072f5f80</guid>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[guraycintir]]></dc:creator>
            <pubDate>Mon, 15 Apr 2024 18:25:38 GMT</pubDate>
            <atom:updated>2024-04-15T18:25:38.251Z</atom:updated>
            <content:encoded><![CDATA[<h3>Amazon DynamoDB — Basic concepts</h3><p>DynamoDB is fully managed NoSQL database service, offered by Amazon. In this post, I will explain basic concepts regarding to DynamoDB such as core components, API functions, read consistency modes, read/write capacity modes, table classes and quotas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*6ezKpqUSq5E2Zk2BkSbJkQ.png" /></figure><blockquote><strong>Amazon DynamoDB</strong></blockquote><p>It is fully managed NoSQL database service that provides fast and predictable performance with seamless scalability. We do not have to deal with hardware provisioning, setup, configuration, replication, software patching or clustering.</p><p><em>For security</em>, DynamoDB offers encryption at rest.</p><p><em>For disaster recovery</em>, DynamoDB provides on-demand backup capability.</p><p><em>For high-availability and durability</em>, DynamoDB automatically spreads data and traffic for your tables over sufficient number of servers to handle throughput. All data is stored in SSD and automatically replicated across multiple availability zones in a region. We can also use <em>global tables</em> to keep table data sync across regions.</p><blockquote><strong>Core Components</strong></blockquote><ul><li><em>Table </em>: DynamoDB stores data in tables. It is a collection of data.</li><li><em>Item </em>: each table contains zero or more items. It is a group of attributes that is uniquely identifiable among all other items.</li><li><em>Attribute</em> : each item is composed of one or more attributes. It is fundamental data element.</li><li><em>Partition Key</em> : primary key, composed of one attribute. DynamoDB uses it’s value as input to an internal hash function. Output of hash function determines the partition in which the item will be stored.</li><li><em>Partition Key and Sort Key</em> : referred as composite primary key, it is composed of two attributes. DynamoDB uses the partition key value as input to an internal hash function. The output from the hash function determines the partition (physical storage internal to DynamoDB) in which the item will be stored. All items with the same partition key value are stored together, in sorted order by sort key value.</li><li><em>Global Secondary Index</em> : an index with partition key and sort key that can be different from those on the table.</li><li><em>Local Secondary Index</em> : an index that has same partition key as the table, but a different sort key.</li><li><em>DynamoDB Streams</em> : It is an optional feature that captures data modification events in tables. The data about these events appear in the stream in near-real time and in order that the events occurred.</li></ul><blockquote><strong>DynamoDB API</strong></blockquote><ul><li><em>Control Plane</em> : These operations allow us to create and manage tables. They also let us to work with indexes, streams on tables. Example commands : CreateTable, DescribeTable, ListTables, UpdateTable, DeleteTable</li><li><em>Data Plane</em> : These operations allow us to handle our CRUD operations on data in tables. Example commands : PutItem, BatchWriteItem, GetItem, BatchGetItem, Query, Scan, UpdateItem, DeleteItem, BatchDeleteItem, ListStreams, DescribeStream, GetShardIterator, GetRecords</li><li>Transactions : It provides ACID enabling you to maintain data correctness in our applications. Example commands: TransactWriteItems, TransactGetItems</li></ul><blockquote><strong>Quota Basics</strong></blockquote><p>DynamoDb users have dependency to quotas by Amazon. Followings are some important DynamoDb quotas:</p><ul><li><em>Read capacity unit (RCU)</em> : one strongly consistent read per second, or two eventually reads per second, for items up to 4 KB in size.</li><li><em>Write capacity unit (WCU)</em> : one write per second, for items up to 1 KB in size.</li><li><em>Number of tables</em> : there is initial quota of 2500 tables per region.</li><li><em>Page size limit for query and scan</em> : there is a limit of 1MB per page , per query or scan. If your query parameters or scan operation on a table result more than 1 MB of data, DynamoDB returns ‘<em>LastEvaluatedKey</em>’ parameter along with page data.</li><li><em>Local Secondary Index (LSI) </em>: We can define maximum of 5 LSIs per table.</li><li><em>Global Secondary Index (GSI) </em>: There is default quota of 20 GSIs per table.</li><li><em>Partition key</em> : maximum length is 2048 bytes</li><li><em>Sort key</em> : maximum length is 1024 bytes</li><li><em>Item size</em> : maximum item size is 400 KB</li></ul><blockquote><strong>Read Consistency</strong></blockquote><p>DynamoDB reads data from tables, LSIs, GSIs and streams. All reads from streams and GSIs are eventually consistent while reads from tables and LSIs provide eventual consistency (default) and strongly consistent reads.</p><p>DynamoDB provides read-committed isolation and ensures that read operations always return committed values for an item.</p><ul><li><em>Eventually Consistent Reads</em> : default read consistent model for all read operations. When issuing eventually consistent reads to a DynamoDB table or an index, the responses may not reflect the results of a recently completed write operation. If you repeat your read request after a short time, the response should eventually return the more recent item.</li><li><em>Strongly Consistent Reads</em> : read operations such as GetItem, Query, Scan provide optional ‘<em>ConsistentRead</em>’ parameter. If this parameter is set to true, DynamoDB returns a response with the most up-to-date data, reflecting the updates from all prior write operations that were successful.</li><li><em>Global table read consistency</em> : Any change made to any item in any replica table is replicated to all the other replicas within the same global table, typically within a second, and are eventually consistent.</li></ul><blockquote><strong>Read/Write Capacity Mode</strong></blockquote><p>The read/write capacity mode controls how you are charged for read and write throughput and how you manage capacity. You can set the read/write capacity mode when creating a table or you can change it later.</p><p><em>Secondary indexes inherit the read/write capacity mode from the base table</em>.</p><ul><li><em>On-demand mode</em> : flexible billing option capable of serving thousands of requests per second without capacity planning. DynamoDB on-demand offers pay-per-request pricing for read and write requests so that you pay only for what you use. It is good option if you create new tables with unknown workloads or you have unpredictable application traffic or you prefer the ease of paying for only what you use. Tables can be switched to on-demand mode once every 24 hours. Creating a table as on-demand also starts this 24-hour period.</li><li><em>Provisioned mode</em> : you specify the number of reads and writes per second that you require for your application. You can use auto scaling to adjust your table’s provisioned capacity automatically in response to traffic changes. This helps you govern your DynamoDB use to stay at or below a defined request rate in order to obtain cost predictability. It is good option if you have predictable application traffic or you run applications whose traffic is consistent or ramps gradually or you can forecast capacity requirements to control costs.</li></ul><p>Provisioned throughput is the maximum amount of capacity that an application can consume from a table or index. If your application exceeds your provisioned throughput capacity on a table or index, it is subject to <em>request throttling</em>. Throttling prevents your application from consuming too many capacity units. When a request is throttled, it fails with an HTTP 400 code (Bad Request) and ProvisionedThroughputExceededException. The AWS SDKs have built-in support for retrying throttled requests.</p><p>Example: you create a provisioned table with 6 read capacity units and 6 write capacity units. With these settings, your application could do the following:</p><ul><li>Perform strongly consistent reads of up to 24 KB per second (4 KB × 6 read capacity units).</li><li>Perform eventually consistent reads of up to 48 KB per second (twice as much read throughput).</li><li>Perform transactional read requests of up to 12 KB per second.</li><li>Write up to 6 KB per second (1 KB × 6 write capacity units).</li><li>Perform transactional write requests of up to 3 KB per second.</li></ul><blockquote><strong>Table Classes</strong></blockquote><p>DynamoDB offers two table classes designed to help you optimize for cost. The DynamoDB <em>Standard table</em> class is the default, and is recommended for the vast majority of workloads. The DynamoDB<em> Standard-Infrequent Access</em> (DynamoDB Standard-IA) table class is optimized for tables where storage is the dominant cost. For example, tables that store infrequently accessed data, such as application logs, old social media posts, e-commerce order history, and past gaming achievements, are good candidates for the Standard-IA table class. All secondary indexes associated with the table use the same table class.</p><p>The choice of a table class is not permanent. You can change it later for single-region tables and global tables.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=088e072f5f80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to sort out DynamoDbEvent deserialization issue in AWS Quarkus Lambda]]></title>
            <link>https://medium.com/@guraycintir/how-to-sort-out-dynamodbevent-deserialization-issue-in-aws-quarkus-lambda-b0bda3ca6f4c?source=rss-212cba9beec7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0bda3ca6f4c</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[dynamodb-stream]]></category>
            <category><![CDATA[quarkus-framework]]></category>
            <dc:creator><![CDATA[guraycintir]]></dc:creator>
            <pubDate>Fri, 05 Apr 2024 14:57:14 GMT</pubDate>
            <atom:updated>2024-04-05T14:57:14.955Z</atom:updated>
            <content:encoded><![CDATA[<p>CDC (Change Data Capture) is a solution of tracking all changes in a data source such as database, data warehouse, etc so that downstream services are able to react for data changes. AWS DynamoDb Streams is a feature of AWS DynamoDb service which provides a time-ordered sequence of item-level updates made to a DynamoDb table. DynamoDb Streams can be enabled for a lambda function so that lambda function is able to process DynamoDb stream events. There is an issue during deserialization of DynamoDb stream event in lambda function which is implemented based on Quarkus framework and I will share a simple solution to sort out this deserialization issue in this post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*dKRWgU9kcuCmSnbNRL0UvQ.png" /></figure><p>In Quarkus lambda function, we need to define a class which implements <strong><em>com.amazonaws.services.lambda.runtime.RequestHandler&lt;I,O&gt;</em></strong> generic interface. <strong><em>com.amazonaws.services.lambda.runtime.events.DynamoDbEvent</em></strong> class represents a stream event so we give this class as input parameter type (I) and String class as output parameter type (O) for RequestHandler interface.</p><p>The sample code snippet is shown on below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*rY7hZWtKpbbcXspreGxSvQ.png" /><figcaption>Quarkus Lambda sample invoked by DynamoDb Streams</figcaption></figure><p>When lambda function is triggered by a stream event, lambda function fails to invoke and logs the following failure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HCvK0xj9DfOCYnwRFnqKWw.png" /><figcaption>Lambda failed invocation log</figcaption></figure><p>The error says that deserializer, used by Quarkus, can not deserialize <strong><em>‘ApproximateCreationDateTime’ </em></strong>attribute, located in StreamRecord. The root cause is due to the fact that ‘ApproximateCreationDateTime’ attribute is serialized as <strong><em>Floating-point</em></strong> value by DynamoDb stream before delivering to lambda function and serialized Floating-point value can not be converted to <strong><em>java.util.Date</em></strong> by Quarkus’s deserializer.</p><p>The solution is for this issue is to customize deserialization process of Quarkus framework. To do that, we need to add a class which implements <strong><em>io.quarkus.jackson.ObjectMapperCustomizer</em></strong> and we need to override deserialize method which returns <strong><em>java.util.Date</em></strong>.</p><p>The sample code is shown on below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*PkUu2mRJiQphZC9_JeSzVw.png" /><figcaption>Csutom ObjectMapperCustomizer for Date deserialization</figcaption></figure><p>After adding this class into source code, lambda function invokes successfully and logs following content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQtBrBvdvYpEEVWgtaqKAw.png" /><figcaption>Lambda success invocation log</figcaption></figure><p>That’s all ! I hope it would be helpful for you to sort out the issue at first shot before spending so much time like me :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0bda3ca6f4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Filtering/Searching Lambda function logs with CloudWatch Logs and CloudWatch Log Insights]]></title>
            <link>https://medium.com/@guraycintir/filtering-searching-lambda-function-logs-with-cloudwatch-logs-and-cloudwatch-log-insights-bd5d1cc907fc?source=rss-212cba9beec7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd5d1cc907fc</guid>
            <category><![CDATA[cloudwatch-logs]]></category>
            <category><![CDATA[filtering]]></category>
            <category><![CDATA[searching]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[cloudwatch-logs-insights]]></category>
            <dc:creator><![CDATA[guraycintir]]></dc:creator>
            <pubDate>Mon, 18 Mar 2024 08:19:12 GMT</pubDate>
            <atom:updated>2024-03-18T08:19:40.766Z</atom:updated>
            <content:encoded><![CDATA[<p>AWS lambda functions generate several log entries per invocation. These log entries include valuable information for troubleshooting and performance monitoring of our lambda functions. In this blog, I would like to share some examples on how to handle our filtering and searching operations with lambda function log entries via CloudWatch Logs and CloudWatch Insights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*8m01Lg-r2A6eQ8AoIy_LJg.png" /><figcaption>Lambda function emits logs to CloudWatch Service</figcaption></figure><blockquote><strong>CloudWatch</strong></blockquote><p><em>CloudWatch </em>is monitoring and observability service provided by AWS. It is designed to collect and track metrics, log files and events from various AWS resources, applications and services, as well as from on-promise servers. <em>CloudWatch </em>provides a centralized platform for monitoring and managing the performance, availability, and security of your AWS infrastructure and applications. It is regional service.</p><blockquote><strong>CloudWatch Logs</strong></blockquote><p><em>CloudWatch Logs</em> is a service provided by AWS that enables you to monitor, store, and analyze log files generated by AWS resources and applications. It allows you to centralize log data from various sources, such as EC2 instances, Lambda functions, Elastic Load Balancers (ELB), and more, into a single, scalable repository for easier management and analysis.. Any log statement in your application creates a log event.</p><ul><li><em>Log group</em>: grouping realated log events together</li><li><em>Log stream</em>: provides a further level of distinction within log group</li><li><em>Log event</em>: your application emits logs as events. Log events belong to a log stream</li></ul><blockquote><strong>Filter Pattern Examples</strong></blockquote><ul><li>Filter log entries containing ‘abc’ keyword</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VYBntSexuy1Sg6f9SOGJdw.png" /></figure><ul><li>Filter log entries containing ‘REPORT’ keyword</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sk0lfu8QtyP3mAlh_LiHYg.png" /></figure><p>Using filtering directly with keywords has limitation. It also fetches unstructured log entries.</p><p>Better approach is to use filter patterns which allows us to specify conditions.</p><p><em>Two major rules with filter patterns:</em></p><ul><li>filter patterns have to be enclosed in {}</li><li>set off property selectors with dollar sign followed by a period (“$.”)</li><li>Filter log entries which show input event related to cold start invocations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8FBSM-aWbrNySS9Jf7F4Kg.png" /></figure><ul><li>Filter INFO level log entries of ‘LambdaStack-InputTextReverserLambda’ lambda function</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C5_e2mlAbZ_pFZUj-OWoMQ.png" /></figure><p>Filters can only be used to fetch relevant log entries based on patterns. It can not be used to perform advanced operations such as aggregations and visulations.</p><blockquote><strong>CloudWatch Log Insights</strong></blockquote><p><em>CloudWatch Logs Insights</em> is a fully managed log analytics service provided by AWS. It allows you to interactively search, analyze, and visualize log data from AWS resources and applications stored in CloudWatch Logs. CloudWatch Logs Insights provides a powerful query language and interactive query editor to help you gain insights into your log data quickly and efficiently. CloudWatch automatically associates following fields with the log event.</p><ul><li><em>@timestamp</em>: the time at which the event was added to CloudWatch</li><li><em>@message</em>: the raw message for log event</li><li><em>@logStream</em>: the log stream name</li><li><em>@log</em>: the log group name</li></ul><blockquote><strong>CloudWatch Log Insights Examples</strong></blockquote><ul><li>Filter first 100 timestamp and message attributes of log entries sorted in descending order</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Trkr9Gaa1BNNhX9ynk_VfA.png" /></figure><p><strong>Query</strong>: fields <em>@timestamp</em>, <em>@message</em></p><p>| sort <em>@timestamp</em> desc</p><p>| limit 100</p><ul><li>Filter first 100 timestamp, message and coldStart attributes of log entries sorted in ascending order</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aGO_yY0pAytmQZR_lAEokw.png" /></figure><p><strong>Query</strong>: fields <em>@timestamp</em>, message, coldStart</p><p>| filter !isempty(message)</p><p>| sort <em>@timestamp</em> asc</p><p>| limit 10</p><ul><li>Group first 100 coldStart attributes of log entries by log level</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zn9fXkzbid0iLZPH7toqrQ.png" /></figure><p><strong>Query</strong>: stats count(level) by coldStart</p><p>| filter !isempty(coldStart)</p><p>| limit 100</p><ul><li>Aggregate number of lambda invocations per 5 second</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yuI0rURTIBSpfNbH1S_U5g.png" /></figure><p><strong>Query</strong>: stats count(message) as num_of_invocations by bin(5s)</p><p>| filter message like ‘received’</p><p>| limit 100</p><ul><li>Display coldStart time values of lambda function</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IzEXuq1leK6UwZ8bJkuafA.png" /></figure><p><strong>Query</strong>: filter <em>@message</em> like ‘Init Duration’</p><p>| parse <em>@message</em> “Init Duration: * ms” as coldStartTime</p><p>| display coldStartTime</p><p>| limit 100</p><ul><li>Show timing and memory information of lambda function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ySKj-PE3HOF04ayNfDD1Kw.png" /></figure><p><strong>Query </strong>: filter @type = ‘REPORT’</p><p>| fields @duration, @billedDuration, (@memorySize / 1000 / 1000) as configuredMemoryMB, (@maxMemoryUsed / 1000 / 1000) as usedMemoryMB,</p><p>(configuredMemoryMB — usedMemoryMB) as overProvisionedMemoryMB,@initDuration as coldStartTime</p><ul><li>Show first 10 longest coldStart time ordered in descending order</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7tFfaIRVM6AAgKlL0ShNSQ.png" /></figure><p><strong>Query</strong>: filter @type = ‘REPORT’</p><p>| fields @initDuration</p><p>| filter ispresent(@initDuration)</p><p>| sort @initDuration desc</p><p>| limit 10</p><ul><li>Show last 20 lambda invocation errors ordered in descending order</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fOuDzy_a-usiQPEiRqfjzw.png" /></figure><p><strong>Query</strong>: fields <em>@timestamp</em>, <em>@message</em></p><p>| sort <em>@timestamp</em> desc</p><p>| filter <em>@message</em> not like ‘EXTENSION’</p><p>| filter <em>@message</em> not like ‘Lambda Insights’</p><p>| filter <em>@message</em> not like ‘DEBUG’</p><p>| filter <em>@message</em> not like ‘INFO’</p><p>| filter <em>@message</em> not like ‘REPORT’</p><p>| filter <em>@message</em> not like ‘END’</p><p>| filter <em>@message</em> not like ‘START’</p><ul><li>Show statistical duration information of lambda function based on 1 minute time slots</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QB8hLmUU92h9wtWfP2PkmA.png" /></figure><p><strong>Query</strong>: filter @type = ‘REPORT’</p><p>| stats avg(@duration), max(@duration), min(@duration), pct(@duration, 99), count(@duration) by bin(1m)</p><ul><li>Parse lambda invocation message to display input and output contents</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sIOEuhsBEJzXimiUCTFATw.png" /></figure><p><strong>Query</strong>: fields message</p><p>| filter message like ‘received text’</p><p>| parse message “received text: * response: *” as input, output</p><p>| display input, output</p><p>In this blog, we saw some examples on how to use <em>CloudWatch Logs </em>and <em>CloudWatch Log Insights</em> for filtering/searching our lambda function logs. Using CloudWatch service efficiently is so important for debugging and performance monitoring of our applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd5d1cc907fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy AWS Lambda java function having PowerTools logging utility with AWS CDK]]></title>
            <link>https://medium.com/@guraycintir/deploy-aws-lambda-java-function-having-powertools-utility-with-aws-cdk-1e136eee07df?source=rss-212cba9beec7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e136eee07df</guid>
            <category><![CDATA[cloudwatch]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[cloudformation]]></category>
            <dc:creator><![CDATA[guraycintir]]></dc:creator>
            <pubDate>Wed, 28 Feb 2024 17:33:19 GMT</pubDate>
            <atom:updated>2024-03-12T10:41:03.214Z</atom:updated>
            <content:encoded><![CDATA[<p>Nowadays, serverless architecture is gaining importance day by day due to it’s several advantegeous features such as cost-effectiveness, scalability, etc. Managing cloud infrastructure efficiently is also hot topic in today’s software engineering world. AWS provides Lambda service to build applications based on serverless architecture. AWS also provides AWS Cloud Development Kit (CDK) software development framework to define cloud infrastructure in code. CDK allows developers to use familiar programming languages with CDK toolkit. In this post we will learn</p><ul><li>how to create AWS lambda function java project structure with maven</li><li>how to use Powertools for AWS Lambda Java for logging</li><li>how to implement simple business logic in lambda function</li><li>how to write unit test with Junit to verify lambda business logic</li><li>how to create AWS CDK project structure</li><li>how to deploy CDK application to AWS environment</li><li>how to invoke lambda function with aws cli command</li><li>how to remove CDK application on AWS environment</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*jSa_3qVnV263__CxgZs6CA.png" /></figure><blockquote><strong>AWS Lambda function Java project structure</strong></blockquote><p>Our project structure is based on<strong><em> maven quickstart archetype</em></strong> and we use following maven command to create project structure.</p><pre>mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DgroupId=com.awscloudprojects -DartifactId=input-text-reverser-lambda -DinteractiveMode=false</pre><p>We need to add <strong><em>aws-lambda-java-core</em></strong> maven dependency in pom.xml file.</p><pre>&lt;dependency&gt;<br>      &lt;groupId&gt;com.amazonaws&lt;/groupId&gt;<br>      &lt;artifactId&gt;aws-lambda-java-core&lt;/artifactId&gt;<br>      &lt;version&gt;1.2.3&lt;/version&gt;<br>&lt;/dependency&gt;</pre><blockquote><strong>Powertools for AWS Lambda Java</strong></blockquote><p>Powertools for AWS Lambda Java is a set of utility libraries provided by AWS to simplify development of lambda functions using Java. It provides several utilities in the scope of logging, tracing, metrics, etc. We use it for <strong><em>logging </em></strong>in our lambda function.</p><p>As powertools uses aspect oriented programming for annotation processing, we need to add <strong><em>aspectjrt </em></strong>dependency along with <strong><em>powertools-logging</em></strong> dependency in pom.xml file.</p><pre>&lt;dependency&gt;<br>      &lt;groupId&gt;software.amazon.lambda&lt;/groupId&gt;<br>      &lt;artifactId&gt;powertools-logging&lt;/artifactId&gt;<br>      &lt;version&gt;1.18.0&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>      &lt;groupId&gt;org.aspectj&lt;/groupId&gt;<br>      &lt;artifactId&gt;aspectjrt&lt;/artifactId&gt;<br>      &lt;version&gt;1.9.20.1&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>We also need to add <strong><em>log4j2.xml</em></strong> file under <strong><em>src/main/resources</em></strong> folder to configure logging appenders and logging levels.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;Configuration&gt;<br>    &lt;Appenders&gt;<br>        &lt;Console name=&quot;JsonAppender&quot; target=&quot;SYSTEM_OUT&quot;&gt;<br>            &lt;JsonTemplateLayout eventTemplateUri=&quot;classpath:LambdaJsonLayout.json&quot; /&gt;<br>        &lt;/Console&gt;<br>    &lt;/Appenders&gt;<br>    &lt;Loggers&gt;<br>        &lt;Logger name=&quot;JsonLogger&quot; level=&quot;INFO&quot; additivity=&quot;false&quot;&gt;<br>            &lt;AppenderRef ref=&quot;JsonAppender&quot;/&gt;<br>        &lt;/Logger&gt;<br>        &lt;Root level=&quot;INFO&quot;&gt;<br>            &lt;AppenderRef ref=&quot;JsonAppender&quot;/&gt;<br>        &lt;/Root&gt;<br>    &lt;/Loggers&gt;<br>&lt;/Configuration&gt;</pre><blockquote><strong>AWS Lambda java function implementation</strong></blockquote><p>As a business logic, we implement a simple function which takes a string input parameter and returns reverse format of it.</p><p><strong><em>RequestHandler&lt;I,O&gt;</em></strong> is an interface which Lambda functions need to implement to receive input(I) and to return output(O). First, we implement this interface via <strong><em>Map&lt;String, Object&gt;, String</em></strong>, then we implement our business logic inside overridden method <strong><em>handleRequest.</em></strong></p><p>For logging we use <strong><em>@Logging</em></strong> annotation, provided by Powertools library, with logEvent=true and clearState=true parameters. l<strong><em>ogEvent=tru</em></strong>e is used to log input event content and <strong><em>clearState=true</em></strong> is used to clear logger state/context between lambda invocations without adding custom code.</p><pre>package com.awscloudprojects.lambda;<br><br>import com.amazonaws.services.lambda.runtime.Context;<br>import com.amazonaws.services.lambda.runtime.RequestHandler;<br>import java.util.Map;<br>import java.util.Objects;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br>import software.amazon.lambda.powertools.logging.Logging;<br><br>public class InputTextReverserLambda implements RequestHandler&lt;Map&lt;String, Object&gt;, String&gt; {<br><br>    private static final Logger logger = LoggerFactory.getLogger(InputTextReverserLambda.class);<br><br>    @Override<br>    @Logging(logEvent = true, clearState = true)<br>    public String handleRequest(Map&lt;String, Object&gt; input, Context context) {<br>        String response;<br>        try {<br>            if (Objects.isNull(input)) {<br>                return &quot;Input event is null&quot;;<br>            }<br>            if (Objects.isNull(input.get(&quot;text&quot;))) {<br>                return &quot;Input text is null&quot;;<br>            }<br>            String inputText = (String) input.get(&quot;text&quot;);<br>            response = new StringBuilder(inputText).reverse().toString();<br>            logger.info(&quot;received text: {} response: {}&quot;, inputText, response);<br><br>        } catch (Exception e) {<br>            logger.error(e.getMessage());<br>            response = e.getMessage();<br>        }<br>        return response;<br>    }<br>}<br></pre><blockquote><strong>Junit unit test implementation</strong></blockquote><p>Junit is widely used open-source testing framework for Java to write and run unit tests. We need to add <strong><em>junit </em></strong>maven dependency in pom.xml file.</p><pre>&lt;dependency&gt;<br>      &lt;groupId&gt;junit&lt;/groupId&gt;<br>      &lt;artifactId&gt;junit&lt;/artifactId&gt;<br>      &lt;version&gt;4.13.2&lt;/version&gt;<br>      &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>Our lambda function takes <strong><em>Context </em></strong>object as input parameter in handleRequest method, we need to give a Context object as mock. To do that, we create TestContext class which implements Context interface.</p><pre>package com.awscloudprojects;<br><br>import com.amazonaws.services.lambda.runtime.ClientContext;<br>import com.amazonaws.services.lambda.runtime.CognitoIdentity;<br>import com.amazonaws.services.lambda.runtime.Context;<br>import com.amazonaws.services.lambda.runtime.LambdaLogger;<br><br>public class TestContext implements Context {<br>    public TestContext() {}<br>    public String getAwsRequestId(){<br>        return new String(&quot;00054321-xmpl-0000-0000-160484189f99&quot;);<br>    }<br>    public String getLogGroupName(){<br>        return new String(&quot;/aws/lambda/input-text-reverser-function&quot;);<br>    }<br>    public String getLogStreamName(){<br>        return new String(&quot;2020/02/26/[$LATEST]704f8dxmpla04097b9134246b8438f1a&quot;);<br>    }<br>    public String getFunctionName(){<br>        return new String(&quot;input-text-reverser-function&quot;);<br>    }<br>    public String getFunctionVersion(){<br>        return new String(&quot;$LATEST&quot;);<br>    }<br>    public String getInvokedFunctionArn(){<br>        return new String(&quot;arn:aws:lambda:us-east-1:000000000000:function:input-text-reverser-function&quot;);<br>    }<br>    public CognitoIdentity getIdentity(){<br>        return null;<br>    }<br>    public ClientContext getClientContext(){<br>        return null;<br>    }<br>    public int getRemainingTimeInMillis(){<br>        return 300000;<br>    }<br>    public int getMemoryLimitInMB(){<br>        return 512;<br>    }<br>    public LambdaLogger getLogger(){<br>        return new TestLogger();<br>    }<br>}</pre><p>We also need to implement <strong><em>LambdaLogger </em></strong>interface with a class and use it in TestContext class.</p><pre>package com.awscloudprojects;<br><br>import com.amazonaws.services.lambda.runtime.LambdaLogger;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br><br>public class TestLogger implements LambdaLogger {<br>    private static final Logger logger = LoggerFactory.getLogger(TestLogger.class);<br><br>    @Override<br>    public void log(String s) {<br>    }<br><br>    @Override<br>    public void log(byte[] bytes) {<br>    }<br>}</pre><p>After setup necessary dependencies, we can write a simple unit test to verify that our lambda function returns reversed format of input string.</p><pre>    @Test<br>    public void shouldReturnReversedTextWhenInputTextValid() {<br>        Map&lt;String, Object&gt; input = new HashMap&lt;&gt;();<br>        input.put(&quot;text&quot;, &quot;hello-world&quot;);<br>        Context context = new TestContext();<br>        InputTextReverserLambda inputTextReverserLambda = new InputTextReverserLambda();<br>        String response = inputTextReverserLambda.handleRequest(input, context);<br>        assertNotNull(response);<br>        assertEquals(&quot;dlrow-olleh&quot;, response);<br>    }</pre><blockquote><strong>AWS CDK project structure</strong></blockquote><p>We prefer Java programming language in our AWS CDK project and we create project structure as maven project with following cdk command.</p><pre>cdk init app --language=java</pre><p>Stack,construct and Application are foundational blocks to understand carefully in CDK application. Basically, constructs are used to form resources in cloud infrastructure while stacks define deployment units and used to manage lifecycle of deployments to cloud environments. Application is the root of a CDK project.</p><p>We create <strong><em>LambdaStack </em></strong>class extending <strong><em>Stack</em></strong> class. In LambdaStack class, we first create <strong><em>IAM role</em></strong> which is needed by lambda function to send log entries to <strong><em>CloudWatch </em></strong>log stream. Then, we create our lambda function by setting it’s properties such as runtime, handler, timeout value, memory size, etc.</p><pre>package com.awscloudprojects;<br><br>import software.amazon.awscdk.Duration;<br>import software.amazon.awscdk.RemovalPolicy;<br>import software.amazon.awscdk.services.iam.ManagedPolicy;<br>import software.amazon.awscdk.services.iam.Role;<br>import software.amazon.awscdk.services.iam.ServicePrincipal;<br>import software.amazon.awscdk.services.lambda.Code;<br>import software.amazon.awscdk.services.lambda.Function;<br>import software.amazon.awscdk.services.lambda.Runtime;<br>import software.amazon.awscdk.services.logs.LogGroup;<br>import software.amazon.awscdk.services.logs.RetentionDays;<br>import software.constructs.Construct;<br>import software.amazon.awscdk.Stack;<br>import software.amazon.awscdk.StackProps;<br><br>public class LambdaStack extends Stack {<br>    public LambdaStack(final Construct scope, final String id, final StackProps props) {<br>        super(scope, id, props);<br><br>        Role executionRole = Role.Builder.create(this, id + &quot;-InputTextReverserLambdaRole&quot;)<br>                .assumedBy(new ServicePrincipal(&quot;lambda.amazonaws.com&quot;))<br>                .roleName(id + &quot;-InputTextReverserLambdaRole&quot;)<br>                .build();<br>        executionRole.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(&quot;service-role/AWSLambdaBasicExecutionRole&quot;));<br><br>        String functionName = id + &quot;-InputTextReverserLambda&quot;;<br>        Function.Builder.create(this, functionName)<br>                .runtime(Runtime.JAVA_21)<br>                .code(Code.fromAsset(&quot;../function/input-text-reverser-lambda/target/input-text-reverser-lambda.jar&quot;))<br>                .handler(&quot;com.awscloudprojects.lambda.InputTextReverserLambda::handleRequest&quot;)<br>                .functionName(functionName)<br>                .role(executionRole)<br>                .timeout(Duration.seconds(30L))<br>                .memorySize(512)<br>                .logGroup(LogGroup.Builder.create(this, functionName + &quot;-logGroup&quot;)<br>                        .logGroupName(&quot;/aws/lambda/&quot; + functionName)<br>                        .retention(RetentionDays.ONE_DAY)<br>                        .removalPolicy(RemovalPolicy.DESTROY)<br>                        .build())<br>                .build();<br>    }<br>}</pre><p>When we delete our stack from cloud environment, we also want CloudWatch log stream to be deleted or log entries in log stream to be deleted after a period of time in order to prevent unnecessary cost. To achieve this, we set <strong><em>RetentionDays.ONE_DAY</em></strong> as retention and <strong><em>RemovalPolicy.DESTROY</em></strong> as removal policy.</p><blockquote><strong>CDK application deployment to AWS environment</strong></blockquote><p>In order to deploy our lambda function first we need to package our lambda function project with maven command and to be sure that <strong><em>input-text-reverser-lambda.jar</em></strong> artifact is created under target folder in project folder.</p><pre>mvn clean package</pre><p>Then, we package our CDK project structure with maven command.</p><pre>mvn clean package</pre><p>When AWS CDK project is synthesized, it generates a <strong><em>CloudFormation </em></strong>template and CDK uses that template to create resources on AWS environment. So, we synthesize template with following cdk command. This commands synthesizes our java code and generates Cloudformation template under <strong><em>cdk.out</em></strong> folder in project directory.</p><pre>cdk synth</pre><p>Now, we bootstrap our AWS environment. Bootstrapping means CDK prepares AWS environment for deployment of CDK application. It involves creating and configuring resources that are necessary for CDK to manage our infrastructure. Bootstrapping process is only done once then we can deploy our CDK application without that process.</p><pre>cdk bootstrap --profile &lt;aws-cli-profile-name&gt;<br>cdk deploy --profile &lt;aws-cli-profile-name&gt;</pre><p>Once we deploy our CDK application to AWS environment, we can see our LambdaStack is created successfully on CloudFormation Management console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7QP-nRdKndtw_lW1LWwjkQ.png" /></figure><p>We can see that our lambda function is created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1mBN5NS3ZkNiP4wCHaduIA.png" /></figure><blockquote><strong>Lambda function invocation with aws cli command</strong></blockquote><p>Now, we can invoke our lambda function with aws cli command. We execute cli command under <strong><em>src/test/resources/data</em></strong> folder as there is <strong><em>payload.json</em></strong> file for input.</p><pre>aws lambda invoke --function-name LambdaStack-InputTextReverserLambda --payload file://payload.json output.txt --cli-binary-format raw-in-base64-out --profile &lt;aws-cli-profile-name&gt;</pre><p>After executing the aws cli command, we receive response with 200 StatusCode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*ODrVGlbua7fAD3SkFyFFTg.png" /></figure><p><strong><em>output.txt</em></strong> file contains invocation result of lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/176/1*WXuVEyJCZHyMrQUUmxTABA.png" /></figure><p>We can also see that our lambda function send log entries to CloudWatch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMGvhmJYteI1_gg9xMP5ZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uDc9deI9axrZYVbonN8-rA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rKJcXylPWoR9vGah_1ZIsw.png" /></figure><p>As we use <strong><em>JsonTemplateLayout </em></strong>as log appender in<strong><em> log4j2.xml</em></strong>, logs are written in <strong><em>json</em></strong> format which is more user-friendly and more efficient for searching operations.</p><blockquote><strong>Remove CDK applicationon AWS environment</strong></blockquote><p>Now, we delete our LambdaStack CDK application from AWS cloud environment with following CDK command.</p><pre>cdk destroy --profile &lt;aws-cli-profile-name&gt;</pre><p>Finally, our java lambda function is ready. We deploy it to AWS environment by using AWS CDK (Infrastructure As Code tool) and we use Powertools utility library for logging. You can download project source code from my <a href="https://github.com/gcintir/aws-cdk-lambda-function-example">github repository</a>. If this article helped you, feel free to follow me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e136eee07df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fundamentals of Docker]]></title>
            <link>https://medium.com/@guraycintir/fundamentals-of-docker-957ae0fca1b5?source=rss-212cba9beec7------2</link>
            <guid isPermaLink="false">https://medium.com/p/957ae0fca1b5</guid>
            <dc:creator><![CDATA[guraycintir]]></dc:creator>
            <pubDate>Thu, 25 May 2023 21:43:02 GMT</pubDate>
            <atom:updated>2023-05-25T21:43:41.550Z</atom:updated>
            <content:encoded><![CDATA[<p>Docker is a tool that allows us to automate deployment of sofware applications inside containers running on a host machine. Docker provides an abstraction layer that seperates the application layer from infrastructure layer. Users are able to package their applications with all their dependencies into a standardized unit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*yM-hh34Y4SnWgQFF1kWoqg.png" /><figcaption>Docker Architecture</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7diMuNYFX08rIWgStfOy6A.png" /><figcaption>Docker vs VM</figcaption></figure><ol><li><strong>Basic Docker terms</strong></li></ol><ul><li>Dockerfile : simple text file that contains list of commands which docker client uses to build Docker image. It automates creation of docker image.</li><li>Docker image : templates for docker containers. It is source code for a docker container.</li><li>Docker container : copy of docker images. It is isolated environment that runs on host machine. Multiple containers could be created from same docker image.</li><li>Docker engine : it is core engine of docker. dockerd is server. docker client and server can run on same host and on different hosts. Clients can communicate with dockerd with rest api calls.</li><li>Docker registry : it is a repository that stores docker images. It could be public or private.</li></ul><p><strong>2. Basic Docker commands</strong></p><ul><li>docker info : shows information about underlying docker engine.</li></ul><pre>docker info<br><br>Server:<br> Containers: 2<br>  Running: 0<br>  Paused: 0<br>  Stopped: 2<br> Images: 1<br> Server Version: 23.0.5<br>.......</pre><ul><li>docker pull : downloads docker image from docker registry.</li></ul><pre>docker pull ubuntu<br><br>Using default tag: latest<br>latest: Pulling from library/ubuntu<br>dbf6a9befcde: Pull complete<br>Digest: sha256:dfd64a3b4296d8c9b62aa3309984f8620b98d87e47492599ee20739e8eb54fbf<br>Status: Downloaded newer image for ubuntu:latest<br>docker.io/library/ubuntu:latest</pre><ul><li>docker images : shows docker images downloaded locally.</li></ul><pre>docker images<br><br>REPOSITORY   TAG       IMAGE ID       CREATED       SIZE<br>postgres     latest    bf700010ce28   3 weeks ago   379MB<br>ubuntu       latest    3b418d7b466a   4 weeks ago   77.8MB</pre><ul><li>docker run : runs a container from a docker image.</li></ul><pre>docker run ubuntu</pre><ul><li>docker ps : shows running containers.</li></ul><pre>docker ps<br><br>CONTAINER ID   IMAGE      COMMAND                  CREATED       STATUS         PORTS                    NAMES<br>d8977c6f1260   postgres   &quot;docker-entrypoint.s…&quot;   3 weeks ago   Up 3 minutes   0.0.0.0:5432-&gt;5432/tcp   postgresqldb</pre><ul><li>docker start : runs container previously created.</li></ul><pre>docker run postgresql<br><br>postgresqldb</pre><ul><li>docker stop : stops a running container.</li></ul><pre>docker stop postgresql<br><br>postgresqldb</pre><ul><li>docker stats : shows resource usages of containers.</li></ul><pre>docker stats<br><br>CONTAINER ID   NAME           CPU %     MEM USAGE / LIMIT    MEM %     NET I/O       BLOCK I/O   PIDS<br>d8977c6f1260   postgresqldb   0.01%     68.5MiB / 3.734GiB   1.79%     1.46kB / 0B   0B / 0B     6</pre><ul><li>docker image rm / docker rmi: remove one or more containers.</li></ul><pre>docker rm 123a889b196a<br><br>123a889b196a</pre><ul><li>docker rmi : remove docker image locally.</li></ul><pre>docker rmi hello-world<br><br>Untagged: hello-world:latest<br>Untagged: hello-world@sha256:fc6cf906cbfa013e80938cdf0bb199fbdbb86d6e3e013783e5a766f50f5dbce0<br>Deleted: sha256:9c7a54a9a43cca047013b82af109fe963fde787f63f9e016fdc3384500c2823d<br>Deleted: sha256:01bb4fce3eb1b56b05adf99504dafd31907a5aadac736e36b27595c8b92f07f1</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=957ae0fca1b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>