<?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 Jake Bazin on Medium]]></title>
        <description><![CDATA[Stories by Jake Bazin on Medium]]></description>
        <link>https://medium.com/@jake.bazin?source=rss-d00cc608d883------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AkjxpH_Xh5XcAP1oXsD9XA@2x.jpeg</url>
            <title>Stories by Jake Bazin on Medium</title>
            <link>https://medium.com/@jake.bazin?source=rss-d00cc608d883------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 02:05:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jake.bazin/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[Building Flexible AI Model Training Pipelines on AWS]]></title>
            <link>https://medium.com/@jake.bazin/building-flexible-ai-model-training-pipelines-on-aws-b7eed6281a94?source=rss-d00cc608d883------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7eed6281a94</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[amazon-bedrock]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-step-functions]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Jake Bazin]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 12:40:56 GMT</pubDate>
            <atom:updated>2025-11-12T12:41:39.425Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HT9In0jAyJ36e0DRwHLmqw.png" /></figure><p>Training AI models isn’t just about feeding data into a large language model (LLM) — it’s about designing a reliable, reusable process that ensures your model learns from high-quality, contextually relevant information.</p><p>At a high level, that means:</p><ul><li>✏️ Gathering domain-specific non-AI-generated data</li><li>🧼 Cleaning and validating it</li><li>🛠️ Structuring it into prompts</li><li>🧳 Storing it for reuse</li><li>📚 Training (or distilling) models efficiently</li></ul><p>Our use case involves training a model on AWS Bedrock, for generating headlines across a set of publications that all have different requirements in terms of writing style, SEO and format.</p><p>In this post, I’ll talk about an example architecture on AWS that meets these requirements.</p><p>The full code repository that goes with this article is available on my Github.</p><p><a href="https://github.com/jakebaz/bedrock-training-pipeline">GitHub - jakebaz/bedrock-training-pipeline: A Step Functions workflow to orchestrate model training and data processing with ECS</a></p><h3>Step Functions + ECS: The Orchestration Layer</h3><p>Our pipeline utilises <strong>AWS Step Functions</strong>, which coordinates the full training workflow. Step Functions gives us flexible invocation options — we can trigger training on a schedule, via an API, or manually when new data becomes available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*GZzGopJgQ-pqnj1TtgWA0w.png" /><figcaption>Step Functions Pipeline</figcaption></figure><p>Each training run spins up an <strong>ECS task</strong>, which performs the core processing.</p><p>This task uses a <em>look-back period</em> (for example, the past 30 days) to gather human-authored examples from a data source — in our case, <strong>Amazon Athena</strong>. However, this could equally be <strong>DynamoDB</strong>, <strong>DocumentDB</strong>, or even <strong>JSON-formatted data in S3</strong>. These parameters are defined at the beginning of the workflow.</p><blockquote><em>🧠 Tip: When building LLM training pipelines, it’s crucial that your data comes from </em><strong><em>human-authored sources</em></strong><em>. AI-generated content in your training data can cause quality degradation and style drift over time.</em></blockquote><h4>Why ECS?</h4><p>We chose to run the data processing inside <strong>Amazon ECS</strong> because it needs to be able to query and transform large volumes of data from Athena. which can exceed <strong>AWS Lambda’s 15-minute execution limit</strong>.</p><p>ECS also gives us more control over compute resources and memory, making it better suited for heavier workloads while still providing some of the benefits of serverless through <strong>AWS Fargate</strong> (serverless containers).</p><p>Since the actual training step happens downstream, <strong>AWS Lambda</strong> can be a simpler and more cost-effective option for smaller or medium-sized datasets, or for triggering follow-up steps in event-driven workflows.</p><p>If you need a managed environment for iterative development and scaling ML workloads, <strong>SageMaker Processing Jobs</strong> or <strong>Glue Jobs</strong> could also be good fits depending on your stack and data volume.</p><p>See also: 👇</p><p><a href="https://medium.com/@jake.bazin/lambda-vs-fargate-in-modern-architectures-exploring-the-trade-offs-224946645865">Lambda vs Fargate in Modern Architectures: Exploring the Trade-Offs</a></p><h3>Cleaning and Validating Data</h3><p>Real-world data is rarely clean. Before it can be used for training, it must go through a series of validation steps.</p><p>In our case, the ECS task performs:</p><ul><li><strong>Null value removal</strong> — ensures only complete records are kept</li><li><strong>HTML stripping</strong> — removes markup from stored text</li><li><strong>Duplicate filtering</strong> — prevents over-representation of certain patterns</li><li><strong>Quote validation</strong> — checks accuracy of quotes against the original</li></ul><pre>// Step 2: Clean and validate data<br>console.log(&quot;Step 2: Cleaning and validating data...&quot;);<br>const dataCleaner = new DataCleaner();<br>const cleanedExamples = dataCleaner.cleanExamples(rawExamples);<br>console.log(`After cleaning: ${cleanedExamples.length} examples`);<br><br>if (cleanedExamples.length &lt; minPromptCount) {<br>  throw new Error(<br>    `Insufficient examples after cleaning: ${cleanedExamples.length} found, ${minPromptCount} required`<br>  );<br>}</pre><p>After cleaning, each example is transformed into a <strong>structured prompt</strong> suitable for model training. In the example below we include the prompt, completion and some metadata.</p><blockquote>✏️ <em>Note:</em> The completion refers to the headline used for the article — i.e. the target output we want the model to generate.</blockquote><pre>{<br>  &quot;prompt&quot;: &quot;Generate a headline for the following article:\n\nArticle content:\nIn a groundbreaking development that could reshape the technology landscape, researchers at leading universities have announced a major breakthrough in artificial intelligence. The new system demonstrates unprecedented capabilities in understanding context and generating human-like responses. This advancement comes after years of collaborative research between computer scientists and cognitive psychologists, who have been working to bridge the gap between machine learning and human cognition. The implications for industries ranging from healthcare to education are profound, with early applications already showing promising results in pilot programs across the country...\n\nPublication: tech-news\nStyle requirements: Editorial quality, SEO-optimized, engaging&quot;,<br>  &quot;completion&quot;: &quot;AI Breakthrough: Researchers Announce Major Advance in Machine Learning&quot;,<br>  &quot;metadata&quot;: {<br>    &quot;articleId&quot;: &quot;article-12345&quot;,<br>    &quot;publication&quot;: &quot;1&quot;,<br>    &quot;publishedDate&quot;: &quot;2024-01-15&quot;,<br>    &quot;exampleIndex&quot;: 0<br>  }<br>}</pre><p>The pipeline ensures that we have at least a minimum number of examples (e.g. <strong>100 prompts</strong>) before proceeding. If the threshold isn’t met, the Step Function fails, triggering an alert via an <strong>SNS Topic</strong>.</p><h3>Storing and Reusing Training Data</h3><p>Once the dataset is prepared, it’s stored in <strong>Amazon S3</strong> in JSONL format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*Vak4RcUvjaXLm844cQod4A.png" /><figcaption>ECS processes data from Athenaand stores in S3 before sending to Bedrock</figcaption></figure><p>This step provides multiple benefits:</p><ul><li><strong>Reusability</strong> — You can retrain or fine-tune without re-processing data</li><li><strong>Resilience</strong> — Easily recover if a training job fails</li><li><strong>Traceability</strong> — Preserve dataset versions for auditing or future comparison</li></ul><p>Having your data versioned and accessible in S3 also makes it simple to integrate with downstream ML processes such as fine-tuning, evaluation, or deployment pipelines.</p><h3>Model Distillation with Amazon Bedrock</h3><p>For efficiency, we use <strong>model distillation</strong> via <strong>Amazon Bedrock</strong>.</p><pre>// data processing done above and stored in `result` variable...<br>try {<br>   const jobArn = await bedrockService.createModelCustomizationJob(<br>      config,<br>      result,<br>      bedrockConfig<br>    );<br>    console.log(`Bedrock training job started: ${jobArn}`);<br>  } catch (error) {<br>    console.error(<br>      &quot;Failed to start Bedrock training job (dataset is saved in S3):&quot;,<br>      error<br>    );<br>    throw error;<br>  }</pre><p>Distillation takes a powerful <em>“teacher”</em> model and trains a smaller <em>“student”</em> model to mimic its behaviour. This delivers:</p><ul><li>🚀 <strong>Faster inference</strong> — critical for real-time applications</li><li>💰 <strong>Lower cost per request</strong> — smaller models consume less compute</li><li>⚙️ <strong>Task specialisation</strong> — fine-tune on your domain while leveraging a foundation model’s power</li></ul><p>We send our 100+ prompts to Bedrock via the SDK to train the models, from the ECS Task. Information about the training job is passed on to the next step in the pipeline, allowing us to monitor its progress downstream.</p><h3>Polling Bedrock Until Model Training Completes</h3><p>Once the ECS task has finished preparing the dataset and initiating a <strong>model customisation job</strong> in Amazon Bedrock, the pipeline moves into a monitoring phase to track the training progress.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*jhTi4JR89BKWDaeU6pfUUQ.png" /><figcaption>Step Functions uses a wait state to poll Bedrock</figcaption></figure><p>Bedrock model training can take anywhere from a few minutes to several hours depending on the dataset size and foundation model, it’s important not to assume it completes instantly. Instead, the workflow <strong>polls Bedrock at regular intervals</strong> until the job reaches a terminal state (either COMPLETED or FAILED).</p><p>This is handled entirely within <strong>AWS Step Functions</strong> using a combination of built-in states:</p><ol><li><strong>Wait state</strong> — pauses the workflow for a defined duration (e.g., 5 minutes).</li><li><strong>CallAwsService</strong> — invokes bedrock:getModelCustomizationJob to check the latest job status.</li><li><strong>Choice state</strong> — evaluates the returned status to decide whether to continue waiting, mark success, or handle failure.</li></ol><pre>const waitForTraining = new stepfunctions.Wait(this, &quot;WaitForTraining&quot;, {<br>  // Adjust polling duration if needed<br>  time: stepfunctions.WaitTime.duration(cdk.Duration.minutes(5)),<br>});<br><br>const checkTrainingStatus = new tasks.CallAwsService(this, &quot;CheckTrainingStatus&quot;, {<br>  service: &quot;bedrock&quot;,<br>  action: &quot;getModelCustomizationJob&quot;,<br>  parameters: {<br>    JobIdentifier: stepfunctions.JsonPath.stringAt(&quot;$.taskExecution.BedrockJobArn&quot;),<br>  },<br>  iamResources: [&quot;*&quot;], // Allow Bedrock access (should be scoped further)<br>  resultPath: &quot;$.trainingStatus&quot;,<br>});<br><br>const handleTrainingCompletion = new stepfunctions.Choice(this, &quot;HandleTrainingCompletion&quot;)<br>  .when(<br>    stepfunctions.Condition.stringEquals(&quot;$.trainingStatus.status&quot;, &quot;COMPLETED&quot;),<br>    new stepfunctions.Succeed(this, &quot;TrainingSucceeded&quot;)<br>  )<br>  .when(<br>    stepfunctions.Condition.stringEquals(&quot;$.trainingStatus.status&quot;, &quot;FAILED&quot;),<br>    new stepfunctions.Fail(this, &quot;TrainingFailed&quot;)<br>  )<br>  .otherwise(waitForTraining);</pre><p>This pattern creates a loop where Step Functions waits, checks the Bedrock job status, and repeats until completion or failure.</p><p>If the job fails, a <strong>failure notification</strong> is sent through <strong>Amazon SNS</strong>, alerting your team immediately. This makes the pipeline fault-tolerant and fully automated — you don’t have to manually check the Bedrock console or intervene mid-run.</p><blockquote>💡 <strong>Tip:</strong> If you have a good idea of how long your Bedrock training jobs usually take, consider adding a retry or timeout mechanism to your polling loop. This helps prevent your Step Functions workflow from running indefinitely if something goes wrong — for example, if the Bedrock job gets stuck in an unexpected state. You can do this by passing the number of retries between each state, and then exiting or failing gracefully once a defined threshold is reached.</blockquote><h3>Conclusion</h3><p>Leveraging AWS Step Functions with ECS, you can build a <strong>modular and scalable training pipeline</strong> that works for virtually any LLM use case.</p><p>This architecture gives you the ability to:</p><p>✅ Train models with high-quality, human-authored examples<br>✅ Clean, validate, and structure data programmatically<br>✅ Persist and reuse datasets for future fine-tuning<br>✅ Distil efficient models optimised for your needs</p><p>In this example, the goal was to generate editorial-quality headlines — but the same approach can be used to train AI models for <strong>summarisation, categorisation, personalisation, or question-answering</strong> across industries.</p><p>With the right orchestration and data hygiene, AWS gives you all the building blocks to make custom AI model training both reliable and cost-effective.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7eed6281a94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lambda vs Fargate in Modern Architectures: Exploring the Trade-Offs]]></title>
            <link>https://medium.com/@jake.bazin/lambda-vs-fargate-in-modern-architectures-exploring-the-trade-offs-224946645865?source=rss-d00cc608d883------2</link>
            <guid isPermaLink="false">https://medium.com/p/224946645865</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[ecs-fargate]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless-architecture]]></category>
            <dc:creator><![CDATA[Jake Bazin]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 10:24:29 GMT</pubDate>
            <atom:updated>2025-01-16T10:28:10.647Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*reS_sYOMvCRLNy4aVl06JQ.png" /></figure><p>I must confess, when I recently started my new role, I came in with a strong inclination towards Serverless architecture, ready to apply my experience with AWS Lambda, AppSync, DynamoDB, and EventBridge etc. I’ll admit, I didn’t fully understand their architecture or the decisions that shaped it.</p><p>As someone whose concept of “Serverless” revolved entirely around Lambda-based event-driven architectures, I initially saw Fargate as a halfway house. As I’ve delved deeper, I’ve come to understand why Fargate is the right fit for our workloads — and why Serverless doesn’t always mean Lambda functions.</p><h3>My Serverless Experience: Lambda, AppSync, and Event-Driven Architectures</h3><p>In my previous role, Serverless architecture was my bread and butter. AWS Lambda, with its on-demand scalability and cost efficiency, was perfect for our event-driven workloads. Paired with services like AppSync for GraphQL APIs, DynamoDB for fast and highly available data storage, and EventBridge for connecting distributed systems, we created architectures that were nimble, scalable, and required little operational overhead.</p><p>For workloads with unpredictable traffic or short-lived tasks, Serverless shines. Developers can focus entirely on business logic while AWS manages the infrastructure. However, Serverless isn’t without challenges. Cold starts, execution time limits, and limited control over runtime environments can make Lambda unsuitable for certain applications.</p><p>This is where Fargate offers a compelling alternative.</p><h3>What Is Fargate and Why Use It?</h3><p>AWS Fargate is a Serverless way to run containers without worrying about the underlying infrastructure. Unlike EC2, where you manage and provision servers, Fargate abstracts away tasks like scaling, patching, and maintenance. You simply define your task or service, and AWS handles the rest.</p><p>Our use case involves running a Node.js application that doesn’t follow an event-driven or stateless microservices approach. It’s a monolithic application requiring long-lived processes and predictable performance.</p><p>While hosting this on EC2 would work — and might even be more cost-effective for long-running processes — Fargate eliminates the operational overhead of managing servers. It combines the flexibility of containerised workloads with the simplicity of Serverless infrastructure. This allows us to define our runtime environment with precision while benefiting from AWS-managed scalability and security.</p><h3>Comparing Lambda and Fargate: Key Differences in Compute</h3><h4>Execution model</h4><ul><li><strong>Lambda: </strong>Operates on a <strong>function-as-a-service (FaaS)</strong> model. Each invocation is stateless, triggered by events like HTTP requests or file uploads. No local state is maintained between executions.</li><li><strong>Fargate:</strong> Runs <strong>containerised applications</strong>, allowing you to deploy Docker images. Containers listen for HTTP requests, can maintain state during execution and support long-lived processes.</li></ul><h4>Lifecycle and Persistence</h4><ul><li><strong>Lambda: </strong>Functions are ephemeral and designed for short-lived tasks, with a maximum execution time of <strong>15 minutes</strong>. Each function is terminated after execution.</li><li><strong>Fargate:</strong> Containers can run as long as needed. Even when idle, they stay running and listen for incoming traffic.</li></ul><h4>Deployment and Configuration</h4><ul><li><strong>Lambda: </strong>You deploy individual functions, referencing code from an S3 bucket or uploading directly. AWS-supported runtimes (e.g., Node.js, Python) are preconfigured for Serverless execution. <strong>Lambda Layers</strong> allow you to share dependencies across functions.</li><li><strong>Fargate: </strong>Grants full control over the operating system and runtime via Docker images. Containers package the application code, dependencies, and any required libraries or customisations. Images are stored in registries like <strong>Amazon Elastic Container Registry (ECR)</strong> or <strong>Docker Hub</strong>.</li></ul><h4>Scaling</h4><ul><li><strong>Lambda:</strong> Instantly scales by creating isolated environments for each invocation. AWS automatically manages scaling, with a default concurrency limit of 1,000 executions (increased via support).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*B_W_psTM67vQc7w5Qr51CA.png" /><figcaption>Each invocation spins up a new instance of the Lambda function</figcaption></figure><ul><li><strong>Fargate:</strong> Scaling occurs at the container level. ECS Auto Scaling adjusts the number of running containers based on CPU or memory usage. Containers handle multiple requests concurrently, though scaling isn’t as instantaneous as Lambda.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*WR-l25cO-3F2KJ4nXaf-yw.png" /><figcaption>Containers are added based on metrics such as CPU usage or Memory</figcaption></figure><h4>Pricing</h4><ul><li><strong>Lambda: </strong>Charged based on invocations and execution time (in <strong>milliseconds</strong>). Ideal for spiky or short-lived workloads.</li><li><strong>Fargate:</strong> Charged based on allocated resources (vCPU and memory) and runtime duration. Costs are fixed regardless of utilisation.</li></ul><h3>Cost and Performance Considerations</h3><p>When running containers in AWS, it’s important to estimate your application’s traffic to make informed decisions about CPU and memory allocation. Understanding your traffic patterns can help you provision enough resource for your application.</p><p>If you’re unsure about your traffic levels, I recommend enabling <strong>auto scaling</strong> on your ECS cluster. By scaling on custom metrics, you can ensure your application remains highly available and worry about cost optimisation later.</p><p>In general, it’s best to avoid over-provisioning CPU and memory for your ECS Fargate tasks unless your workload specifically requires it. A common mistake is allocating excessive resources to a single container, only to find that these resources remain underutilised when scaling out additional containers.</p><p>A more efficient approach is to use smaller containers with right-sized resource allocations that can scale horizontally to meet demand. This ensures better utilisation of resources and can also help optimise costs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*QcFqLFP1EPMWgpOWQT2CYg.png" /><figcaption>More instances with less resource could save you money</figcaption></figure><p>In contrast, Lambda functions scale differently: each invocation typically creates a new execution environment. While these environments can be reused, cold starts can affect performance for high-traffic or latency-sensitive workloads.</p><p>Fortunately, there are many strategies that can help to reduce the impact of cold starts and optimise both performance and costs for Lambda. <a href="https://medium.com/@jake.bazin/10-tips-for-keeping-your-aws-lambda-functions-performant-f0504949659a">Check out this article</a> I wrote to see my tips on keeping Lambda functions efficient.</p><p>Cold starts are not an issue with ECS Fargate as the service is always readily available and listening for traffic.</p><h3>When to Choose Lambda/API-Based Architectures</h3><p>Lambda and API-based architectures are well-suited to the following scenarios:</p><ul><li><strong>Event-Driven Workloads:</strong> Perfect for systems that react to triggers like database changes or user interactions.</li><li><strong>Unpredictable Traffic:</strong> Automatically scales for spiky demand.</li><li><strong>Short-Lived Tasks:</strong> Pay-per-millisecond pricing suits lightweight operations.</li><li><strong>Simplified Operations: </strong>AWS manages the runtime, allowing teams to focus on development.</li></ul><h3>When to Choose Fargate</h3><p>Fargate, on the other hand, is better suited to these use cases:</p><ul><li><strong>Long-Lived Processes:</strong> Persistent workloads or continuous tasks are more cost-effective in containers.</li><li><strong>Custom Runtime Requirements:</strong> Containers provide flexibility for specific OS, libraries, or runtime needs.</li><li><strong>Consistent Performance: </strong>Predictable workloads benefit from Fargate’s controlled environment.</li><li><strong>Monolithic Applications: </strong>Traditional architectures fit well with Fargate’s straightforward hosting model.</li></ul><h3>Bridging Traditional and Serverless Architectures</h3><p>Adopting Serverless architecture incrementally is often more effective than an all-at-once migration. ECS Fargate provides an excellent starting point for organisations transitioning to Serverless while retaining elements of their traditional systems.</p><p>By running containerised applications on Fargate, you can continue using the AWS SDK to interact with other AWS services such as DynamoDB, S3, EventBridge, or SNS. This allows for hybrid architectures where event-driven patterns and Serverless components coexist with legacy systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*ENQ9c-d5qi5rMQD9IPXPaQ.png" /><figcaption>Example — Fargate interacting with Event Driven Architecture</figcaption></figure><h3>Reflections on the Transition</h3><p>Coming from a Serverless-first mindset, I initially saw ECS Fargate as a step backwards. However, I’ve grown to appreciate its value within the AWS ecosystem.</p><p>Serverless and container-based architectures aren’t mutually exclusive — it’s about choosing the right tool for the job. While Lambda excels for event-driven workloads, Fargate offers flexibility and control for applications that don’t fit the Serverless mould.</p><p>The key to resilient, scalable systems is understanding when to use each, tailoring architecture decisions to the problem at hand rather than the technology you’re most familiar with.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=224946645865" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Tips for keeping your AWS Lambda functions performant]]></title>
            <link>https://medium.com/@jake.bazin/10-tips-for-keeping-your-aws-lambda-functions-performant-f0504949659a?source=rss-d00cc608d883------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0504949659a</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Jake Bazin]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 08:50:49 GMT</pubDate>
            <atom:updated>2024-09-23T08:50:49.118Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZ2aiKYuu_AqdRsS0XrJkg.png" /><figcaption>Image generated using Amazon Bedrock</figcaption></figure><p>AWS Lambda provides a serverless compute service, running your code on demand without the hassle of managing servers. However, to maintain high performance, there are several best practices to be adopted in order to keep response times low. Let’s dive into 10 key strategies for keeping your Lambda functions fast and efficient.</p><h3><strong>1. Initialise SDK Clients Outside Handler</strong></h3><p>Initialising SDK clients, database connections, or other heavy resources outside of the handler ensures that they are re-used across multiple invocations when the execution environment is re-used.</p><p>This can drastically reduce the number of times it needs to be initialised, especially in high usage applications.</p><pre>import { DynamoDBClient, GetCommand, GetCommandOutput } from &#39;@aws-sdk/client-dynamodb&#39;;<br><br>// Initialise DynamoDB client outside handler<br>const dynamoClient = new DynamoDBClient({});<br>const TABLE_NAME = process.env.TABLE_NAME;<br><br>export const handler = async (event) =&gt; {<br>  const command = new GetCommand({<br>    TableName: TABLE_NAME,<br>    Key: { id: event.id }<br>  });<br>  const result: GetCommandOutput = await dynamoClient.send(command);<br>  return {<br>    item: result.Item,<br>    statusCode: 200<br>  }<br>};</pre><h3><strong>2. Use a Compiled Runtime (e.g Rust or Go)</strong></h3><p>For faster execution, consider using compiled languages like <strong>Rust</strong> or <strong>Go</strong>. They compile code into a binary that is executed directly, which leads to a faster startup compared to interpreted languages like Python or Node.js.</p><p>Although there is more complexity in building the code, cold start times can be drastically reduced.</p><p>Check out this article written by <a href="https://medium.com/u/d70df98d3609">Steve Morland</a>. <a href="https://medium.com/@smorland/serverless-rust-a-frugal-choice-426d66d44873">Serverless &amp; Rust: A frugal choice?</a></p><p>This post compares the execution time between the NodeJS and Rust runtimes. As you will see, Rust requires less memory and the execution time is significantly less, particularly in cold start scenarios.</p><h3><strong>3. Minimise Deployment Package Size</strong></h3><p>The larger your deployment package, the longer it takes AWS to load and initialise your function. By pruning unnecessary dependencies and files you can decrease the deployment package size.</p><pre># Only install production dependencies in Node.js<br>npm install --production</pre><p>You can use tools like <strong>Webpack</strong> or <strong>esbuild</strong> to bundle and minify your code, which reduces the overall size of your deployment package and improves Lambda cold start times.</p><p>These tools can also handle tree-shaking, a process that removes unused code from the final bundle, ensuring only the necessary code is included.</p><p>You can also use Lambda Layers to externalise shared dependencies for re-use across multiple functions. This keeps your function-specific code lightweight and further optimises deployment and initialisation times.</p><h3><strong>4. Use Provisioned Concurrency</strong></h3><p>Cold starts occur when Lambda needs to initialise a new execution environment. To avoid the performance hit during cold starts, you can use <strong>Provisioned Concurrency</strong>, which pre-warms Lambda containers and keeps them ready to handle incoming requests.</p><p>This ensures that a specified number of Lambda instances are always running and ready, reducing latency spikes. The trade off is a small price implication.</p><h3><strong>5. Use VPC Wisely</strong></h3><p>While it’s tempting to place Lambda functions inside a VPC for better network control, this can increase cold start times. Only place Lambda functions inside a VPC when they need to access resources that reside within it.</p><p>When needed, use <strong>AWS PrivateLink</strong> or <strong>VPC Endpoints</strong> to securely connect to AWS services without routing traffic over the internet, and thus reducing latency.</p><p>By limiting VPC usage to only necessary cases, you can improve cold start times and reduce overhead.</p><h3><strong>6. Optimise Memory Allocation</strong></h3><p>AWS Lambda allocates CPU power proportional to the memory size. By allocating the right amount of memory for your workload, you can significantly impact both the execution speed and cost of your Lambda function. More memory often results in faster execution times.</p><p>However, be careful not to go overboard as too much memory and CPU can lead to an unnecessary costs.</p><h3><strong>7. Batch Database Writes</strong></h3><p>Frequent database writes can slow down Lambda, especially if they’re done sequentially. Instead, batch operations whenever possible.</p><p>For example, in DynamoDB, you can use a BatchWriteCommand to process multiple records at once, reducing the number of roundtrips and improving overall performance. This allows DynamoDB to optimise operations internally.</p><pre>import { BatchWriteCommand, BatchWriteCommandOutput, DynamoDB } from &#39;@aws-sdk/client-dynamodb&#39;;<br>import { DynamoDBDocumentClient } from &#39;@aws-sdk/lib-dynamodb&#39;;<br><br>const dynamodb = DynamoDBDocumentClient.from(new DynamoDB());<br>const TABLE_NAME = process.env.TABLE_NAME;<br><br>// Batch write item params<br>const params = {<br>  RequestItems: {<br>    [TABLE_NAME]: [<br>      {<br>        PutRequest: {<br>          Item: {<br>            PK: { S: &#39;1&#39; },<br>            data: { S: &#39;example1&#39; }<br>          }<br>        }<br>      },<br>      {<br>        PutRequest: {<br>          Item: {<br>            id: { S: &#39;2&#39; },<br>            data: { S: &#39;example2&#39; }<br>          }<br>        }<br>      }<br>    ]<br>  }<br>};<br><br>export const handler = async () =&gt; {<br>  const command = new BatchWriteCommand(params);<br>  const result: BatchWriteCommandOutput = await dynamodb.send(command);<br>  return result;<br>};</pre><p>However, there are some limitations:</p><ul><li>The total batch size must not exceed 16mb</li><li>Any individual item must not exceed 400kb</li><li>A maximum of 25 items per batch request.</li></ul><p>If you expect to hit one or more of these limitations, the next best approach would be to use Promise.all().</p><pre>import { DynamoDBDocumentClient } from &#39;@aws-sdk/lib-dynamodb&#39;;<br>import { DynamoDB, PutItemCommand, PutItemCommandOutput } from &#39;@aws-sdk/client-dynamodb&#39;;<br><br>const dynamodb = DynamoDBDocumentClient.from(new DynamoDB());<br>const TABLE_NAME = process.env.TABLE_NAME;<br><br>const itemsToPut = [<br>  {<br>    PK: { S: &#39;1&#39; },<br>    data: { S: &#39;example 1&#39; }<br>  },<br>  {<br>    PK: { S: &#39;2&#39; },<br>    data: { S: &#39;example 2&#39; }<br>  }<br>]<br><br>export const handler = async () =&gt; {<br>  // Use Promise.all() to make both requests to Dynamo async<br>  const result: Promise&lt;PutItemCommandOutput[]&gt; = await Promise.all(itemsToPut.map(item) =&gt; {<br>    const params = {<br>      TableName: TABLE_NAME,<br>      Item: item<br>    };<br>    const command = new PutItemCommand(item);<br>    const response = await dynamodb.send(command);<br>    return response;<br>  });<br>  return result;<br>};</pre><h3><strong>8. Give your function a single purpose</strong></h3><p>A Lambda function should follow the principle of doing one thing and doing it well. By keeping your function focused on a single responsibility, you can improve performance, simplify debugging, and reduce execution time. Functions that handle multiple, unrelated tasks tend to become complex, slower, and harder to manage.</p><p>For example, if your function is responsible for processing a file upload, it shouldn’t also handle data transformations or analytics. Instead, split these tasks into separate Lambda functions or offload them to other AWS services like <strong>EventBridge</strong>, <strong>Kinesis</strong>, or <strong>SNS</strong>. This modular approach improves the overall efficiency and maintainability of your application.</p><p>In practice, you could chain Lambda functions together using <strong>AWS Step Functions</strong> or <strong>EventBridge</strong>, allowing each function to handle a specific task in the workflow. This keeps each function lightweight and focused on a single purpose, whilst keeping the response to the end user snappy.</p><h3><strong>9. Ask Yourself: Do You Really Need This Lambda Function?</strong></h3><p>AWS offers several services with built-in integrations that can handle many use cases without requiring you to put a Lambda function in the middle. For example, <strong>API Gateway</strong>, <strong>AppSync</strong>, and <strong>EventBridge Pipes</strong> can each directly integrate with many services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*1ZnYNI2xUpt6op_R3lMlaA.png" /><figcaption>A Lambda function is not required between AppSync and DynamoDB</figcaption></figure><pre># This VTL template that sends a request from AppSync to DynamoDB<br>{<br>    &quot;version&quot;: &quot;2018-05-29&quot;,<br>    &quot;operation&quot; : &quot;GetItem&quot;,<br>    &quot;key&quot; : {<br>        &quot;PK&quot; : $util.dynamodb.toDynamoDBJson( &quot;song&quot; ),<br>        &quot;SK&quot; : $util.dynamodb.toDynamoDBJson( $ctx.args.songId )<br>    }<br>}</pre><p>Using these service integrations can eliminate unnecessary Lambda invocations and cost, reduce latency and improve overall system performance.</p><h3><strong>10. Monitor and Adjust Based on Metrics</strong></h3><p>Use AWS CloudWatch to monitor the performance of your Lambda functions, paying attention to metrics like <strong>Duration</strong>, <strong>Memory Usage</strong>, and <strong>Cold Starts</strong>. Regularly review and adjust your configuration based on these metrics to ensure optimal performance.</p><p>AWS also offers CloudWatch Insights to help visualise and track performance over time, allowing you to make data-driven decisions for optimising your Lambda functions.</p><h3>Conclusion</h3><p>That’s my 10 tips to improve Lambda function performance!</p><p>Optimising your AWS Lambda functions for performance is crucial for maintaining fast, efficient, and cost-effective serverless applications. By following best practices such as initialising external dependencies outside the handler, minimising deployment package sizes, and giving each function a single purpose, you can significantly reduce cold start times, improve execution speed, and ensure your functions scale smoothly under load.</p><p>What else did I miss? Let me know in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0504949659a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authenticate AppSync with Cognito: Part 3 — Integrate your API with a frontend application using…]]></title>
            <link>https://awstip.com/authenticate-appsync-with-cognito-part-3-integrate-your-api-with-a-frontend-application-using-11cb5dd7df2a?source=rss-d00cc608d883------2</link>
            <guid isPermaLink="false">https://medium.com/p/11cb5dd7df2a</guid>
            <category><![CDATA[aws-appsync]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-amplify]]></category>
            <category><![CDATA[cognito]]></category>
            <dc:creator><![CDATA[Jake Bazin]]></dc:creator>
            <pubDate>Wed, 11 Sep 2024 07:21:40 GMT</pubDate>
            <atom:updated>2024-09-19T18:09:02.154Z</atom:updated>
            <content:encoded><![CDATA[<h3>Authenticate AppSync with Cognito: Part 3 — Integrate your API with a frontend application using AWS Amplify</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*zTyM82gWR5ZGocc6jNnzBg.png" /></figure><p>In the first two parts of this series, we explored how to create an AWS AppSync API and secure it using AWS Cognito Identity Pools and User Pools. Now, in Part 3, we’ll take it a step further by integrating a frontend application using AWS Amplify. This guide will walk you through the process of setting up Amplify in your frontend, connecting it to your AppSync API, and enabling user authentication and data interaction. I will also be deploying the website to Amplify.</p><p>If you haven’t set up your API and Cognito User Pool yet, make sure to check out <a href="https://medium.com/@jake.bazin/authenticate-appsync-with-cognito-part-1-cognito-identity-pools-for-unauthenticated-access-7408ad59383a">Part 1</a> and <a href="https://medium.com/@jake.bazin/authenticate-appsync-with-cognito-part-2-cognito-user-pools-and-group-based-permissions-9ceeb6062d13">Part 2</a> to get started.</p><p>Feel free to checkout the source code on my Github profile: <a href="https://github.com/jakebaz/amplify-frontend-test">https://github.com/jakebaz/amplify-frontend-test</a></p><h3>Why use AWS Amplify?</h3><p>AWS Amplify makes it incredibly fast and straightforward to build and integrate with cloud applications. In this article, we’ll focus on two key Amplify modules: <strong>Auth</strong> for handling user authentication and <strong>API</strong> for connecting to your AppSync API.</p><p>Amplify’s NPM libraries offer a diverse set of features that simplify the integration process, making it an ideal choice for rapidly scaling applications with minimal setup.</p><p>Additionally, Amplify provides a fully managed web hosting solution, complete with built-in CI/CD, making deployment and updates a breeze. However, even if your website isn’t hosted on AWS, Amplify can still be used to connect to your AppSync API, offering flexibility across various hosting options.</p><h3>What are we going to build?</h3><p>We are going to:</p><ul><li>Build a basic UI with NextJS</li><li>Add User Pool authentication to our UI using the Amplify Auth module</li><li>Connect the application to our API using the Amplify API module</li><li>Deploy to the application to Amplify on AWS</li></ul><h3>Lets build the UI</h3><p>Although I’ll be using <strong>Next.js</strong>, this approach works with any JavaScript framework. So, feel free to adapt it to your framework of choice.</p><h4>Prerequisites</h4><p>Before we start, install the necessary packages:</p><pre>npm install aws-amplify @aws-amplify/api @aws-amplify/ui-react</pre><ul><li>aws-amplify — The core package used to configure authentication and connect to the API.</li><li>@aws-amplify/api — creates the API client which sends requests to your AppSync backend.</li><li>@aws-amplify/ui-react — Adds authentication flows and helps display the login form and other authentication UI components. If you’re working with a different framework like Vue or Angular, Amplify provides equivalent libraries for those as well.</li></ul><p>To get started, update the home page to look something like this. The component will display a list of posts if any are available. Since there are no posts at the moment, it should render the message “No blog posts available.”</p><pre>&quot;use client&quot;;<br><br>import { useEffect, useState } from &quot;react&quot;;<br><br>export default function Home() {<br>  const [posts, setPosts] = useState([]);<br>  const [loading, setLoading] = useState(true);<br><br>  useEffect(() =&gt; {<br>    setLoading(false);<br>  }, []);<br><br>  return (<br>    &lt;main className=&quot;flex flex-col items-center justify-between p-24&quot;&gt;<br>      &lt;h2 className=&quot;text-3xl font-bold&quot;&gt;Blog&lt;/h2&gt;<br>      {!loading &amp;&amp; (<br>        &lt;div className=&quot;flex gap-2 my-2&quot;&gt;<br>          {posts.length ? posts.map((post) =&gt; (<br>            &lt;p key={post.id}&gt;{post.title} written by {post.author}&lt;/p&gt;<br>          )) : &lt;p&gt;No blog posts available&lt;/p&gt;}<br>        &lt;/div&gt;<br>      )}<br>    &lt;/main&gt;<br>  );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UI93aA2g4fMVYQ_ehL8ZBA.png" /></figure><h4>Configure environment variables</h4><p>In the root of your project, create a .env file to define environment variables for your local development environment. The specific names of these variables may vary depending on the framework you&#39;re using. For NextJS, each environment variable should be prefixed with NEXT_PUBLIC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vVOJ1yLHVEVbT7hz1oHlPA.png" /></figure><ul><li>NEXT_PUBLIC_USER_POOL_ID — The id of your Cognito User Pool</li><li>NEXT_PUBLIC_USER_POOL_CLIENT — The id of your Cognito User Pool Client</li><li>NEXT_PUBLIC_GRAPHQL_ENDPOINT — The endpoint URL for your AppSync API</li><li>NEXT_PUBLIC_REGION — The AWS region in which your environment is deployed</li></ul><h4>Add Authentication</h4><p>To add authentication to our app, we need to configure Amplify which is typically done at the top level. In NextJS, we can use the layout.tsx file located in the app directory. Start by importing Amplify and configuring it outside the component like this:</p><pre>import &#39;@aws-amplify/ui-react/styles.css&#39;;<br><br>import { Amplify } from &quot;aws-amplify&quot;;<br>import { Authenticator } from &#39;@aws-amplify/ui-react&#39;;<br><br>Amplify.configure({<br>  Auth: {<br>    // Note that I am using Amplify v6 - v5 cofiguration is slightly different<br>    Cognito: {<br>      // process.env references environment variables created earlier<br>      userPoolId: process.env.NEXT_PUBLIC_USER_POOL_ID as string,<br>      userPoolClientId: process.env.NEXT_PUBLIC_USER_POOL_CLIENT as string<br>    }<br>  }<br>});</pre><p>In this configuration, we’re telling Amplify to use Cognito for authentication. When users log in, Amplify retrieves temporary credentials from Cognito. These credentials will be validated on page load before displaying any content within the Authenticator component (see below).</p><p>Next, in the same file, use the Authenticator component we imported earlier to wrap any content that requires authentication:</p><pre>export default function RootLayout({<br>  children,<br>}: Readonly&lt;{<br>  children: React.ReactNode;<br>}&gt;) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body className={inter.className}&gt;<br>      &lt;Authenticator&gt;<br>          {({signOut, user}) =&gt; (<br>            &lt;&gt;<br>              &lt;div className=&quot;flex justify-between p-8&quot;&gt;<br>                &lt;h1 className=&quot;text-xl&quot;&gt;Hello {user?.username}&lt;/h1&gt;<br>                &lt;button className=&quot;border border-stone-900 cursor-pointer hover:underline p-2 rounded&quot; onClick={signOut}&gt;Sign Out&lt;/button&gt;<br>              &lt;/div&gt;<br>              {children}<br>            &lt;/&gt;<br>          )}<br>        &lt;/Authenticator&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><p>The Authenticator component provides a full authentication workflow, granting us access to user data and methods, such as signing users in or out. In the example above, everything inside the body tag requires authentication.</p><p>Additionally, we display a header and use signOut and user to show the logged in user’s name and includes a button to log out. With this setup, users will now be prompted to log in before they can view any blog posts. The login screen can be customised but by default should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f7ml_p66VzL30sBhZL7EPw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fQhRqck7UbbB9F-6ZB4Z3w.png" /></figure><h3>Configure the API</h3><p>With authentication in place, we can now configure the API to interact with our AppSync backend and display data in the app. To begin, add the following API configuration to Amplify.configure():</p><pre>Amplify.configure({<br>  Auth: {<br>    Cognito: {<br>      userPoolId: process.env.NEXT_PUBLIC_USER_POOL_ID as string,<br>      userPoolClientId: process.env.NEXT_PUBLIC_USER_POOL_CLIENT as string<br>    }<br>  },<br>  API: {<br>    GraphQL: {<br>      endpoint: process.env.NEXT_PUBLIC_GRAPHQL_ENDPOINT as string,<br>      region: process.env.NEXT_PUBLIC_REGION,<br>      defaultAuthMode: &#39;userPool&#39;<br>    }<br>  }<br>});</pre><p>Next, you’ll need to define the client that will interact with your API. In page.tsx, include the following code:</p><pre>import { generateClient, GraphQLResult } from &#39;@aws-amplify/api&#39;;<br><br>const API = generateClient();</pre><h4>Codegen</h4><p>This is an optional step — to make life easy, Amplify allows us to generate all of our Queries, Mutations Subscriptions, Typescript types from our GraphQL schema. This makes integration with your frontend application much simpler as it saves us from having to manually create them. To run the code generation, use the following command:</p><pre>npx @aws-amplify/cli codegen add --apiId {YOUR_APPSYNC_API_ID} --region eu-west-2</pre><p>You’ll be prompted to provide some input, which will look like this:</p><pre>? Choose the type of app that you&#39;re building javascript<br>? What javascript framework are you using react<br>✔ Getting API details<br>? Choose the code generation language target typescript<br>? Enter the file name pattern of graphql queries, mutations and subscriptions src/graphql/**/*.ts<br>? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions Yes<br>? Enter maximum statement depth [increase from default if your schema is deeply nested] 2<br>? Enter the file name for the generated code src/API.ts<br>? Do you want to generate code for your newly created GraphQL API Yes<br>✔ Downloaded the schema<br>✔ Generated GraphQL operations successfully and saved at src/graphql<br>✔ Code generated successfully and saved in file src/API.ts</pre><p>Once complete, you can now import the auto-generated GraphQL Queries and TypeScript types from the newly created graphql folder and API.ts file. This setup reduces manual typing and errors, making the process much more efficient.</p><h4>Sending requests to the API</h4><p>Now we are able to send requests to our API. My updated homepage component looks like this:</p><pre>&quot;use client&quot;<br><br>import { generateClient, GraphQLResult } from &#39;@aws-amplify/api&#39;;<br>import { getPosts } from &quot;@/graphql/queries&quot;;<br>import { GetPostsQuery, Post } from &quot;@/API&quot;;<br>import { useEffect, useState } from &quot;react&quot;;<br><br>const API = generateClient();<br><br>export default function Home() {<br>  const [posts, setPosts] = useState&lt;Post[]&gt;([]);<br>  const [loading, setLoading] = useState(true);<br><br>  const fetchData = async () =&gt; {<br>    try {<br>      const result = await API.graphql({<br>        query: getPosts<br>      }) as GraphQLResult&lt;GetPostsQuery&gt;;<br><br>      if (result.errors?.length) {<br>        throw new Error(result.errors[0].message);<br>      } else {<br>        const newPosts = result.data.getPosts;<br>        setPosts(newPosts ? newPosts : []);<br>      }<br><br>    } catch (err) {<br>      console.error(err);<br>    }<br>    setLoading(false);<br>  }<br><br>  useEffect(() =&gt; {<br>    fetchData()<br>  }, []);<br><br>  return (<br>    &lt;main className=&quot;flex flex-col items-center justify-between p-24&quot;&gt;<br>      &lt;h2 className=&quot;text-3xl font-bold&quot;&gt;Blog&lt;/h2&gt;<br>      {!loading &amp;&amp; (<br>        &lt;div className=&quot;flex gap-2 my-2&quot;&gt;<br>          {posts.length ? posts.map((post) =&gt; (<br>            &lt;p key={post.id}&gt;{post.title} written by {post.author}&lt;/p&gt;<br>          )) : &lt;p&gt;No blog posts available&lt;/p&gt;}<br>        &lt;/div&gt;<br>      )}<br>    &lt;/main&gt;<br>  );<br>}</pre><p>Here’s a breakdown of the key additions to the homepage:</p><ul><li><strong>Imports:</strong> I’ve added imports for the GraphQL types, the GraphQL query, and useEffect.</li><li><strong>useState with Types:</strong> The posts state is explicitly typed to avoid any type errors when updating it.</li><li><strong>fetchData Function:</strong> This function makes the API call, updates the state with the returned result, and handles any errors that may occur during the process.</li><li><strong>useEffect:</strong> The useEffect hook is set to trigger the API call when the page initially loads.</li><li><strong>Conditional Rendering:</strong> Within the JSX, a condition ensures that the page has fully loaded before rendering either a “No blog posts available” message or a list of blog post titles.</li></ul><p>Once the API call is successful, the useState will update with the data, and the list of blog posts should now appear on your page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RESrKUCT8urc1oY_4rarmg.png" /></figure><h3>Deploying the application</h3><p>Now that your application is ready, it’s time to deploy it! You have two main options: set up Amplify to integrate with a remote Git repository or deploy without Git. For this guide, I’ll be using GitHub, which offers CI/CD integration — every time you push changes to the main branch, a new deployment is automatically triggered. This approach is incredibly convenient, though if you prefer more granular control over the build process, you might opt to deploy without a Git repository.</p><h4>Step 1: Connect Amplify to Your Git Repository</h4><p>Once you select GitHub (or your chosen Git provider), Amplify will redirect you to authenticate and allow access to your repositories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2fXEE1TeDKwr5_DU6uZThA.png" /><figcaption>Select your git provider</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*WLVjhLfowLXtExwXOpaEtA.png" /><figcaption>Authorise AWS Amplify to access your Github account</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*ZiX8kVLib3gKFbP-MpGvNw.png" /><figcaption>Select the repository(s) you want Amplify to access</figcaption></figure><h4>Step 2: Configure Your Build Settings</h4><p>After granting access, select your project repository from the dropdown list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9DpngTha8WUidKoqvWV4og.png" /></figure><p>Next, ensure the build command and output directory settings are correct. If you’re using Next.js, these are typically pre-filled, but double-check for any discrepancies before proceeding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CEiNwV3sJ-8PVEYxchYpog.png" /></figure><p>Finally expand “Advanced Settings” and populate the environment variables that you declared earlier in your .env file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-zzRpWziXaKRVL9GNBSYRg.png" /></figure><h4>Step 4: Deploy</h4><p>Click “Next,” review your settings, then hit “Save and Deploy.” Your app will start deploying — this can take a few minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jEWtVkLSRbMj01JyMCX-Qw.png" /></figure><p>Once complete, Amplify will provide a live URL for your app!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VekIxllbXgipxXXY5OZfLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HPcPLpp6ht2Jdi7vJ19Odg.png" /></figure><p>From this point on, every time you push changes to the main branch, Amplify will automatically re-deploy your app, ensuring your live version is always up to date.</p><h3>Conclusion</h3><p>By following this guide, you’ve successfully provided a secure connection from your frontend application AppSync API using AWS Amplify and Cognito for authentication. You have also learned how to build and deploy applications on AWS Amplify providing you with CI/CD pipelines you don’t have to manage.</p><p>Stay tuned for future posts where we’ll dive even deeper into AWS services and ways to enhance your application further!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11cb5dd7df2a" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/authenticate-appsync-with-cognito-part-3-integrate-your-api-with-a-frontend-application-using-11cb5dd7df2a">Authenticate AppSync with Cognito: Part 3 — Integrate your API with a frontend application using…</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authenticate AppSync with Cognito: Part 2 — Cognito User Pools and Group Based Permissions]]></title>
            <link>https://medium.com/@jake.bazin/authenticate-appsync-with-cognito-part-2-cognito-user-pools-and-group-based-permissions-9ceeb6062d13?source=rss-d00cc608d883------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ceeb6062d13</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[appsync]]></category>
            <category><![CDATA[cognito]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <dc:creator><![CDATA[Jake Bazin]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 08:15:16 GMT</pubDate>
            <atom:updated>2024-07-01T08:40:56.221Z</atom:updated>
            <content:encoded><![CDATA[<h3>Authenticate AppSync with Cognito: Part 2 — Cognito User Pools and Group Based Permissions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Smut1VdT73dyM4AeXEuJPw.png" /></figure><h3>Introduction</h3><p>In the first part of this series, we provisioned a Cognito Identity Pool to grant unauthenticated users access to an AppSync API. If you missed it, catch up on part 1 <a href="https://medium.com/p/7408ad59383a">here</a>.</p><p>While Cognito Identity Pools enable user login with various identity providers, there are scenarios where you might want to create and manage your own user directory. This is where Cognito User Pools come in very handy.</p><p>In this second part, we will focus on adding access to our AppSync API using a Cognito User Pool. We’ll also discuss how to limit permissions using Cognito Groups, providing more granular control over what different users can do within your AppSync API.</p><h3>What are Cognito User Pools?</h3><p>Amazon Cognito User Pools provide a secure and scalable way to manage your users, handling everything from sign-up and sign-in to access control. Since it’s an AWS managed service, it takes care of all the heavy lifting, making user management very simple. You can easily access its features by using the AWS SDK, AWS Management console or by integrating AWS Amplify into your frontend application.</p><p>Another great thing about Cognito User Pools is that you can create user “groups” which can be very powerful when you need expose specific features to different types of user.</p><h3>Setting up a Cognito User Pool</h3><p>There are many configurable options in Cognito when creating a Cognito User Pool. The below code snippet shows how you can create a User Pool using the AWS CDK.</p><pre>const userPool = new cognito.UserPool(this, &#39;UserPool&#39;, {<br>  userPoolName: &#39;my-user-pool&#39;, // Name of the user pool<br>  selfSignUpEnabled: true, // Allow visitors to sign themselves up<br>  passwordPolicy: { // Define a password policy all users must adhere to<br>    minLength: 8,<br>    requireLowercase: true,<br>    requireUppercase: true,<br>    requireDigits: true,<br>    requireSymbols: true,<br>  },<br>});</pre><p>In my previous blog post, I created a GraphQL schema with a single query called getPosts(). Now, we&#39;ll take this further by creating user groups in our User Pool. We&#39;ll have two groups: authors, who can create and read posts, and readers, who can only read posts.</p><p>After creating our User Pool, we can define these user groups using the CfnUserPoolGroup class from the Cognito CDK.</p><pre>const authorGroup = new cognito.CfnUserPoolGroup(this, &#39;AuthorGroup&#39;, {<br>  userPoolId: userPool.userPoolId,<br>  groupName: &#39;author&#39;<br>});<br><br>const readerGroup = new cognito.CfnUserPoolGroup(this, &#39;ReaderGroup&#39;, {<br>  userPoolId: userPool.userPoolId,<br>  groupName: &#39;reader&#39;<br>});</pre><h3>Creating a User Pool Client</h3><p>To interact with our AppSync API, users need to sign in through our Cognito User Pool. The authentication process is handled by a User Pool Client, which acts as the interface.</p><p>Whether you are signing in via the frontend Amplify library, a Cognito Hosted UI, or even directly in the AppSync console, this is mostly handled by Cognito, and all we need to do is attach an app client to the user pool we just created.</p><p>The following code snippet creates a User Pool Client:</p><pre>const userPoolClient = new cognito.UserPoolClient(this, &#39;UserPoolClient&#39;, {<br>  userPoolClientName: &#39;my-user-pool-client&#39;,<br>  userPool<br>});</pre><p>While there are many customisable options available for a User Pool Client, in this case, all we need to do is specify the userPoolClientName and reference the userPool we’ve already configured.</p><h3>Updating our GraphQL Schema</h3><h4>Step 1: Create the new mutation</h4><p>We need to create a new mutation that creates a new post. Your schema should now look like this:</p><pre>type schema {<br>  query: Query<br>  mutation: Mutation<br>}<br><br>type Query {<br> getPosts: [Post!]<br>}<br><br>type Mutation {<br>  createPost(title: string, body: string, author: string): Post!<br>}<br><br>type Post {<br> id: String!<br> title: String!<br> author: String!<br> body: String!<br>}</pre><h4>Step 2: Allow access to users within our User Pool</h4><p>Right now, nobody can access any data from AppSync. To let users in our Cognito User Pool access the data, we can use decorators similar to the @aws_iam decorator we saw in <a href="https://medium.com/@jake.bazin/authenticate-appsync-with-cognito-part-1-cognito-identity-pools-for-unauthenticated-access-7408ad59383a">part 1</a>.</p><p>There are two main decorators we need to know:</p><ul><li>@aws_cognito_user_pools — This lets all users in your Cognito User Pool access the data, no matter which group they belong to.</li><li>@aws_auth(cognito_groups: []) — This allows users in specific groups to access the data, giving you more control over permissions based on group membership.</li></ul><pre>type schema {<br>  query: Query<br>  mutation: Mutation<br>}<br><br>type Query {<br> getPosts: [Post!] @aws_cognito_user_pools<br>}<br><br>type Mutation {<br>  createPost(title: string, body: string, author: string): Post!<br>    @aws_auth(cognito_groups: [&quot;author&quot;])<br>}<br><br>type Post @aws_cognito_user_pools {<br> id: String!<br> title: String!<br> author: String!<br> body: String!<br>}</pre><p>To make sure that all users can see posts, we used the @aws_cognito_user_pools decorator in the getPosts query. To restrict access for creating posts, we added the @aws_auth(cognito_groups: [&quot;author&quot;]) decorator to the createPost mutation.</p><p>We have also added the @aws_cognito_user_pools decorator to the type Post, note that this is only mandatory if Cognito User Pools is not the default authorisation method in your AppSync setup.</p><h4>Step 3: Setup AppSync Resolvers and Data Sources</h4><p>In order to use our schema, we need to tell AppSync what to do with incoming requests. For this we use AppSync Resolvers, which forward the request on to the Data Source.</p><p>The code snippet below creates a DynamoDB table, adds it to our API as a Data Source, and creates resolvers for our GraphQL Query and Mutation.</p><pre>const db = new dynamodb.Table(this, &#39;Table&#39;, {<br>  partitionKey: {<br>    name: &#39;PK&#39;,<br>    type: dynamodb.AttributeType.STRING<br>  },<br>  sortKey: {<br>    name: &#39;SK&#39;,<br>    type: dynamodb.AttributeType.STRING<br>  },<br>  billingMode: dynamodb.BillingMode.PAY_PER_REQUEST<br>});<br><br>const dynamodbDataSource = api.addDynamoDbDataSource(&#39;DynamoDBDataSource&#39;, db);<br><br>const putPostResolver = new appsync.Resolver(this, &#39;PutPostResolverTemplates&#39;, {<br>  api,<br>  dataSource: dynamodbDataSource,<br>  typeName: &#39;Mutation&#39;,<br>  fieldName: &#39;createPost&#39;,<br>  requestMappingTemplate: appsync.MappingTemplate.fromFile(&#39;lib/src/api/mapping-templates/create-post.request.vtl&#39;),<br>  responseMappingTemplate: appsync.MappingTemplate.fromFile(&#39;lib/src/api/mapping-templates/create-post.response.vtl&#39;),<br>});<br><br>const getPostsResolver = new appsync.Resolver(this, &#39;GetPostsResolverTemplates&#39;, {<br>  api,<br>  dataSource: dynamodbDataSource,<br>  typeName: &#39;Query&#39;,<br>  fieldName: &#39;getPosts&#39;,<br>  requestMappingTemplate: appsync.MappingTemplate.fromFile(&#39;lib/src/api/mapping-templates/get-posts.request.vtl&#39;),<br>  responseMappingTemplate: appsync.MappingTemplate.fromFile(&#39;lib/src/api/mapping-templates/get-posts.response.vtl&#39;),<br>});</pre><p>Notice on putPostResolver and getPostResolver there is a requestMappingTemplate and a responseMappingTemplate. The request mapping template maps the request into a DynamoDB query, whilst the response mapping template just returns the result. These are written in VTL, but can also be written in JavaScript.</p><pre># create-post.request.vtl<br><br>#set($id = $util.autoId())<br>#set($pk = $util.dynamodb.toDynamoDBJson( &quot;Post&quot; ))<br>#set($sk = $util.dynamodb.toDynamoDBJson( $id ))<br>{<br>  &quot;version&quot;: &quot;2018-05-29&quot;,<br>  &quot;operation&quot;: &quot;UpdateItem&quot;,<br>  &quot;key&quot;: {<br>    &quot;PK&quot;: $pk,<br>    &quot;SK&quot;: $sk<br>  },<br>  &quot;update&quot;: {<br>    &quot;expression&quot;: &quot;SET id = :id, title = :title, body = :body, author = :author&quot;,<br>    &quot;expressionValues&quot;: {<br>      &quot;:id&quot;: $util.dynamodb.toDynamoDBJson( $id ),<br>      &quot;:title&quot;: $util.dynamodb.toDynamoDBJson( $ctx.args.title ),<br>      &quot;:body&quot;: $util.dynamodb.toDynamoDBJson( $ctx.args.body ),<br>      &quot;:author&quot;: $util.dynamodb.toDynamoDBJson( $ctx.args.author )<br>    }<br>  }<br>}</pre><pre># create-post.response.vtl<br><br>$util.toJson($ctx.result)</pre><pre># get-posts.request.vtl<br><br>{<br>    &quot;version&quot; : &quot;2017-02-28&quot;,<br>    &quot;operation&quot; : &quot;Query&quot;,<br>    &quot;query&quot; : {<br>        &quot;expression&quot;: &quot;PK = :PK&quot;,<br>        &quot;expressionValues&quot;: {<br>          &quot;:PK&quot;: $util.dynamodb.toDynamoDBJson( &quot;Post&quot; )<br>        }<br>    }<br>}</pre><pre># get-posts.response.vtl<br>$util.toJson($ctx.result.items)</pre><h3>Testing it all works</h3><p>The First thing you need to do to test this works, is create a two users in your Cognito User Pool, give one the role “reader” and the other the role “author”. This can be done from Cognito in the AWS Console.</p><p>Then navigate to your AppSync API in the AppSync Console. When you get there, click the Queries tab, and make sure the correct authorisation type is selected in the dropdown at the top of the page before running a query. You should find that you get an unauthorised response that looks something like this:</p><blockquote>AxiosError: Request failed with status code 401</blockquote><p>Now we know that our AppSync API is protected. Next login with the button above the response pane that says “Login with User Pools”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYpKrfIqWG4IlWG9_gUHxQ.png" /></figure><p>First login with as an author and run the following query:</p><pre>query MyQuery {<br>  createPost(<br>    title: &quot;My first post&quot;,<br>    body: &quot;Welcome, this is my first post&quot;,<br>    author: &quot;Jake Bazin&quot;<br>  ) {<br>    id<br>    title<br>    body<br>    author<br>  }<br>}</pre><p>You should get a response that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5YieiW6-WEyzMp2nNbRHQ.png" /></figure><p>We have now created our first post. Next run the getPosts query:</p><pre>query MyQuery {<br>  getPosts {<br>    author<br>    body<br>    id<br>    title<br>  }<br>}</pre><p>You should receive back an array with just the post you created. Now we know that authors can access both getPosts and createPost. Perfect!</p><p>Now try logging in as a reader and run the same queries. You should find that reader can access getPosts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LPzPJjoRw9n3YI6p4ybQ6A.png" /></figure><p>However you should get an unauthorised error when trying to access createPost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fl_B-g7RD1JZIVzUWN5Ybg.png" /></figure><h3>Conclusion</h3><p>That’s a wrap for part 2 on Authenticating AppSync with Cognito. In conclusion we learned how to create a Cognito User Pool and use it as an authentication method for our AppSync API. We also learned how to create Cognito Groups and added group based access in our GraphQL schema. Additionally we got a look into how to create Resolvers and Data Sources in AppSync using the AWS CDK and VTL for the resolver templates.</p><p>In the next part of this series I am going to show you how to integrate Cognito Authentication into a frontend application using AWS Amplify, so that users are able to sign in and sign up using your website. I will also cover how to integrate the AppSync API into a frontend.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ceeb6062d13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authenticate AppSync With Cognito: Part 1 —  Cognito Identity Pools for Unauthenticated Access]]></title>
            <link>https://medium.com/@jake.bazin/authenticate-appsync-with-cognito-part-1-cognito-identity-pools-for-unauthenticated-access-7408ad59383a?source=rss-d00cc608d883------2</link>
            <guid isPermaLink="false">https://medium.com/p/7408ad59383a</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cognito-identity-pool]]></category>
            <category><![CDATA[aws-appsync]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[cognito]]></category>
            <dc:creator><![CDATA[Jake Bazin]]></dc:creator>
            <pubDate>Wed, 22 May 2024 09:44:39 GMT</pubDate>
            <atom:updated>2024-05-22T10:11:44.522Z</atom:updated>
            <content:encoded><![CDATA[<h3>Authenticate AppSync With Cognito: Part 1 — Cognito Identity Pools for Unauthenticated Access</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*ede0CXV5ryxSNOwE7WjRXA.png" /></figure><h3>Introduction</h3><p>Many public-facing applications require users to access certain features or data without the need for authentication. However, AWS AppSync, by default, does not support unauthenticated requests.</p><p>In this first part of my series on AppSync Authentication with Cognito, we will explore how to enable unauthenticated users to securely access an AppSync API using AWS Cognito Identity Pools. By the end of this post, you’ll understand the architectural approach and implementation steps needed to securely grant access to unauthenticated users.</p><h3>What are Cognito Identity Pools?</h3><p>Cognito Identity Pools (also known as federated identities) enable you to create unique identities for your users and authenticate them with a variety of identity providers, which we’ll see in the next section.</p><p>They allow both authenticated and unauthenticated users to obtain temporary AWS credentials, which can then be used to access AWS services.</p><p>This functionality provides a flexible and scalable way to manage user identities and permissions, ensuring secure and efficient access to your AWS resources.</p><h3>Supported Identity Providers for Cognito Identity Pools</h3><p>Cognito Identity Pools offer support for various identity providers, giving you great flexibility in authenticating users from one or multiple sources.</p><p>Here are the primary types of identity providers that Cognito Identity Pools support:</p><ol><li><strong>Cognito User Pools: </strong>AWS Cognito User Pools provide a secure and scalable user directory that can handle user sign-up, sign-in, and access control. When integrated with identity pools, users authenticated via user pools can obtain temporary AWS credentials to access AWS services.</li></ol><p>2. <strong>Social Identity Providers:</strong></p><ul><li><strong>Facebook</strong>: Allow users to sign in with their Facebook accounts.</li><li><strong>Google</strong>: Enable users to authenticate using their Google credentials.</li><li><strong>Amazon</strong>: Support login via Amazon accounts.</li><li><strong>Apple</strong>: Integrate with Apple ID for user authentication.</li></ul><p>3. <strong>OpenID Connect (OIDC) Providers: </strong>Connect with any identity provider that supports the OpenID Connect standard. This includes services like Auth0 and Okta, allowing for extensive flexibility and compatibility with various authentication systems.</p><p>4. <strong>SAML-based Providers: </strong>Integrate with SAML-based identity providers commonly used in enterprise environments. This allows users to authenticate using corporate credentials from providers like Microsoft Active Directory Federation Services (ADFS).</p><h3>Setup your Cognito Identity Pool and IAM role</h3><p>To allow unauthenticated users to access an AppSync API, we need to provision the required resources. Here’s some how it works with all infrastructure written with the AWS CDK:</p><h4>Step 1 - Create an Identity Pool</h4><p>Make sure to specify that it should allow unauthenticated identities. This means users can access certain AWS resources without needing to sign in. You also need to specify an identity provider, in the snippet below I use a Cognito User Pool.</p><pre>const identityPool = new cognito.CfnIdentityPool(this, &#39;IdentityPool&#39;, {<br> identityPoolName: `my-identity-pool`,<br> allowUnauthenticatedIdentities: true, // Allow unauthenticated access<br> cognitoIdentityProviders: [<br>  {<br>   clientId: guestUserPoolClient.userPoolClientId,<br>   providerName: guestUserPool.userPoolProviderName,<br>  }<br> ]<br>});</pre><h4>Step 2 - Provision an IAM Role</h4><p>Within the identity pool configuration, define an IAM role for unauthenticated users. This role includes policies that specify the permissions for these users, such as access to AppSync.</p><pre>// Policy gives access to all actions on AppSync<br>const unauthenticatedPolicyDocument = new iam.PolicyDocument({<br> statements: [new iam.PolicyStatement({<br>  sid: &#39;AllActions&#39;,<br>  actions: [&#39;appsync:GraphQL&#39;],<br>  resources: [&#39;arn:aws:appsync:*:*:apis/*/types/*/fields/*&#39;]<br> })]<br>});<br><br>// Attach policy to new IAM role<br>const unauthenticatedRole = new iam.Role(this, &#39;CognitoDefaultUnauthenticatedRole&#39;, {<br> roleName: `cognito-default-unauthenticated-role`,<br> description: &#39;IAM Role to be assumed by Cognito for unauthenticated user&#39;,<br> managedPolicies: [unauthenticatedPolicyDocument.toJSON()],<br> assumedBy: new iam.FederatedPrincipal(&#39;cognito-identity.amazonaws.com&#39;, {<br>  StringEquals: { &#39;cognito-identity.amazonaws.com:aud&#39;: identityPool.attrId },<br>  &#39;ForAnyValue:StringLike&#39;: { &#39;cognito-identity.amazonaws.com:amr&#39;: &#39;unauthenticated&#39; },<br> })<br>});</pre><h4>Step 3 - Attach IAM role to Cognito Identity Pool</h4><p>The role must be attached to the identity pool so that it knows to use it. You can provision an unauthenticated role and an authenticated role, for now we only need the unauthenticated role, but this gives us flexibility because we can give unauthenticated users different permissions to authenticated users.</p><pre>// Attach role to Identity Pool<br>new cognito.CfnIdentityPoolRoleAttachment(this, &#39;IdentityPoolRoleAttachment&#39;, {<br> identityPoolId: identityPool.attrId,<br> roles: {<br>  unauthenticated: unauthenticatedRole.roleArn<br> }<br>});</pre><p>If you’d like to add an authenticated role just follow step 2 again to add the desired permissions, change the variable names, and add it to roles section:</p><pre>// Attach roles to Identity Pool<br>new cognito.CfnIdentityPoolRoleAttachment(this, &#39;IdentityPoolRoleAttachment&#39;, {<br> identityPoolId: identityPool.attrId,<br> roles: {<br>  authenticated: authenticatedRole.roleArn,<br>  unauthenticated: unauthenticatedRole.roleArn<br> }<br>});</pre><h3>Setting Up AWS AppSync for Unauthenticated Access</h3><p>To allow unauthenticated users to access your AppSync API, you need to configure AppSync to work with your Identity Pool. Here’s a concise guide on setting up AWS AppSync for unauthenticated access:</p><h4>Step 1: Create an AppSync API</h4><p>When creating the API you need to specify the authorisation type as `AWS_IAM`, using the `authorizationConfig` option.</p><pre>const api = new appsync.GraphqlApi(this, &#39;GraphQLAPI&#39;, {<br> name: `my-graphql-api`,<br> definition: appsync.Definition.fromFile(path.join(__dirname, &#39;src/api/schema.graphql&#39;)),<br> authorizationConfig: {<br>  defaultAuthorization: {<br>   authorizationType: appsync.AuthorizationType.IAM,<br>  }<br> },<br> logConfig: {<br>  fieldLogLevel: appsync.FieldLogLevel.ALL<br> }<br>});<br><br>// ...add data sources and resolvers below</pre><h4>Step 2: Create an your GraphQL schema</h4><p>Create a file called `schema.graphql`. The file should be stored at the path specified with the `definition` option in your api configuration above. Here is a basic example of what it might look like:</p><pre>type Query {<br> getPosts: [Post!] @aws_iam<br>}<br><br>type Post {<br> id: String!<br> title: String!<br> author: String!<br> body: String!<br>}</pre><p>The `@aws_iam` directive tells AppSync that an IAM role with the correct permissions is required to access the `getPosts` query. You must add this directive to all queries, mutations, and subscriptions that you want unauthenticated users to access.</p><p>If IAM is the primary authentication method, this setting cascades down, and you do not need to add it to the returned types. However, if it is an additional authentication method, you will need to specify it on the types, like so:</p><pre>type Query {<br> getPosts: [Post!] @aws_iam<br>}<br><br>type Post @aws_iam {<br> id: String!<br> title: String!<br> author: String!<br> body: String!<br>}</pre><h3>Conclusion</h3><p>By following the steps outlined in this post, you can configure AWS Cognito Identity Pools and IAM roles to enable unauthenticated users to securely access your AWS AppSync API. This setup leverages the power of AWS services to provide seamless and secure access to public features and data in your application.</p><p>To summarise, we’ve covered:</p><p><strong>1. Creating an Identity Pool:</strong> Allowing unauthenticated identities and configuring identity providers.<br><strong>2. Provisioning an IAM Role: </strong>Defining permissions and attaching the role to the identity pool.<br><strong>3. Setting Up AppSync:</strong> Configuring the API with IAM authorisation and defining the GraphQL schema to specify access permissions.</p><p>In the next part of this series, I will show you how to add authenticated access using Cognito User Pools. We’ll also discuss how to limit permissions through the use of Cognito Groups, allowing for more granular control over what different users can do within your AppSync API.</p><p>Stay tuned for more insights on securing your AWS AppSync APIs with Cognito!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7408ad59383a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining Menu Data Retrieval with AWS AppSync and Amazon S3]]></title>
            <link>https://medium.com/@jake.bazin/streamlining-menu-data-retrieval-with-aws-appsync-and-amazon-s3-46587bb5d391?source=rss-d00cc608d883------2</link>
            <guid isPermaLink="false">https://medium.com/p/46587bb5d391</guid>
            <category><![CDATA[aws-appsync]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Jake Bazin]]></dc:creator>
            <pubDate>Wed, 27 Mar 2024 08:53:06 GMT</pubDate>
            <atom:updated>2024-03-27T08:53:06.433Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s dynamic airport environments, ensuring swift service for guests in the lounge is paramount while upholding a premium experience. Leveraging the capabilities of AWS AppSync and its direct integration with Amazon Simple Storage Service (S3), developers can create a seamless solution for retrieving menu data stored in S3 directly from the guest-facing frontend. In this blog post, we’ll explore how to streamline file retrieval with AWS AppSync, focusing on the specific use case of retrieving menu data from S3 for guests accessing the a menu in the airport lounge.</p><h4>Why Retrieve Files from S3 via AppSync?</h4><p>Our scenario involves storing menu data in DynamoDB which is managed by the lounge staff. When the menu is to be published it is bundled into a JSON object, and pushed it to S3 for centralised storage. The lounge staff may want to update menu data in DynamoDB without publishing the changes to the guests. This is possible by decoupling the menu that the guest sees from the data stored in DynamoDB.</p><p>Integrating S3 with AWS AppSync offers several advantages for retrieving menu data:</p><ol><li><strong>Efficient Data Management:</strong> By storing menu data in S3, we can easily manage large JSON objects containing menu items, sections and categories — which all have different keys in DynamoDB.</li><li><strong>Reduced Latency:</strong> Direct integration between AppSync and S3 minimises the number of network hops, resulting in lower latency compared to accessing S3 through an intermediate service.</li><li><strong>Scalability</strong>: Leveraging the scalability of both AppSync and S3 allows applications to seamlessly handle increasing loads and efficiently manage large volumes of data.</li></ol><p>And many more…</p><h3>Retrieving Menu Data from S3 via AppSync: Step-by-Step</h3><h4>Step 1: Upload a structured JSON file to S3</h4><p>Bundle your data into a structured JSON object. It is important to know the structure of your data because AppSync is a strict schema based API and you will be required to specify the response structure in your GraphQL Schema.</p><p>I will use a simple data structure for this example:</p><pre>{<br>  &quot;categories&quot;: [<br>    {<br>      &quot;id&quot;: &quot;36cef14e-6368-4e28-b044-0659abdcce50&quot;,<br>      &quot;title&quot;: &quot;Food&quot;<br>      &quot;sections&quot;: [<br>        {<br>          &quot;id&quot;: &quot;2a4e7552-ccfa-4ed4-b7e4-3b9517019f0f&quot;,<br>          &quot;title&quot;: &quot;Hot Food&quot;,<br>          &quot;menuItems&quot;: [<br>            {<br>              &quot;id&quot;: &quot;d702f95f-643f-4535-afcc-9e92ed69e8c1&quot;,<br>              &quot;calories&quot;: 750,<br>              &quot;description&quot;: &quot;A delicious beef burger served with lettuce, onion rings, tomato and burger sauce&quot;,<br>              &quot;title&quot;: &quot;Beef Burger&quot;<br>            },<br>            {<br>              &quot;id&quot;: &quot;7785ad91-a266-4deb-837e-ace0c115b1d7&quot;,<br>              &quot;calories&quot;: 650,<br>              &quot;description&quot;: &quot;A delicious chicken burger served with lettuce, tomato and burger sauce&quot;,<br>              &quot;title&quot;: &quot;Chicken Burger&quot;<br>            }<br>          ]<br>        }<br>      ]<br>    }<br>  ]<br>}</pre><h4>Step 2: Create an AWS AppSync API</h4><p>In the AWS AppSync console, create a new API with a schema defining a query to retrieve menu data.</p><pre>schema {<br>  query: Query<br>}<br><br>type Query {<br>  getMenuData: Menu<br>}<br><br>type Menu {<br>  categories: [Category]!<br>}<br><br>type Category {<br>  id: String!<br>  title: String!<br>  sections: [Section]!<br>}<br><br>type Section {<br>  id: String!<br>  title: String!<br>  menuItems: [MenuItem]!<br>}<br><br>type MenuItem {<br>  id: String!<br>  calories: Int!<br>  description: String<br>  title: String!<br>}</pre><h4>Step 3: Implement a Resolver</h4><p>Create a resolver in the AppSync API to fetch menu data from S3. This resolver will execute custom logic to retrieve the JSON file containing menu data.</p><p>There are many lounges worldwide, so we have a path in S3 for each lounge.</p><p>A menu can also be published in multiple languages, so we include the language and lounge id in the file name. These variables can then be fetched from the request payload on the mapping templates.</p><p>The below examples are written with VTL. Note that AppSync also supports Javascript resolvers.</p><p><strong>Request:</strong></p><pre>{<br>  &quot;version&quot;: &quot;2018-05-29&quot;,<br>  &quot;method&quot;: &quot;GET&quot;,<br>  &quot;resourcePath&quot;: &quot;/foodmenu/${context.arguments.loungeId}/${context.arguments.loungeId}.${context.arguments.language}.FoodMenu.json&quot;<br>}</pre><p><strong>Response:</strong></p><pre>#if($context.result.statusCode &amp;&amp; $context.result.statusCode != 200)<br>  #set ($error = $utils.xml.toMap($context.result.body))Error<br>  $utils.error($error.Message, $error.Code, $context.result, $error)<br>#else<br>  $context.result.body<br>#end</pre><h4>Step 4: Integrate with Guest-Facing Frontend</h4><p>Integrate the AWS AppSync client SDK into the guest-facing frontend application. Configure the client to communicate with the AppSync API endpoint and execute GraphQL queries to retrieve menu data from S3.</p><pre>import AWSAppSyncClient, { gql } from &#39;aws-appsync&#39;;<br>import { Auth } from &#39;aws-amplify&#39;;<br><br>const client = new AWSAppSyncClient({<br>  url: &#39;&lt;YOUR_APPSYNC_API_ENDPOINT&gt;&#39;,<br>  region: &#39;&lt;YOUR_AWS_REGION&gt;&#39;<br>});<br><br>const getMenuData = async () =&gt; {<br>  const query = gql`<br>    query GetMenuData {<br>      getMenuData {<br>        categories {<br>          sections {<br>            menuItems<br>          }<br>        }<br>      }<br>    }<br>  `;<br><br>  const response = await client.query({ query });<br>  return response.data.getMenuData;<br>};<br><br>// Usage<br>getMenuData().then((menuData) =&gt; {<br>  console.log(&#39;Menu Data:&#39;, menuData);<br>});</pre><h3>Conclusion</h3><p>Integrating S3 with AWS AppSync provides a streamlined approach to retrieving menu data for guests accessing the frontend. By leveraging the capabilities of AWS AppSync and S3, developers can create a robust solution that efficiently manages and retrieves menu data from the cloud. Whether you’re building a food/drink ordering system or any other application requiring retrieval of a large amount of data, the combination of AppSync and S3 empowers you to deliver an effortless and scalable data management solution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46587bb5d391" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Solution to Provide Airport Lounge Customers up to Date Flight and Gate Information via the…]]></title>
            <link>https://medium.com/on-tech-by-leighton/aws-solution-to-provide-airport-lounge-customers-up-to-date-flight-and-gate-information-via-the-d53235760db9?source=rss-d00cc608d883------2</link>
            <guid isPermaLink="false">https://medium.com/p/d53235760db9</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[application-modernization]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Jake Bazin]]></dc:creator>
            <pubDate>Thu, 11 May 2023 14:43:38 GMT</pubDate>
            <atom:updated>2023-05-11T14:46:47.272Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS Solution to Provide Airport Lounge Customers up to Date Flight and Gate Information via the Lounge App</h3><p>For frequent travellers, airport lounges provide a haven from the chaos of the airport. An airport lounge app that provides real-time flight and gate information can be a useful tool for any frequent traveller as it removes the need to get up from where they are sat and check the board.</p><p>An airline approached us to deliver an in-app departures notification system as part of a larger application modernisation project for airport lounges. To give their First and Business Class travellers up-to-date flight and gate information to improve their pre-flight experience, the airline used two existing data sources across their digital portfolio, neither of which were the perfect fit for the in-app departures notification system.</p><p>One of the services was a HTTP endpoint meaning we couldn’t get data in real-time and the other supplied us with real time data, but it is not customer facing and is updated too often with data that the user does not need to know about.</p><p>In this blog post, I will explain how we leveraged the existing data sources to deliver as close to a real-time solution as possible, without creating unnecessary load on downstream services.</p><p>The blog will explore how I created a serverless solution using AWS and the Serverless Framework to build an API that integrates with the lounge app so that users can get flight and gate information in real-time.</p><h3>Designing The Solution</h3><figure><img alt="Diagram of the solution" src="https://cdn-images-1.medium.com/max/927/1*PGXfacNno-RXB7P9mdUWyA.png" /></figure><p>The two existing services available that store the information we needed both had advantages and disadvantages.</p><p>Service A was a good choice because it provides a WebSocket endpoint which can be subscribed to, but the data is often manually changed by a real person behind a desk. The data is not customer facing and often becomes inaccurate.</p><p>Service B provides a HTTP endpoint which means to check for updates, a request has to be sent each time. Also, this service already receives millions of requests per day, so it was necessary to be careful with how many calls are made because I didn’t want to be the one to overload it! That being said, the data is already customer facing, meaning it is reliable and only contains data the customer is allowed to see.</p><p>I went for service B. Due to the fact that the data is already customer facing, less money is spent on compute time for the Lambda functions because data doesn’t need to be manipulated to ensure we only have the data we need for this application. Read on to find out how I used AWS Step Functions to keep the number of calls to this service to a minimum.</p><p>I chose to use the following AWS resources to try to minimise costs and meet business requirements:</p><ul><li>AWS AppSync to provide a GraphQL API that can be accessed via the frontend application, update in real-time and be able to scale to millions of connections</li><li>AWS DynamoDB to store flight and gate information and act as a datastore for the AppSync API</li><li>DynamoDB Streams, which were used to call a Lambda function. This Lambda kicks off an AWS Step Functions workflow</li><li>An AWS Step Functions workflow which handles the periodic fetching of up to date flight information from an external API, as well as calling a lambda function, which contains some business logic to decide whether or not to push an update to the frontend</li></ul><h3>Implementing the Solution</h3><p>To build the solution, I decided to use the Serverless Framework, which is an open-source framework that simplifies the process of building serverless applications.</p><p>I used AWS Step Functions to fetch data periodically. The idea is that we have a Step Functions workflow per flight, but only if there is someone in the lounge who has requested information for that specific flight. There are hundreds of flights taking off per day, but it will not fetch data for a specific flight if nobody has requested that data.</p><p>In the first step of the AWS Step Functions workflow a Lambda function fetches the data for the given flight from the external API. When it has fetched the data, it gets compared with the data we already have in DynamoDB. If the data is not the same, it publishes a mutation on the AppSync API that updates the DynamoDB and pushes the update to the frontend in real-time.</p><p>The second step of the AWS Step Functions workflow is a “choice” step. If the flight has taken off, the workflow ends and the record is removed from the database after 30 minutes have passed. If the flight has not taken off, it will go to a “sleep” step, where it will sleep for X number of minutes, depending on how soon the flight is due to take off. I made the sleep step dynamic, dramatically reducing the number of calls to the datastore as well as our AWS costs, all while still giving a dynamic user experience.</p><p>When a user requests information for a specific flight, it will check to see if information for this flight is already in the database. If it is, it will subscribe to this data. However, if it is not already in the database, it will add the PK and SK for this item into the database and create the subscription. Then, DynamoDB streams will use a Lambda function to kick off the AWS Step Functions workflow for the given flight number. The good thing about this is that there will only ever be one instance of Step Functions running for a given flight, even if there are 20 customers in the lounge requesting information for this flight.</p><p>The DynamoDB table was implemented with single table design principles in mind, meaning we have one table for everything. This means a flight is stored in the same table as a gate, see below for an example of the PK’s and SK’s on this table.</p><figure><img alt="Visual representation of the DynamoDB data structure" src="https://cdn-images-1.medium.com/max/895/1*rVYWPnm0ymG9yVjBOV_Z7A.png" /></figure><p>AWS AppSync was chosen for our API so that we could create GraphQL subscriptions between the frontend and backend. For a real-time application like this, it allows us to give users information as they are waiting for their departure.</p><h3>Conclusion</h3><p>By using the Serverless Framework and AWS services, we were able to create a reliable and scalable solution for an airport lounge app that provides real-time flight and gate information. The solution acts as a cache, utilising AWS Step Functions to update flight and gate information periodically, depending on how soon the a flight is due to take off. AWS AppSync and DynamoDB streams were used to provide real-time updates to the frontend, and AWS Step Functions ensured we only made the necessary calls to the external API, reducing the overall load on the system. This solution could now be consumed by other applications throughout the business to make fetching flight and gate information easy and painless.</p><p><strong>About Leighton</strong></p><p>Leighton is a software development business that builds high performing teams and develops successful software applications for its customers. We’re on a mission to help organisations and their customers thrive in today’s fast paced world. For as long as we can remember (and we’ve been around for 30 years) organisations have struggled to deliver digital change. That’s where we come in. We help organisations thrive by bringing people and technology together.</p><p><a href="https://www.leighton.com/">www.leighton.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d53235760db9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/on-tech-by-leighton/aws-solution-to-provide-airport-lounge-customers-up-to-date-flight-and-gate-information-via-the-d53235760db9">AWS Solution to Provide Airport Lounge Customers up to Date Flight and Gate Information via the…</a> was originally published in <a href="https://medium.com/on-tech-by-leighton">on:tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Pros and Cons of TailwindCSS]]></title>
            <link>https://medium.com/@jake.bazin/the-pros-and-cons-of-tailwindcss-205febbab782?source=rss-d00cc608d883------2</link>
            <guid isPermaLink="false">https://medium.com/p/205febbab782</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[tailwind]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <dc:creator><![CDATA[Jake Bazin]]></dc:creator>
            <pubDate>Fri, 20 Jan 2023 21:50:18 GMT</pubDate>
            <atom:updated>2023-01-20T21:50:18.329Z</atom:updated>
            <content:encoded><![CDATA[<p>I have been using Tailwind on a project for the past 10 months and have been thinking about its pros and cons, and whether or not I would use it again on future projects.</p><h3>What is Tailwind?</h3><p><a href="https://tailwindcss.com/">TailwindCSS</a> is an open source utility-first CSS framework that allows you to style your webpages directly in your HTML through the use of “utility classes”. This allows you to write pre-defined classes on to your HTML elements and not have write your own CSS.</p><p>Tailwind also offer a component library called <a href="https://tailwindui.com/">Tailwind UI</a> which is available if you’re happy to spend some money. This provides HTML, Vue, and React code that you can copy and paste into your project.</p><p>This all sounds great, but I believe it also has its downsides. In this article I am going to tell you what I like and dislike about Tailwind in order to try and help you make your own decision as to whether or not you should use it.</p><h3>Rapid UI Development</h3><p>From the code snippet below, you can see how quick it is to create a simple component that looks great. All the code is in the HTML so you can do it in fewer lines than creating your own classes for your elements and styling them with CSS. This enables you to build a UI very quickly.</p><pre>```HTML<br>&lt;div class=&quot;h-screen w-screen relative&quot;&gt;<br> &lt;div class=&quot;w-full h-full bg-black opacity-30&quot;&gt;&lt;/div&gt;<br> &lt;div class=&quot;flex justify-center&quot;&gt;<br>  &lt;div class=&quot;absolute container w-full top-2/4 -translate-y-1/2 mx-4&quot;&gt;<br>   &lt;div class=&quot;bg-white rounded-md shadow py-4 px-8&quot;&gt;<br>    &lt;h3 class=&quot;text-center text-gray-800 font-bold text-lg my-4&quot;&gt;Delete User&lt;/h3&gt;<br>    &lt;p class=&quot;my-2 text-gray-700 text-center&quot;&gt;Are you sure you would like to delete this User?&lt;/p&gt;<br>    &lt;div class=&quot;mt-8 flex justify-end&quot;&gt;<br>     &lt;button class=&quot;rounded-md text-gray-700 bg-gray-200 hover:bg-gray-300 border border-gray-600 hover:underline px-4 py-2&quot;&gt;Cancel&lt;/button&gt;<br>    &lt;button class=&quot;rounded-md text-white bg-red-600 hover:bg-red-700 hover:underline px-4 py-2 ml-2&quot;&gt;Delete&lt;/button&gt;<br>    &lt;/div&gt;<br>   &lt;/div&gt;<br>  &lt;/div&gt;<br> &lt;/div&gt;<br>&lt;/div&gt;<br>```</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mNH_7Oq892HW-5XzkqfHoA.png" /></figure><h3>Responsive UI</h3><p>Building a responsive UI couldn’t be easier with the class prefixes sm:, md:, lg:, xl:, 2xl: and so on...</p><p>In my experience, I have found creating media queries a little bit of a pain when writing CSS, especially when I first started out creating responsive webpages. I would never know whether to use min-width or max-width. Media queries can be quite ugly in the code, and can just cause general confusion. Tailwind takes away a lot of the thinking behind making your webpage responsive.</p><p>Below is a comparison of how to make a button responsive using Tailwind vs your own CSS using media queries:</p><pre>&lt;!-- Tailwind --&gt;<br>&lt;button class=&quot;w-full md:w-10&quot;&gt;Click Me!&lt;/button&gt;</pre><pre>&lt;!-- CSS --&gt;<br>&lt;button class=&quot;my-button&quot;&gt;Click Me!&lt;/button&gt;<br>&lt;style&gt;<br>.button {<br>  width: 100%<br>}<br>@media screen and (min-width: 768px) {<br>  .button {<br>    width: 2.5rem<br>  }<br>}<br>&lt;/style&gt;</pre><h3>Downsides</h3><p>Though Tailwind is very useful for quickly spinning up an interface, it also comes with its downsides. In this section I will discuss what I dislike about Tailwind.</p><h4>Code Maintainability</h4><p>As you can see from the modal that we wrote earlier, Tailwind really bloats your HTML code, elements end up needing an exhaustive list of classnames. If you have multiple buttons you have to write out the classnames multiple times, leading to code duplication.</p><p>Maybe in the future you might want to change the colour of all of the buttons on your website, and you’ll find yourself looking through all the class names on all the buttons to change the colour, it just becomes a nightmare to maintain, and code reviews take longer. In these situations I find it easier to use CSS and have a button class which you can use on all your buttons.</p><p>If you’re using a modern Javascript framework, you could of course create a button component to remove this duplication, but I find when working with Tailwind creating a dynamic component can be awkward, and this brings me on to my next point…</p><h4>Dynamic Components</h4><p>I’ll use a button as an example again… It is common that a developer may build a dynamic button component to remove the duplication of writing buttons over and over again. This component will render different types of button and use different colours depending on the values of the props passed by the parent.</p><p>When using Tailwind I find that you end up using many conditionals in your HTML code. This again makes the HTML code bloated and harder to maintain.</p><pre>&lt;template&gt;<br>  &lt;button<br>    :class=&quot;{<br>      &#39;bg-green-700 text-white&#39; : btnType === &#39;primary&#39;,<br>      &#39;bg-red-700 text-white&#39; : btnType === &#39;danger&#39;,<br>      &#39;bg-yellow-700 text-black&#39; : btnType === &#39;warning&#39;<br>      &#39;bg-gray-200 text-black&#39; : btnType === &#39;secondary&#39;<br>    }&quot; <br>  &gt;Click me!&lt;/button&gt;<br>&lt;/template&gt;<br>&lt;script&gt;<br>  export default {<br>    props: {<br>      btnType: {<br>        type: String,<br>        default: &#39;primary&#39;,<br>        validator: (value) =&gt; [<br>          &#39;primary&#39;,<br>          &#39;danger&#39;,<br>          &#39;warning&#39;,<br>          &#39;secondary&#39;<br>        ].includes(value)<br>      }<br>    }<br> }<br>&lt;/script&gt;</pre><p>In the code snippet above, the button could be one of 4 colours dependent on the ‘btnType’ prop. We have 4 conditionals on the class attribute, and this is just for the colour, you may still want to style it differently dependent on other props.</p><pre>&lt;template&gt;<br>  &lt;button :class=&quot;btnType&quot;&gt;Click me!&lt;/button&gt;<br>&lt;/template&gt;<br>&lt;script&gt;<br>  export default {<br>    props: {<br>      btnType: {<br>       type: String,<br>       default: &#39;primary&#39;,<br>       validator: (value) =&gt; [<br>         &#39;primary&#39;,<br>         &#39;danger&#39;,<br>         &#39;warning&#39;,<br>         &#39;secondary&#39;<br>       ].includes(value)<br>     }<br>   }<br> }<br>&lt;/script&gt;<br>&lt;style lang=&#39;scss&#39; scoped&gt;<br>button {<br>  color: white;<br><br>  &amp;.primary {<br>    background: green;<br>  }<br>  &amp;.danger {<br>    background: red;<br>  }<br>  &amp;.warning {<br>    background: yellow;<br>    color: black;<br>  }<br>  &amp;.secondary {<br>    background: gray;<br>    color: black;<br>  }<br>}<br>&lt;/style&gt;</pre><p>Though this example is longer than the Tailwind example, it is much more readable and it is easy to style each button variant exactly how you want it, without having to write any conditionals. It is also much easier to add :before and :after pseudo elements if you need to.</p><h3>Conclusion</h3><p>I think Tailwind would be a good choice for prototyping an application, and on future projects I would use Tailwind again if the project had a short turnaround because the component library as well as not having to worry about CSS saves a lot of time on building the UI, leaving more time to focus on the frontend functionality and the backend. However, if time is no concern, I would prefer to style using CSS or SCSS to make my code more readable and maintainable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=205febbab782" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>