<?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 Mike Schouw on Medium]]></title>
        <description><![CDATA[Stories by Mike Schouw on Medium]]></description>
        <link>https://medium.com/@mike.schouw?source=rss-6fada95ea51a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xiiBKbKjnseJmjfKm5U0vA.jpeg</url>
            <title>Stories by Mike Schouw on Medium</title>
            <link>https://medium.com/@mike.schouw?source=rss-6fada95ea51a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:08:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mike.schouw/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[How I Skipped SQL and Went All-In on DynamoDB for FlightMessenger’s Stats Feature]]></title>
            <link>https://medium.com/@mike.schouw/how-i-skipped-sql-and-went-all-in-on-dynamodb-for-flightmessengers-stats-feature-5323b7567b35?source=rss-6fada95ea51a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5323b7567b35</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[dynamodb]]></category>
            <dc:creator><![CDATA[Mike Schouw]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 15:06:55 GMT</pubDate>
            <atom:updated>2025-07-17T17:52:13.433Z</atom:updated>
            <content:encoded><![CDATA[<p>Last month, I launched my favorite feature for FlightMessenger yet: calculating statistics for all the flights a user has tracked with the app. But here’s the twist: I used no SQL and built it using DynamoDB’s NoSQL magic to keep things fast, scalable, and fun.</p><p>In this blog, I’ll break down why I skipped SQL, how I implemented this on AWS with DynamoDB Streams and Lambda, the advantages of this setup, and a few limitations I’ve encountered along the way.</p><h4>What is FlightMessenger?</h4><p>If you have no idea what FlightMessenger is, here’s a quick elevator pitch for my small side project.</p><p>FlightMessenger is a tool that you can use to transform your flight number into a meaningful message that you can share with your loved ones. This message contains all the information they need to stay up to date with your departure and arrival times, a live tracking link, and general information about your flight, such as the airplane, airline, and aircraft type.</p><p>So far, over 150 messages have been generated with FlightMessenger, and now, you can also see statistics of all the flights you have tracked!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z7JKoBsAOMv2FT2uBhz96w.png" /><figcaption>A preview for the user of their key statistics</figcaption></figure><h4>The Technical Implementation on AWS</h4><p>The key to making statistics work without SQL is DynamoDB Streams. If you’re unfamiliar with this concept:, it’s basically a feature where DynamoDB sends events whenever there’s a PUT, UPDATE, or DELETE operation on the table.</p><p>So, how does this work out in FlightMessenger?</p><p>It is actually quite simple: All the flights a user tracks are stored in a single DynamoDB table. I enabled DynamoDB Streams on this table and routed the events to a Lambda function called stats-processor. That means whenever a new flight is added, an existing one is updated, or one is removed, the stats-processor receives the event and then processes it accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xccmeaDBxCihzVkj7AApdA.png" /></figure><h4>Coding the statistics calculation</h4><p>For calculating the statistics, my approach is to store details, like counts of airlines flown or countries visited, in a separate DynamoDB table. I update these values incrementally each time there’s a change to the user’s flights.</p><p>In this statistics table, everything is organized with the userId as the primary key (pk) and the specific metric as the sort key (sk).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YEdZdsAflQHdqTpWiPmIKw.png" /><figcaption>Example user with all their statistics tracked in the DynamoDB table</figcaption></figure><p>As of this writing, the following metrics, and thus also the following sort keys, are used:</p><ul><li>detailed#aircrafts</li><li>detailed#airlines</li><li>detailed#airports</li><li>detailed#countries</li><li>detailed#continents</li><li>detailed#routes</li><li>detailed#time</li><li>summary</li></ul><p>All the detailed# metrics follow a similar structure: the main entry holds general info about that aspect, plus a map with detailed breakdowns.</p><p>To illustrate, let’s look at the definition of countries :</p><pre>DetailedCountries struct {<br>  Countries            map[string]CountryStat `json:&quot;countries&quot; dynamodbav:&quot;countries&quot;`<br>  DomesticFlights      int                    `json:&quot;domesticFlights&quot; dynamodbav:&quot;domesticFlights&quot;`           // count of domestic flights<br>  InternationalFlights int                    `json:&quot;internationalFlights&quot; dynamodbav:&quot;internationalFlights&quot;` // count of international flights<br>  MostVisitedCountry   string                 `json:&quot;mostVisitedCountry&quot; dynamodbav:&quot;mostVisitedCountry&quot;`<br> }<br><br> CountryStat struct {<br>  Count        int      `json:&quot;count&quot;`<br>  Emoji        string   `json:&quot;emoji&quot;`<br>  DatesVisited []string `json:&quot;datesVisited&quot;` // [2025-01-01, 2025-01-02, 2025-01-03]<br>  CountryCode  string   `json:&quot;countryCode&quot;`<br>  AirportCount int      `json:&quot;airportCount&quot;`<br>  AirportCodes []string `json:&quot;airportCodes&quot;` // [FRA, MUC, DUS] <br> }</pre><p>For each country, we store how often it has been visited, which dates the user has visited this country, which airports in this country the user has visited and more.</p><p>This happens similarly for other entities, such as airports, airlines and, aircraft.</p><h4>Why not SQL?</h4><p>The traditional approach for calculating metrics like this would be to use SQL. Running selects, counts, and joins to calculate all the numbers you want from a relational database.</p><p>It’s a method that I know works, especially if you’re dealing with structured data like flights. However, I wanted to challenge myself and see if I could do it differently, completely avoiding SQL for this feature.</p><p>But why? First, relational databases can get expensive at scale. Imagine a user tracking hundreds or thousands of flights, running complex queries with joins across tables for airlines, countries, and routes every time they want stats could slow things down, especially during peak times. You’d need to provision servers to handle the load, and as a solo dev on a side project, I didn’t want to deal with managing an always-on database or paying for idle capacity.</p><p>Instead, I was already using DynamoDB (a NoSQL database), so why not use Streams? This lets me process changes in real-time without heavy queries, keeping everything lightweight and cost-effective. Sure, it means more upfront design work, but it fits my goal of building something efficient and fun to experiment with. Plus, if I ever need to change it, DynamoDB’s flexibility makes it easier than refactoring a bunch of SQL schemas in my opinion.</p><p>In the end, this approach feels more modern and aligned with FlightMessenger’s style: quick, scalable, and low-maintenance. But hey, if SQL ever makes sense for another feature, I might give it a shot!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*E29RZD-GG3fXsRsd6Mm4EA.png" /><figcaption>Detailed statistics per airline — KLM for example</figcaption></figure><h4>Advantages of this setup</h4><p>Besides not having to spin up an RDS database for this, there are more benefits to this setup:</p><ul><li>Calculating incremental updates to the statistics is relatively cheap, it usually just involves adding a few counts or appending the current date to a list.</li><li>It’s all handled in real-time by the Lambda function, so users see updated stats instantly, without me needing to run massive batch jobs. Plus, DynamoDB’s pay-per-request pricing keeps costs low!</li><li>Another big win is scalability: as more users start tracking flights, the streams and Lambda handle the load automatically</li><li>And lastly, querying the data is super fast because everything’s pre-computed. No more scanning entire tables or calculating metrics on the spot!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ViTXJ_hXuKPcsX87ledOSA.png" /><figcaption>Top 3 most visited airports</figcaption></figure><h4>Disadvantages of this setup</h4><p>Of course no setup or design comes without its disadvantages, here are just a few I noticed over the past weeks working with this setup:</p><ul><li>Calculating ‘new’ metrics is an expensive and time-consuming operation, since all operations are calculated incrementally. If I want to track some completely new feature, I have to reprocess all flights of that user to calculate the feature. This requires writing a time-consuming, one-off script to backfill the data.</li><li>I also calculate metrics around the ‘longest’ or ‘shortest’ flights for example. This is all fine, until users start deleting flights. If the ‘longest’ flight gets deleted, then I’ll have to recheck all flights again to determine which one is the new longest flight. Whereas<strong> </strong>with SQL for this, it would be a simple query.</li><li>If there’s ever a bug in the Lambda processor, it could lead to inconsistent or missing stats, and I had to add error-handling or retries to make it more robust.</li><li>There is also a concurrency issue that I haven’t tackled yet. When there are multiple flights from the same user that are being inserted (for example when the user is batch importing previous flights), normally the Lambda automatically scales to multiple concurrent executions. However, that also means that race conditions can develop and some statistics are lost when they are overwritten by each other. The solution for now is to limit the concurrent invocations of the stats-processor Lambda to 1. However, for the future, I’ll need to develop a more robust solution to this problem</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bvGHtMXak4hhy3RGF75Daw.png" /><figcaption>Most visited countries</figcaption></figure><h4>What’s Next?</h4><p>There are still a few statistics I’d like to add later on, but first, I’m focusing on other features (like importing flights, earning badges, and visualizing flights on a map). Some stats on the roadmap include the total CO2 emissions from a user’s flights and total delay time broken down by airport, airline, country, and continent!</p><p>You can try out the feature for yourself at flightmessenger.co. I can’t wait for you to give it a spin and let me know what you think!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5323b7567b35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building FlightMessenger: A Serverless Aviation App for Travelers]]></title>
            <link>https://medium.com/@mike.schouw/building-flightmessenger-a-serverless-aviation-app-for-travelers-fc4eee1f7495?source=rss-6fada95ea51a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc4eee1f7495</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[flightmessenger]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ephemeral-environment]]></category>
            <dc:creator><![CDATA[Mike Schouw]]></dc:creator>
            <pubDate>Wed, 21 May 2025 09:28:53 GMT</pubDate>
            <atom:updated>2025-05-21T09:28:53.605Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kulymzNZxR_AgzEPOwADig.png" /></figure><p>Have you ever sent a text message that goes something like this? “I’m on flight KL1234 today at 2 PM”?</p><p>While this conveys the basic information, it leaves your friends and family needing to search online for details about your departure time, arrival time, and flight status.</p><p><a href="https://flightmessenger.co/?utm_source=flight_message&amp;utm_medium=social&amp;utm_campaign=medium&amp;utm_content=aws+setup+blog">FlightMessenger</a> solves this problem by transforming simple flight numbers into comprehensive, personalized messages with all the details your loved ones need, including real-time tracking links so they can stay updated on your journey.</p><p>As someone passionate about both travel and aviation, I wanted to create a tool that bridges the gap between technical flight data and human-readable communication. The result is FlightMessenger: a web app that allows travelers to share detailed flight information with just a few clicks.</p><p>In this article, I’ll walk you through how I built <a href="https://flightmessenger.co/?utm_source=flight_message&amp;utm_medium=social&amp;utm_campaign=medium&amp;utm_content=aws+setup+blog">FlightMessenger</a> using AWS serverless architecture and implemented ephemeral environments to streamline development.</p><h3>The Stack: AWS Serverless Architecture</h3><p>When building <a href="https://flightmessenger.co/?utm_source=flight_message&amp;utm_medium=social&amp;utm_campaign=medium&amp;utm_content=aws+setup+blog">FlightMessenger</a>, I opted for a serverless architecture because I was already familiar with it from my professional work, and it allows you to develop very quickly, with nearly zero costs</p><p>Here’s a high-level overview of <a href="https://flightmessenger.co/?utm_source=flight_message&amp;utm_medium=social&amp;utm_campaign=medium&amp;utm_content=aws+setup+blog">FlightMessenger</a>’s architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MsBLCFEDPGqBsCaTMRbBtg.png" /><figcaption>FlightMessenger AWS platform overview</figcaption></figure><p>People familiar with the AWS Serverless stack will find little surprises here. It uses the fairly standard setup with CloudFront, API Gateway, Lambda &amp; DynamoDB. Lets look at the components in more detail.</p><h3>The Components of FlightMessenger</h3><h4>Frontend: Static Site Hosted on S3 + CloudFront</h4><p>The FlightMessenger user interface is built with React, allowing me to host it on Amazon S3 with CloudFront as a CDN. The advantage of CloudFront as a CDN is that it delivers content with low latency regardless of a user’s location.</p><p>Deploying a new version of the website is as easy as: building the new package, syncing it to S3 and invalidating the cache. This means that I can push a new version of the website to the world in under 1.5 minutes!</p><h4>Auth: Cognito for User Registration/Login</h4><p>User authentication is a critical component of any modern web application, and rather than building this system from scratch, I leveraged Amazon Cognito for FlightMessenger.</p><p>Cognito provides a robust, secure solution for user management with a generous free tier that’s perfect for projects at this scale.</p><p>In FlightMessenger’s architecture, Cognito serves two essential functions:</p><ul><li>User Management: It handles the entire user lifecycle: registration, email verification, password resets, and profile updates.</li><li>API Authorization: Cognito integrates directly with API Gateway to authorize requests, ensuring only authenticated users can access protected endpoints.</li></ul><p>The game-changer for development velocity was Cognito’s “managed login” feature. Instead of building custom authentication interfaces, Cognito provides ready-to-use, brandable pages for login, registration, and multi-factor authentication.</p><p>This single feature eliminated weeks, if not months, of development work, allowing me to focus on FlightMessenger’s core functionality rather than authentication flows.</p><p>I’ll dive deeper into the Cognito configuration, including custom domains for ephemeral environments and user pool management, in a dedicated future blog post.</p><h4>Backend APIs: Lambda with API Gateway</h4><p>The core functionality of FlightMessenger is powered by AWS Lambda functions written in Go. These functions handle everything from flight data retrieval to message generation and updating user preferences.</p><p>For the flight data, I’m currently using <a href="https://www.flightaware.com/aeroapi/portal/documentation#overview">AeroAPI</a>, which is a product of FlightAware. The API gives me all the relevant details, such as departing and arriving airport, distance, timings and aircraft and airline information.</p><p>Unfortunately, AeroAPI does not provide any historical information for a fair price, which means that I’m currently not able to process any flights in the past. I have yet to find an API that provides me without paying $500 each month, so if you have any recommendations, I’m all ears!</p><h4>AI: Bedrock</h4><p>I mean, did you really expect a SaaS in 2025 to not have AI in there? 😉</p><p>I don’t want to contribute to the AI-hype and call this an ‘AI-powered app’, but there is a sprinkle of some GenAI in there.</p><p>Currently, when the flight message is generated, I let Bedrock create a 1 paragraph summary of all the flight details, and add a fun fact about the destination. For an example, see below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*4NOweadMaagMSLeJ" /></figure><p>I’m currently using the <em>anthropic.claude-instant-v1</em> model, with the following prompt:</p><pre>`The flight information below is for a message I&#39;m sending to loved ones about my upcoming flight.<br><br>Please generate:<br>1. 👋 A greeting in the OFFICIAL language of the DESTINATION COUNTRY (not the departure country). Use this format: &quot;[Wave emoji] [Greeting appropriate for current time of day in that language]!&quot;<br>   - For example: &quot;👋 Bonjour!&quot; for France, &quot;👋 Namaste!&quot; for India<br>   - If the flight is domestic (same country for departure and arrival), use the country&#39;s official language<br>   - Include the country code of the destination in your analysis: %s<br><br>2. A brief one-line summary of my flight starting with &quot;I&#39;m flying from...&quot; or similar phrase. Include details about the duration, airline and aircraft type as well.<br><br>3. A short interesting fact about the destination city starting with &quot;Fun fact: ...&quot;<br><br>Separate each response with a newline. The summary and fun fact must be in English only.<br><br>Do NOT include phrases like &quot;Enjoy your flight&quot; or &quot;Safe travels&quot; since the recipients are not the ones traveling.<br><br>Flight details:<br>- Departing airport: %s (Country: %s)<br>- Destination airport: %s (Country: %s)<br>- Flight time: %s<br>- Airline: %s<br>- Aircraft type: %s<br>- Flight number: %s`</pre><p>This combination of prompt &amp; model has served me well over the past months, but I’ll make some time in the future to explore new possibilities and improvements!</p><h4>Persistence: DynamoDB</h4><p>Amazon DynamoDB serves as the primary database for FlightMessenger. The application uses six specialized tables</p><ul><li>Users Table: Stores profiles, preferences, and authentication metadata</li><li>User Flights Table: Tracks flights registered by each user with a composite key structure</li><li>Flight Archive: Contains comprehensive historical flight data with additional metadata</li><li>Airlines Reference: Global airline information including codes and logos</li><li>Airports Reference: Worldwide airport data with location coordinates and timezones</li><li>Country Emoji Mappings: Links countries to their flag emojis for message personalization</li></ul><h4>Observability: CloudWatch</h4><p>Like most applications that run on AWS and don’t have a million bucks behind it, I do all of my monitoring in CloudWatch. This means using CloudWatch Logs as.. well.. logs, and publishing custom metrics to show interesting dashboards.</p><p>This is an area that hasn’t received a lot of attention yet, and I’ll write a new blog if there are any new developments here.</p><h4>Email: SES</h4><p>I usually avoid email as long as possible, but I was quite surprised how easy it was to setup SES.</p><p>The app uses SES primarily for the flight reminder feature, which sends a timely notification on your departure day, reminding you to share your travel details before takeoff. Implementation was remarkably straightforward:</p><ul><li>Create an HTML email template with variable placeholders</li><li>Expose an API endpoint, which triggers a Lambda to create a Eventbridge Schedule</li><li>On the schedule hit, trigger a Lambda, which fetches all the required information from DynamoDB</li><li>Use the SES SDK to send personalized reminders</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0yDBRL7Au1oLZnWCPZrozA.png" /></figure><h4>Alerting: Discord</h4><p>After seeing this video from <a href="https://www.youtube.com/watch?v=txlPgQ3NbYg"><em>Josh tried coding</em></a><em> </em>on Youtube, I set out to build an alerting system using Discord Webhooks.</p><p>I built a small, sharable Go package that can send various events to the webhook URL. I can import this package in the application code and give if it needs to be send using an INFO, WARN or ERROR level, which service has sent the message and some extra information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*ZUlLrPwwbzafdHPdPsRC6A.png" /></figure><h3>Ephemeral Environments via Branching Strategies</h3><p>One of the most valuable development practices I implemented for FlightMessenger was ephemeral environments. After working with this approach for over 4 years across multiple projects, I’ve found it to be a game-changer for development productivity and velocity.</p><h4>What Are ‘Ephemeral Environments’ and how does it work?</h4><p>Ephemeral environments are completely isolated environments from your ‘main’ environment that exist only for the duration of a feature’s development cycle. This means that each feature branch in the FlightMessenger repository, I spin up a 100% copy of the stack that is running in production.</p><p>Ephemeral environments are made possible because of the serverless technologies. Since serverless resources don’t cost any money when they are not used, you’re free to spin up multiple of copies of your production environment to test your changes and only pay for what you use.</p><h4>How I Set It Up</h4><p>For FlightMessenger, I implemented ephemeral environments using the following approach:</p><ul><li>Branch-based triggers: Creating a new feature branch automatically triggers the provisioning process</li><li>Naming convention: Resources follow a pattern like <em>lambda1-feature-branch-name. </em>This naming strategy not only keeps resources organized but also makes it immediately clear which branch a particular resource belongs to when troubleshooting.</li><li>Infrastructure as Code: Using Terraform to define and deploy all the resources</li></ul><p>Which means that my CI/CD pipelines (using GitHub Actions) perform these steps:</p><ul><li>Each branch has their own Terraform workspace, which means they have completely isolated state files</li><li>Build all the changed binaries for the Go code. (If you’re interested in a guide on how to build reproducible Go builds, <a href="https://medium.com/@mike.schouw/reproducible-golang-builds-in-azure-pipelines-for-aws-lambda-f9fcb1217180">you can check out my other blog here</a>)</li><li>For the new or existing workspace, deploy all resources that are requested</li><li>Run the full test suite against the isolated, ephemeral environment</li></ul><p>I might hear you think, “That sounds great, but there must also be some downsides, right?”</p><p>Yes, of course, each solution has it downsides. Most importantly, if you’re running a large project this way, you have to consider things like:</p><ul><li>Running into AWS resource limits: Each AWS account has quotas that can quickly become constraints. In other projects, I’ve encountered this with IAM roles, S3 buckets and API Gateway stages, requiring occasional limit increase requests to AWS support.</li><li>Cleaning up your unused feature environments (I do this using a tool called <a href="https://github.com/ekristen/aws-nuke">aws-nuke</a>, which can wipe your whole AWS environment in mere minutes)</li><li>Dealing with services that are not fully serverless, or dont scale down to 0 automatically when not in use. (ECS, for example)</li><li>Accepting that your AWS environment becomes a bit more cluttered when having multiple environments deployed at the same time.</li></ul><h3>Lessons Learned, Challenges and the Future of FlightMessenger</h3><p>Building FlightMessenger with AWS serverless architecture and ephemeral environments has been very enjoyable. I can test features independently without worrying about conflicts or destabilizing the production environment. What’s most impressive is how quickly it can go from concept to testing, typically under 5 minutes from pushing code to having a fully functional environment to test against.</p><p>From a cost perspective, the numbers speak for themselves:</p><ul><li>Monthly AWS bill for development: ~$1.30</li><li>Monthly AWS bill for production: ~$1 with current traffic levels</li></ul><p>This efficiency means I can experiment freely without budget constraints. Something that would be a lot harder with traditional server-based architecture.</p><h4>Future Roadmap</h4><p>Looking ahead, I’m planning several technical enhancements to FlightMessenger:</p><ul><li>User statistics: generating interesting statistics on all tracked user’ flights, such as the most visited airport, amount of flights per year, etc.</li><li>Import and export of data: statistics become a lot more fun when you can also enter your non-tracked FlightMessenger tracked flights.</li><li>Enhanced observability: Moving beyond basic CloudWatch to implement distributed tracing with AWS X-Ray</li><li>Alternative flight data providers: Investigating options for historical flight data that won’t bankrupt me. This will also allow me to more easily import old data from the users.</li></ul><p>If you’re interested in trying <a href="https://flightmessenger.co/?utm_source=flight_message&amp;utm_medium=social&amp;utm_campaign=medium&amp;utm_content=aws+setup+blog">FlightMessenger</a> for yourself, visit <a href="https://flightmessenger.co/">https://flightmessenger.co</a> to create an account and start sharing your flight details with loved ones in a much more helpful format.</p><p><strong>I’m planning to write more technical articles about specific aspects of FlightMessenger’s development, including:</strong></p><ul><li>How to track user metrics with Posthog</li><li>Self-hosting GitHub Action runners in Kubernetes</li><li>Using Cognito’s managed login feature to easily create all required auth pages</li><li>Implementing ephemeral environments with Terraform workspaces</li></ul><p><strong>What aspects of FlightMessenger’s architecture would you like to learn more about? Let me know in the comments!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc4eee1f7495" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scheduling events in AWS in a Serverless way - Pt1. EventBridge]]></title>
            <link>https://medium.com/@mike.schouw/scheduling-events-in-aws-in-a-serverless-way-pt1-eventbridge-b057f5859c9f?source=rss-6fada95ea51a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b057f5859c9f</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[event-scheduling]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Mike Schouw]]></dc:creator>
            <pubDate>Fri, 03 May 2024 13:09:57 GMT</pubDate>
            <atom:updated>2024-05-03T13:09:57.792Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bW7FDh4deahvTEykucHvrA.jpeg" /></figure><p>In this series of blog posts, I’m going to take you through different <strong>AWS services</strong> that can <strong>schedule events in</strong> some form, the <strong>serverless</strong> way. In this first edition, we’ll be taking a deeper look into <strong>AWS EventBridge</strong>.</p><p>In each blog post, we’ll test the ability of each service to schedule events, based on three scenarios. These scenarios are <strong>a single event, an hourly event, and second-level accuracy events</strong>. We’ll also evaluate if the solution <strong>scales</strong>, and how much it <strong>costs</strong> to use this service for each scenario.</p><h4>What is EventBridge: A Quick Introduction</h4><blockquote>Amazon EventBridge is a serverless event bus service that makes it easy to connect your applications with data from a variety of sources. EventBridge delivers a stream of real-time data from your applications, software-as-a-service (SaaS) applications, and AWS services and routes that data to targets such as AWS Lambda. You can set up routing rules to determine where to send your data to build application architectures that react in real-time to all of your data sources. EventBridge enables you to build event-driven architectures that are loosely coupled and distributed.</blockquote><p><a href="https://docs.aws.amazon.com/eventbridge/"><em>Source: AWS</em></a></p><p>Some key components of EventBridge that are important for this blog include the Event Bus, Rules &amp; Scheduler.</p><p><strong>Event Bus</strong>: “<a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-event-bus.html">A router that receives events and delivers them to zero or more destinations, or <em>targets</em></a><em>”</em></p><p><strong>Rules</strong>: “<a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-rules.html">To specify what EventBridge does with the events delivered to each event bus, you create <em>rules</em></a><em>”</em></p><p><strong>Scheduler</strong>: “<a href="https://docs.aws.amazon.com/scheduler/latest/UserGuide/what-is-scheduler.html">A serverless scheduler that allows you to create, run, and manage tasks from one central, managed service</a>”</p><h4>Scenario 1: Scheduling a single-time event to invoke a Lambda</h4><p>Let’s start with the most basic scenario, we have to schedule a one-off event to invoke a Lambda, tomorrow at 13:00. This can be solved by EventBridge Scheduler. This service enables you to schedule events at a certain time, or on a certain schedule (which can be cron-based or rate-based).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*b6mFfXak01t85rCeYO1qWQ.png" /></figure><p>After going to the next page, EventBridge allows you to send this event to an AWS service, without having to write the integration for this.</p><p><em>Sweet</em>!</p><p>They offer the choice between templated targets that are often used, or a choice of all API integrations currently available, which at this time of writing is an impressive 320+ available integrations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*Vo6ViqCuIaujW8qRyeZw8w.png" /></figure><p>This is exactly what we need. Now, if you create these schedules more often, there is one problem that you run into: the schedules that are in the past and executed are piling up in your account, cluttering your environment.</p><p>AWS has thought of this, as they provide the option to have the schedule <a href="https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-schedule-delete.html">delete itself after completion</a>. Additionally, EventBridge scheduler also offers retry mechanisms, DLQ integration, and encryption using CMKs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*7oMQCkLEyxJ926LNMuLODg.png" /></figure><p><strong>Costs: </strong>The first 14 <strong>million</strong> invocations per month are free. After that, you pay $1.15 (eu-central-1) per 1 million invocations.</p><h4>Scenario 2: Send a message to SNS, every hour.</h4><p>It seems that EventBridge Scheduler is the right tool for the job again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*3-m7gXj6hqyoxxYz_m2X2A.png" /></figure><p>When you want to create a recurring event, there are two options: cron-based and rate-based. With rate-based events, you can schedule them to happen every X minute, hour, or day. If you need more specific control, such as on which time to run the event or only run it on a specific day, the cron-based schedule is your best friend.</p><p>For our scenario, the rate-based event is the perfect fit. We set the rate at 60 minutes, define the event that we want to send to SNS, and put the correct topic as the destination.</p><p><strong>Costs: </strong>The first 14 <strong>million</strong> invocations per month are free. After that, you pay $1.15 (eu-central-1) per 1 million invocations. Since our schedule runs every hour, we invoke this schedule 731 times (for an average month) per month. This is within the Free Tier, so it would cost us $0.00.</p><h4>Scenario 3: Scheduling events with second-level accuracy, sending them through Lambda</h4><p>Now, this is where the trouble starts for EventBridge. EventBridge is great for scheduling one-time &amp; recurring events, but when you need to schedule events with second-level accuracy, EventBridge comes up short. All methods of scheduling that we discussed before allow you to schedule events up to the minute.</p><p>So, for this, we would be looking at more custom solutions. Let’s make an example.</p><p>I have to make an HTTP call to a client using AWS Lambda. But, when the client doesn’t respond, I have to adhere to a retry schedule. Each time the client doesn’t respond, the waiting time increases to make sure we don’t overload the client with requests. This will go as follows:</p><ul><li>5 seconds; then</li><li>10 seconds; then</li><li>30 seconds; then</li><li>1 minute; then</li><li>5 minutes; then</li><li>10 minutes</li></ul><p>Using EventBridge the last 3 parts of the retry schedule are easily done. We create a schedule that is 1, 5, or 10 minutes from now that will invoke the Lambda. If the client still doesn’t respond, Lambda creates a new schedule with the next waiting time and this is repeated until the schedule is done.</p><p>However, for the first three parts, we have to get more creative. The easy solution would be to handle this in the Lambda itself. We would wait for 5 seconds for the client to respond. If there is no response, we send it again and wait for 10 seconds again. And repeat.</p><p>One problem with this solution is that we just created a Lambda anti-pattern: <a href="https://docs.aws.amazon.com/lambda/latest/operatorguide/synchronous-waiting.html">Synchronous waiting within a single Lambda function</a>. Therefore, this solution will not be suitable.</p><p>Unfortunately, it seems like this problem is not solvable if we only want to keep using EventBridge, and don’t want to implement any anti-patterns in Lambda. We have to use different AWS services to solve this problem (such as Step Functions, SQS, or others. <em>Stay tuned for the next blog in this series</em>)</p><p><strong>Costs: </strong>The first 14 <strong>million</strong> invocations per month are free. After that, you pay $1.15 (eu-central-1) per 1 million invocations. Since we cannot satisfy the first part of the retry schedule, we can maximally create 3 schedules per retry (1, 5 &amp; 10 minutes). Therefore, to stay within the Free Tier, we create this pattern 4.6 million times per month.</p><h4><strong>BONUS</strong>: Does it scale?</h4><p>Since we are only using EventBridge Scheduler, we’ll only consider this part of EventBridge. Let’s look at the most important quotas</p><ul><li>We can create 50 schedules per second</li><li>We can have 500 invocations from a schedule per second</li><li>We can have 1,000,000 million schedules at the same time.</li></ul><p><em>Note: all these limits are adjustable. Source: </em><a href="https://docs.aws.amazon.com/scheduler/latest/UserGuide/scheduler-quotas.html"><em>AWS</em></a></p><p>So, does it scale?</p><p>Yes</p><p>But also not that much.</p><p>If you are keeping the default quotas, it is easy to see how you would reach the ‘50 scheduled creations per second’ quota. Especially if your platform is built to handle hundreds of events per second.</p><p>Therefore you should be aware of the quotas if you adopt EventBridge Scheduler in your platform if there is a chance you’ll be hitting the quotas easily. If you think you’ll hit these quotas easily, reach out to AWS Support to have the quotas raised.</p><h4>So, EventBridge, yay or nay?</h4><p>While EventBridge offers powerful capabilities for scheduling events in a serverless environment, it’s important to recognize its strengths and limitations. EventBridge shines when you don’t need to have second-level accuracy for scheduling (recurring) events, especially with the introduction of EventBridge Scheduler.</p><p>However, if you’re looking for a way to schedule events on a second-level granularity, EventBridge will not satisfy your needs.</p><p>Stay tuned for the next edition of this series, where we’ll explore a service that you might not expect in this series around scheduling serverless events: <strong>SQS</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b057f5859c9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why every IT Engineer should have a HomeLab]]></title>
            <link>https://medium.com/@mike.schouw/why-every-it-engineer-should-have-a-homelab-3d1be31b1cb7?source=rss-6fada95ea51a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d1be31b1cb7</guid>
            <category><![CDATA[diy]]></category>
            <category><![CDATA[it]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[homelab]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mike Schouw]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 09:13:51 GMT</pubDate>
            <atom:updated>2024-04-25T09:13:51.467Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explore, Experiment &amp; Excel: <strong>The Role of HomeLabs in IT Skill Development</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ltEkf2pvdnCa9c3VnvjIog.jpeg" /></figure><p>Ever feel like you’re just scratching the surface of what you could achieve in the IT world? Or have you always wanted to try new technologies and services but don’t know where to run them?</p><p>Well, get ready because we’re about to talk about something that could change the game for you: HomeLabs. Yep, it’s like having your own tech playground, and spoiler alert: it’s awesome. Curious? Let’s discover why every IT engineer should have their own HomeLab</p><h3>What is a HomeLab?</h3><p>A HomeLab is your very own tech playground, where you have the freedom to explore, experiment, and learn about cutting-edge (or older!) technologies right from the comfort of your home. It’s like having a DIY lab where you call the shots and set the rules.</p><p>At its core, a HomeLab can be as simple as using your personal laptop or repurposing that Raspberry Pi you bought some time ago. These entry-level setups are perfect for dipping your toes into the world of IT tinkering, allowing you to experiment with basic configurations and software installations.</p><p>However, if you’re ready to take your HomeLab to the next level, investing in a dedicated machine that can run 24/7 opens up a world of possibilities. This machine can host virtual machines (VMs) and containerized applications. With this setup, you’re not just playing around; you’re building a robust testing environment that can mirror real-world scenarios.</p><p>Now, let’s talk scalability. Interested in diving into the world of Kubernetes and container orchestration? Why stop at one machine when you can have two, three, or more? By expanding your HomeLab setup, you can create a highly available environment for experimenting with complex distributed systems. It’s like having your own mini data center, minus the hefty price tag.</p><h3>Advantages of a HomeLab</h3><h4>Hands-On Knowledge</h4><p>When it comes to the IT field, hands-on experience is (in my opinion) more important than any theoretical knowledge that you have accrued. While theoretical knowledge lays the foundation, it’s the ability to apply that knowledge in real-world scenarios that sets IT professionals apart. With a HomeLab, bridging the gap between theory and practice becomes effortless.</p><h4>Skill Development</h4><p>Think of your HomeLab as your playground, where you hone your IT skills through hands-on practice. Whether you’re configuring networks, setting up servers, or troubleshooting software issues, every click and command contributes to your growth as an IT engineer. In the dynamic landscape of technology, continuous skill development is key, and a HomeLab provides the perfect platform for mastering new tools and technologies.</p><h4>Experimentation</h4><p>In the ever-evolving IT landscape, staying ahead of the curve means being comfortable with experimentation. Unfortunately, the constraints of a daily job may limit your exposure to new technologies. In my case, since my day job is heavily AWS-focused, I don’t get to play around that much with technologies such as Kubernetes, Hashicorp Vault, or Traefik. With the freedom to deploy, configure, and yes, even break, you gain invaluable insights that simply can’t be acquired through passive observation.</p><h4>Portfolio building</h4><p>Your HomeLab doesn’t have to be just a playground — it can also be a showcase of your skills and creativity. Whether you’re developing APIs, building webpages, or designing complex systems, each accomplishment adds depth and versatility to your portfolio. And when it comes time to impress potential employers, your HomeLab serves as a living testament to your passion for innovation and growth.</p><h3>How to start your HomeLab: <strong>From Raspberry Pi to Virtual Data Center</strong></h3><p>Starting with your HomeLab doesn’t have to be complex. You can always expand your setup later to have your own virtual data center at home 😉. Start with booting up that Raspberry Pi that you have lying around (or otherwise buy one second-hand for less than €50).</p><h4><strong>Upgrading Your Hardware</strong></h4><p>As you grow more comfortable with your HomeLab setup, you may find yourself craving more power and flexibility. The first step in upgrading is ensuring your home network can handle the load. Opt for wired connections wherever possible and consider investing in a reliable router like the <a href="https://eu.store.ui.com/eu/en/pro/products/udm">UniFi Dream Machine</a> for consistent performance.</p><p>Next, evaluate your hardware needs based on your aspirations. Are you content with hosting a media server on a single machine? Or do you dream of orchestrating Docker containers and experimenting with containerization technologies like Kubernetes? Depending on your ambitions, you may choose to expand your setup with more powerful machines or multiple nodes to create a robust infrastructure.</p><h4><strong>Keeping Costs in Check</strong></h4><p>While the dream of cutting-edge hardware may be tempting, it’s essential to keep costs in check, especially when building and expanding your HomeLab. Starting with a Raspberry Pi is a budget-friendly option, with second-hand units readily available for around €50.</p><p>When upgrading your hardware, energy consumption becomes aan important consideration. Since your HomeLab machines will likely be running 24/7, monitoring energy usage can help keep operational costs manageable. Opting for second-hand hardware can also be a great financial move, as it offers quality components at a fraction of the cost. Take it from me — I’ve built a robust Kubernetes cluster using Intel NUCs sourced from the second-hand market (for around €100 a piece), supplemented by a Raspberry Pi running Home Assistant.</p><h3>My Setup</h3><p>If you’re interested in my setup, this is what I currently have running:</p><h4>Hardware</h4><ul><li>1x Raspberry Pi</li><li>4x Intel NUC (8–16GB, Intel i3/i5, 256GB SSD) (3 for Kubernetes, 1 for Docker)</li><li>1x UniFi Dream Machine</li><li>2x UniFi Networking Switch</li></ul><h4>Technologies</h4><ul><li><strong>Kubernetes</strong> (managed with <strong>Helm</strong> &amp; <strong>Terraform</strong>) &amp; <strong>Docker / Podman</strong></li><li><strong>Traefik, Cert-Manager, CrowdSec, Oauth2 Proxy, MetalLB &amp; Lets Encrypt </strong>for hosting services &amp; routing and securing traffic</li><li><strong>Hashicorp Vault </strong>for secret management</li><li><strong>GitHub Action Runners </strong>for running my CI/CD workloads</li><li><strong>PiHole &amp; Blocky </strong>for DNS Filtering</li><li><strong>Gatus &amp; Uptime Kuma </strong>for uptime monitoring</li><li><strong>*arr stack, Jellyfin &amp; JellySeer</strong> for content management</li><li><strong>Renovatebot &amp; Watchtower</strong> for keeping dependencies up to date</li><li><strong>LittleLink, Dashdot &amp; Homepage</strong> for dashboards and link pages</li><li><strong>Prometheus, Grafana, Speedtest &amp; Alert-manager </strong>for observability</li><li><strong>FR24Feed </strong>for airplane monitoring</li><li><strong>ChaosKube</strong> for chaos engineering (personal favorite)</li></ul><p>As you can see, it’s quite the list! And this list can change at any time when I discover new or other technologies.</p><h3>Conclusion: Time To Get Started!</h3><p>If you’ve caught the HomeLab bug or found yourself itching to dive into the world of DIY tech experimentation, then my mission here is accomplished. The idea of HomeLabs isn’t just about tinkering with hardware and software — it’s about unlocking endless possibilities for learning and innovation right from the comfort of your own desk.</p><p>Personally, I’ve found immense inspiration from Tech YouTubers who share their HomeLab journeys. Allow me to recommend some of my favorites:</p><ul><li><a href="https://www.youtube.com/@TechnoTim">TechnoTim</a>: This guy is seriously next level, he even recently co-located a part of his HomeLab in an actual data center. My setup is highly inspired by his setup (although way, way, way less impressive 😅)</li><li><a href="https://www.youtube.com/@christianlempa">ChristianLempa</a>: Has a ton of videos regarding building, setting up, and expanding your HomeLab. Although I don’t use all of the same services, it is a great inspiration</li><li><a href="https://www.youtube.com/@NetworkChuck">NetworkChuck</a>: While not exclusively focused on HomeLabs, NetworkChuck’s mix of content includes some gems related to DIY tech setups. His enthusiasm for all things tech is contagious, making his videos a great addition to any IT enthusiast’s watch list.</li></ul><p>But wait, the HomeLab journey doesn’t end here! If you know of other great sources of inspiration or have burning questions about HomeLabs, I’m all ears. Let’s continue this conversation and learn from each other!</p><p>Let’s get building! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d1be31b1cb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to run OAuth2 Proxy with Traefik in Kubernetes, using Helm and Terraform]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@mike.schouw/how-to-run-oauth2-proxy-with-traefik-in-kubernetes-using-helm-and-terraform-85c39dddcd44?source=rss-6fada95ea51a------2"><img src="https://cdn-images-1.medium.com/max/711/1*mxaICLk_Z79cq8tTkeCTqg.png" width="711"></a></p><p class="medium-feed-snippet">Traefik stands out as a top choice for Kubernetes Ingress, particularly within the self-hosted community, where many opt for it as their&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@mike.schouw/how-to-run-oauth2-proxy-with-traefik-in-kubernetes-using-helm-and-terraform-85c39dddcd44?source=rss-6fada95ea51a------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@mike.schouw/how-to-run-oauth2-proxy-with-traefik-in-kubernetes-using-helm-and-terraform-85c39dddcd44?source=rss-6fada95ea51a------2</link>
            <guid isPermaLink="false">https://medium.com/p/85c39dddcd44</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[traefik]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Mike Schouw]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 11:12:49 GMT</pubDate>
            <atom:updated>2024-03-21T11:12:49.958Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Reproducible Golang Builds (in Azure Pipelines) for AWS Lambda]]></title>
            <link>https://medium.com/@mike.schouw/reproducible-golang-builds-in-azure-pipelines-for-aws-lambda-f9fcb1217180?source=rss-6fada95ea51a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9fcb1217180</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[azure-pipelines]]></category>
            <dc:creator><![CDATA[Mike Schouw]]></dc:creator>
            <pubDate>Tue, 22 Aug 2023 12:47:15 GMT</pubDate>
            <atom:updated>2023-09-11T19:09:41.370Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*21jt80ulIxwanvcAkJlkvg.png" /></figure><p>In the fast-paced software development world, ensuring the consistency and reliability of deployments is paramount. Currently, I’m managing multiple AWS Lambda functions through Terraform and deploying them to AWS accounts using Azure DevOps CI/CD pipelines. One challenge I encountered was the need for reproducible Golang builds for the Lambda functions. Because of the way Golang Lambda functions are managed, each CI/CD pipeline iteration redeployed all Lambda functions, cluttering the deployment pipelines and increasing the chance of unintentional changes slipping through to production environments. Introducing reproducible Golang builds would significantly declutter the pipelines and increase the production deployments’ consistency and reliability.</p><h4><strong>The AWS Lambda Golang Compilation Conundrum</strong></h4><p>When it comes to running Golang code for Lambda functions, AWS offers two runtime options: the Go 1.x runtime based on Amazon Linux AMI (al1), and the provided.al2 runtime based on the newer and more efficient Amazon Linux 2 AMI (al2). The shift towards provided.al2 is not only future-proof due to AWS’s ending support for Go 1.x, but it also provides the option to leverage the powerful AWS Graviton2 processor, leading to enhanced performance and cost savings.</p><p>One of the requirements for my project is to have consistent build artifacts throughout all environments, managed in a centralized location. Meaning that it is built once, stored centrally, and deployed to <a href="https://en.wikipedia.org/wiki/Development,_testing,_acceptance_and_production">DTAP</a> environments. Additionally, its not possible to compile Golang code using the provided.al2 runtime within the <a href="https://registry.terraform.io/modules/terraform-aws-modules/lambda/aws/latest">Terraform AWS Lambda module</a>. So, even without the requirement of storing our Golang binaries in a centralized place, I would have to compile our Golang code outside the Terraform module and later integrate it into the deployment process.</p><h4><strong>Sub-optimal Redeployments and Possible Downtime</strong></h4><p>The approach involved building Golang code in Azure Pipelines, storing it on an S3 bucket, and referencing it through the s3_existing_package parameter in the Terraform resource for Lambda. However, this seemingly straightforward solution introduced an unintended consequence: Azure Pipelines generates a new version of the Golang binary with every CI/CD pipeline run since a recompilation of the same code generates a new unique binary. This results in a new version uploaded to S3 and hence a fresh version_id. Since the Terraform Lambda module initiates a redeployment upon detecting a change in the version_id of the S3 object, each Azure Pipeline run triggers a new Lambda deployment.<br>This means that each Lambda module that is managed by Terraform creates and destroys multiple Terraform resources on each deployment. This invariably leads to a cluttered deployment pipeline, increasing the need for a more thorough review of the planned changes made by Terraform. And unfortunately, also increase the chance of missing critical unintended changes to your production environments.</p><h4><strong>A Path to Efficient Redeployments</strong></h4><p>To address this challenge, I embarked to find a solution for the problem by only triggering Lambda redeployments when the Golang function code had truly changed. The solution? Calculating a hash of the code and only uploading a new version to S3 when the hash has changed. However, merely comparing the hash of the compiled binary in each pipeline run proved insufficient because, in each pipeline run, the hash of the binary changed every time, even when the function code doesn’t change and the build environment setup is consistent.</p><h4><strong>Unveiling Reproducible Golang Builds</strong></h4><p>I considered various reasons why the initial solution did not work. Initially, my thought was that the environment variables in the Azure Pipeline environment played a role, since the only thing that changes between CI runs when the function code is identical, are the environment variables in Azure Pipelines. After careful review, I was able to rule that out by encountering the same problem in GitHub Actions and compiling locally. Which maybe meant the issue was with the the function code is managed. Then, I noticed that the same problem did not occur when the source code was copied into a Docker container and was compiled there, even after starting, stopping, and rebuilding the container multiple times. What is the difference? In my environments, the Golang function code is managed through version control, while compiling it in the Docker container, the code was simply copied in there.</p><p>The breakthrough emerged from a deep dive into the go build command and its associated flags. Specifically, two flags stood out as crucial components of the quest for reproducibility: trimpath and buildvcs.<br>- <strong>trimpath</strong>: This flag serves to trim all file system paths from the resulting executable. Instead of absolute file system paths, the recorded file names are either a module path@version (for module usage) or a plain import path (when relying on the standard library or GOPATH). The importance of trimpath becomes evident when file system paths exhibit variability between builds. While it might not be a silver bullet for every scenario, it could provide the solution for similar problems.<br>- <strong>buildvcs</strong>: This flag determines whether binaries should be stamped with version control information. Leveraging buildvcs and setting it to false ensures that no version control information is compiled into the binary, resulting in a consistent hash for the binary.</p><h4><strong>Putting Theory into Practice</strong></h4><p>Below you can find an example of how this implementation would work in Azure Pipelines. The Golang code is compiled with the -buildvcs=false and -trimpath parameters. Afterward, the hash is calculated and compared with what is stored on S3. If there is no change, there is no new version uploaded to S3, and therefore no redeployment of the Golang Lambda functions.</p><p>For my project, introducing reproducible builds led to a significant change. Previously, a simple infrastructure change (e.g., changing the name of an IAM Role) in Terraform led to a plan with 24 additions, 6 changes and 22 destroys. Over 90% of the proposed changes are redeployments of Lambda functions and its associated resources that should not have happened.</p><p>Currently, the deployment pipeline only indicates infrastructure changes that directly result from me changing Terraform or Golang code.</p><pre>jobs:<br>  - job: Build<br><br>    steps:<br>      - task: GoTool@0<br>        inputs:<br>          version: &quot;1.21&quot;<br><br>      - task: Go@0<br>        displayName: &quot;Build&quot;<br>        env:<br>          GOARCH: arm64<br>        inputs:<br>          command: build<br>          workingDirectory: &quot;$(System.DefaultWorkingDirectory)/golang/services/hello_world&quot;<br>          arguments: &quot;-o $(Build.BinariesDirectory)/hello_world/bootstrap -tags lambda.norpc -trimpath -buildvcs=false&quot;<br><br>      - task: ArchiveFiles@2<br>        displayName: &quot;Zip&quot;<br>        inputs:<br>          rootFolderOrFile: $(Build.BinariesDirectory)/hello_world<br>          archiveType: zip<br>          archiveFile: $(Build.ArtifactStagingDirectory)/hello_world.zip<br><br>      - task: AWSShellScript@1<br>        displayName: Compare hashes<br>        inputs:<br>          awsCredentials: $INPUT_FOR_AWS_CREDENTIALS<br>          regionName: $AWS_REGION<br>          scriptType: inline<br>          disableAutoCwd: true<br>          failOnStandardError: true<br>          workingDirectory: $(Build.BinariesDirectory)/hello_world<br>          inlineScript: |<br>            GOLANG_BINARY_HASH=$(shasum bootstrap | cut -d&#39; &#39; -f1)<br><br>            S3_METADATA=$(aws s3api head-object \<br>                      --bucket BUCKET_NAME \<br>                      --key go/hello_world.zip \<br>                      --query &#39;Metadata.sha256sum&#39; \<br>                      2&gt; /dev/null \<br>                      | tr -d &#39;&quot;&#39;)<br><br>            if [ &quot;$GOLANG_BINARY_HASH&quot; != &quot;$S3_METADATA&quot; ]; then<br>              echo &quot;Hashes are not equal between local ($GOLANG_BINARY_HASH) and S3 ($S3_METADATA), or object doesn&#39;t exist on S3. Syncing code to S3&quot;<br>              aws s3 cp hello_world.zip s3://BUCKET_NAME/go/hello_world.zip --metadata &quot;sha256sum=$GOLANG_BINARY_HASH&quot;<br>            else<br>              echo &quot;Hashes are equal. Not syncing to S3&quot;<br>            fi</pre><p>For a more complete example, including Terraform code and a version for GitHub Actions, you can check out <a href="https://github.com/MikeSchouw/reproducible-go-builds-example">this repository</a>.</p><h4><strong>Conclusion</strong></h4><p>In my quest to declutter my deployment pipelines by making sure Golang builds are reproducible, I discovered some optimizations in the build process that help prevent unnecessary redeployments. By using trimpath and buildvcs flags during Golang compilation, I found a way to create reproducible Golang builds for Lambda resulting in clearer pipelines and therefore reducing the risk of missing unintentional changes to critical infrastructure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9fcb1217180" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>