<?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[CAW Engineering Blogs - Medium]]></title>
        <description><![CDATA[CAW Studios is a Product Engineering Company of 100+ geeks based out of Hyderabad. We run engineering for other start-ups. - Medium]]></description>
        <link>https://medium.com/caw-engineering-blogs?source=rss----b077e345995d---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>CAW Engineering Blogs - Medium</title>
            <link>https://medium.com/caw-engineering-blogs?source=rss----b077e345995d---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:08:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/caw-engineering-blogs" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Vacuum Wars: PostgreSQL’s Quest for Optimization]]></title>
            <link>https://medium.com/caw-engineering-blogs/vacuum-wars-postgresqls-quest-for-optimization-3b8065319186?source=rss----b077e345995d---4</link>
            <guid isPermaLink="false">https://medium.com/p/3b8065319186</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[vacuum]]></category>
            <category><![CDATA[database-administration]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[CAW Blogs]]></dc:creator>
            <pubDate>Tue, 28 Mar 2023 07:00:34 GMT</pubDate>
            <atom:updated>2023-03-28T07:11:59.761Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By </em><a href="https://www.linkedin.com/in/prathapchandra/"><em>Prathap Chandra</em></a><em> (</em><a href="https://cawstudios.com/"><em>CAW Studios</em></a><em>)</em></p><p><em>We love PostgreSQL in CAW Studios. Its our go to DB when the product warrants a RDBMS. We have come across many surprises (and some shocks) as we explore the under-the-hood implementation of this awesome DB. We are starting a series where we share our learning with wider community. We hope you enjoy this blog which will be part of a series.</em></p><blockquote>1. <a href="https://medium.com/caw-engineering-blogs/connection-pooling-in-postgresql-9047bd697c32">Connection Pooling In PostgreSQL</a><br><strong>2. Vacuum Wars: PostgreSQL’s Quest for Optimization (You are here)</strong></blockquote><p>Quick question: Let’s say there is a table “<strong>Employees”</strong> in your PostgreSQL database with 4 records in it and as part of a transaction you’re supposed to update 2 of them.</p><p>How many records do you think will actually be present in the “<strong>Employees” </strong>table by the end of the transaction? You’re about to discover something new today if your response is 4.</p><h3>Dead Tuples PostgreSQL</h3><p>When you update a row, PostgreSQL just marks it as a dead tuple (like a soft delete) and <strong>creates a new record for the values to be updated</strong>. So the answer is 6<strong>. </strong>The below GIF is an illustration of the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oPOOTNn_zCGZAzrO.gif" /></figure><p>PostgreSQL creating a new row upon updating a row</p><pre>CREATE TABLE employees (id SERIAL PRIMARY KEY, name TEXT, salary INTEGER);<br>INSERT INTO employees (name, salary) VALUES (&#39;Alice&#39;, 50000), (&#39;Bob&#39;, 60000), (&#39;Matt&#39;, 42000), (&#39;Chris&#39;, 86000);</pre><pre>SELECT xmin, xmax, ctid, * FROM employees;</pre><pre>UPDATE employees SET salary = 65000 WHERE id = 2;<br>UPDATE employees SET name = &#39;Bob&#39; WHERE id = 4;</pre><p>Any table in PostgreSQL contains a few hidden columns. xmin, xmax, and ctid are a few of them.</p><p><strong>Here’s what each of those columns mean:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*ps7QChqSW-IAbwhjxW61QQ.png" /><figcaption>Hidden columns in PostgreSQL</figcaption></figure><p>For example, if a row has a ctid value of (0,5), that means the row is located in block 0 (A block is often referred to as <strong>page</strong>) i.e, the first block in the table and 5th row within that block.</p><p><strong>But why does PostgreSQL behave this way? </strong>That’s because PostgreSQL uses a<strong> multi-version concurrency control</strong> <strong>(MVCC) mechanism</strong>.</p><p>But what’s the point of not deleting those dead tuples?<br>We will be trying to systematically assess how to answer this in this blog.</p><h3>Multi-Version Concurrency Control</h3><p>Multi-Version Concurrency Control (MVCC) is a technique used by PostgreSQL to allow multiple transactions to access the same data simultaneously without interfering with each other. MVCC is implemented using a combination of snapshot isolation and versioning.</p><p>In MVCC, each transaction sees a snapshot of the database at a certain point in time, rather than the current state of the database. This snapshot copies the state of the database at the beginning of the transaction and stores it in memory. As the transaction reads and writes data, it sees only the version of the data that was current at the beginning of the transaction.</p><p>In MySQL, if Transaction A wants to read some data from Table X while Transaction B wants to simultaneously add new data to Table X, as long as the data being read and written are from distinct rows of the table, neither transaction will stop the other.</p><p>However, if the data being read and written are in the same row, then Transaction B will need to wait for Transaction A to release its lock on the row before it can acquire an exclusive lock and modify the row.</p><p>In PostgreSQL, Transaction A can read the data from Table X without blocking Transaction B, even if the data being read and written are in the same row. This is because PostgreSQL’s MVCC mechanism allows multiple transactions to read the same data simultaneously, while still ensuring consistency and preventing conflicts between transactions. Transaction B can acquire an exclusive lock on the row it wants to modify, and other transactions can still read the previous version of the row until Transaction B commits its changes.</p><p>MVCC in PostgreSQL is a powerful mechanism that allows for high concurrency and scalability in a multi-user environment. However, it also has some overheads in terms of storage and processing requirements, as multiple versions of each row must be stored in the database.</p><p><em>By now you must’ve understood why </em><strong><em>SELECT COUNT(*) </em></strong><em>could be a bad idea, especially in PostgreSQL</em>. Instead, you can use the below query if you don’t need an exact number. You can read more about <a href="https://wiki.postgresql.org/wiki/Slow_Counting">Slow Counting</a> and <a href="https://wiki.postgresql.org/wiki/Count_estimate">Count Estimate</a>.</p><pre>SELECT reltuples AS estimate FROM pg_class WHERE relname = &#39;table_name&#39;;</pre><h3><strong><em>When it comes to storage, PostgreSQL is like a teenager’s bedroom — it’s full of bloat and clutter that you have to clean up every once in a while.</em></strong></h3><h3>PostgreSQL Bloat: An Overview of its Types</h3><p>In PostgreSQL, bloat refers to the storage inefficiencies that can occur as tables and indexes grow over time. There are several different types of bloat that can occur in PostgreSQL:</p><ol><li><strong>Dead rows</strong>: <em>As discussed above</em>, when rows are updated or deleted, they are not immediately removed from the table. Instead, they are marked as “dead” and left on the table until the next time that VACUUM is run. This can lead to tables that contain a large number of dead rows, which can consume disk space and slow down queries.</li><li><strong>Index bloat</strong>: As indexes grow, they can become inefficient and consume more disk space than necessary. This can be caused by fragmentation, where index pages become partially filled, or by the presence of duplicate index entries.</li><li><strong>Table bloat</strong>: Tables can become bloated when they contain a large number of dead rows or when the statistics used by the query planner become outdated. This can lead to slower queries and increased disk usage.</li><li><strong>Transaction ID wraparound</strong>: PostgreSQL uses a 32-bit transaction ID to track changes to the database. If the transaction ID counter reaches its maximum value, it will wrap around to zero, which can cause problems if there are still live transactions with IDs greater than the wraparound point. This can lead to data corruption and the need for a manual VACUUM or VACUUM FULL operation.</li><li><strong>Toast table bloat</strong>: Large values stored in TEXT, VARCHAR, and BYTE <strong>columns are stored in a separate table called the “toast” table</strong>. If these values are updated frequently or are very large, the toast table can become bloated and slow down queries.</li></ol><p>To check if a table is making use of the toast table in PostgreSQL, you can use the below query. The pg_class catalog table contains information about all tables in the database, including their attributes, indexes, and storage options.</p><pre>SELECT relname, relkind, reltoastrelid <br>FROM pg_class <br>WHERE relname = &#39;tableName&#39;;</pre><p>If the reltoastrelid column is not null, it means that the table is using the toast table. The relkind column will also show &#39;r&#39; for a regular table or &#39;t&#39; for a toast table.</p><p>Note that a table may use the toast table for some columns but not others. You can check the attstorage column in the pg_attribute catalog table to see which columns are stored in the toast table. A value of &#39;x&#39; in this column indicates that the column is stored in the toast table.</p><p><strong>But what do we do about this bloat data? <br></strong>The answer is Vaccuum.</p><h3>Yes, Vacuum the Saviour</h3><p><strong>Vacuum is used to optimize and improve PostgreSQL performance.</strong> This reclaims storage space and optimizes the performance of the database by removing dead rows, updating statistics, and compacting pages. Vacuum is essential for preventing performance degradation and keeping the database running smoothly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F8LKb38PLUIczaVF9m2skg.png" /><figcaption>Vacuum is used to optimize PostgreSQL</figcaption></figure><p>In short, vacuum takes care of the bloat data in PostgreSQL. <strong><em>Why did we even discuss all of this then?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*oDPh2V59KG8s949b.gif" /></figure><p>While vacuuming is an important maintenance task in PostgreSQL, there are some potential downsides and trade-offs to consider.</p><p>Here are some of the downsides of vacuuming in PostgreSQL:</p><ol><li><strong>Resource usage</strong>: Vacuuming can be a resource-intensive operation, especially for large tables with many dead rows. The process can consume significant CPU, memory, and I/O resources, which may impact the performance of other processes running on the same system.</li><li><strong>Locking</strong>: Vacuuming requires an exclusive lock on the table being vacuumed, which means that no other processes can read from or write to the table while the vacuum is running. This can cause contention and delays if the table is frequently accessed by multiple processes.</li><li><strong>Index maintenance</strong>: As wementioned earlier, vacuuming can have an impact on indexes, as it involves scanning the indexes to find obsolete entries and removing them. This can be an expensive operation, especially for large tables with many indexes, and can increase the time required to complete the vacuum.</li><li><strong>Slowdowns during peak usage</strong>: If you vacuum a large table during peak usage hours, it can impact the performance of the application or service using the table. In this case, it is recommended to schedule vacuuming during off-peak hours to minimize any potential impact on users.</li><li><strong>Increased storage requirements</strong>: When you vacuum a table, PostgreSQL creates a new version of the table file without the dead rows. This new file may be larger than the original file, as it may contain empty space that has not yet been reclaimed. This can result in increased storage requirements for the table, which may be a concern for systems with limited disk space.</li></ol><p>PostgreSQL uses a lock called the <strong>AccessExclusiveLock</strong> on the table being vacuumed. This lock prevents other sessions from performing any operations on the table, including read and write operations, until the vacuum operation is complete.</p><p>The AccessExclusiveLock is a heavyweight lock that prevents any other session from acquiring any lock on the same table, including shared locks, until the lock is released. This is necessary to ensure that the vacuum operation has exclusive access to the table and can perform all necessary maintenance tasks without interference from other sessions.</p><p>It is important to note that the AccessExclusiveLock is a very strong lock and can cause contention in a heavily used database. Therefore, it is recommended to schedule vacuum operations during low-usage periods or to use alternative methods for performing maintenance on large tables, such as table partitioning or table archiving.</p><p>It is important to balance the benefits of vacuuming against the downsides and to carefully plan and schedule vacuuming operations to minimize any potential impact on the system.</p><p>Usually, If a company’s operations are fewer updates and thousands and millions of inserts in a day, then turning off the auto-vacuum is the first thing you should do rather than letting auto-vacuum kick in in the middle of bulk operations and lock everything down. Instead, <strong>have a cron job that does </strong><strong>VACUUM ANALYZE just like </strong><a href="https://zerodha.com/"><strong>Zerodha</strong></a><strong>, the largest stock broker in India does</strong>. For more information on this read this <a href="https://zerodha.tech/blog/working-with-postgresql/">article</a> by their tech team.</p><p>On an ending note, while there are many things to discuss and understand about MVCC, Bloat Data, and Vacuum in PostgreSQL, we’ve avoided to cram in too many things into one blog to make it clear and easy to follow.</p><blockquote>This Blog was written by <a href="https://www.linkedin.com/in/prathapchandra/">Prathap Chandra</a> (<a href="https://cawstudios.com/">CAW Studios</a>)</blockquote><blockquote>CAW Studios is a Product Engineering Company of 100+ geeks based out of Hyderabad. We run engineering for other start-ups.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b8065319186" width="1" height="1" alt=""><hr><p><a href="https://medium.com/caw-engineering-blogs/vacuum-wars-postgresqls-quest-for-optimization-3b8065319186">Vacuum Wars: PostgreSQL’s Quest for Optimization</a> was originally published in <a href="https://medium.com/caw-engineering-blogs">CAW Engineering Blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connection Pooling in PostgreSQL]]></title>
            <link>https://medium.com/caw-engineering-blogs/connection-pooling-in-postgresql-9047bd697c32?source=rss----b077e345995d---4</link>
            <guid isPermaLink="false">https://medium.com/p/9047bd697c32</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database-development]]></category>
            <category><![CDATA[database-administration]]></category>
            <category><![CDATA[connection-pooling]]></category>
            <dc:creator><![CDATA[CAW Blogs]]></dc:creator>
            <pubDate>Wed, 22 Feb 2023 13:36:16 GMT</pubDate>
            <atom:updated>2023-03-23T09:22:50.205Z</atom:updated>
            <content:encoded><![CDATA[<h3><em>Why do we re</em>commend <em>to do connection pooling with PostgreSQL DB</em></h3><p><em>By </em><a href="https://www.linkedin.com/in/prathapchandra/"><em>Prathap Chandra</em></a><em> (</em><a href="https://cawstudios.com/"><em>CAW Studios</em></a><em>)</em></p><p><em>We love PostgreSQL in CAW Studios. Its our go to DB when the product warrants a RDBMS. We have come across many surprises (and some shocks) as we explore the under-the-hood implementation of this awesome DB over the years. We are starting a series where we share our learning with wider community. We hope you enjoy this blog which will be part of a series.</em></p><blockquote>1. Connection Pooling In PostgreSQL (You are here)<br>2. Vacuum Wars: PostgreSQL’s Quest for Optimization</blockquote><p>You might have seen many articles on how and why to use connection pooling in databases. This article, unlike the others, focuses mostly on why it should be sort of mandatory when it comes to PostgreSQL<strong>.</strong> To understand that, we need to understand a few things about PostgreSQL.</p><h3>Process per connection</h3><p>Unlike MySQL or Oracle which uses a thread-based architecture, where each connection is assigned a thread from a thread pool whenever a new connection is established, PostgreSQL creates one <strong>PROCESS PER CONNECTION. </strong>The reasons being :</p><ol><li><strong>Isolation</strong>: Each connection to a PostgreSQL database is isolated from other connections, meaning that one connection’s operations won’t interfere with another. By using a separate process for each connection, PostgreSQL ensures that each connection has its own memory space and can’t accidentally access another connection’s data.</li><li><strong>Security</strong>: Each connection to a PostgreSQL database requires authentication, and by using a separate process for each connection, PostgreSQL can ensure that each connection is properly authenticated and authorized to access the database.</li><li><strong>Scalability</strong>: By using a process for each connection, PostgreSQL can handle many simultaneous connections without overwhelming the system. Each process can manage its own resources, and if one process crashes or becomes unresponsive, it won’t affect the other processes or connections.</li><li><strong>Flexibility</strong>: PostgreSQL supports a variety of different connection types, including TCP/IP, Unix domain sockets, and shared memory. By using a separate process for each connection, PostgreSQL can support these different connection types without having to write specialized code for each one.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*Zuc1KVryciyAQ6pX.png" /><figcaption>PostgreSQL Architecture</figcaption></figure><p>PostgreSQL uses the fork() system call to create a new process for each new client connection. The parent process creates a copy of itself (the child process) and then the child process initializes a new connection to the client. Forking a process can be an expensive operation in terms of system resources because it involves creating a new process and duplicating the parent process’s memory space, file descriptors, and other system resources.</p><p>PostgreSQL is designed to manage system resources efficiently, and it uses various techniques to reduce the overhead of forking new processes. For example, it uses a technique called <strong><em>“copy-on-write”</em></strong> to avoid duplicating memory pages unless they are modified, which can significantly reduce the amount of memory required to start a new process.</p><p>In addition, PostgreSQL provides various configuration parameters that can be used to control the number of processes and other resources used by the system. For example, you can set the maximum number of client connections allowed, adjust the size of the process pool, or set limits on the amount of memory used by each process.</p><p>By default, there is a limit on the no of connections PostgreSQL can handle, which is 100. This means if there are 100 open requests, you will encounter the below error for the subsequent requests</p><pre>psql: FATAL: remaining connection slots are reserved for non-replication superuser connections</pre><p>As Linus Torvalds says, “ <strong>Talk is cheap</strong>. <strong>Show me the code</strong>.”, I’ve added a code snippet below to simulate the same.</p><pre>const { Pool } = require(&#39;pg&#39;);<br><br>// Set up a database connection pool<br>const pool = new Pool({<br>    user: &#39;postgres&#39;,<br>    host: &#39;localhost&#39;,<br>    database: &#39;testdb&#39;,<br>    password: &#39;mypassword&#39;,<br>    port: 5432,<br>    max: 100,  // max_connections setting<br>});<br><br>// Define a function to execute a simple query<br>async function runQuery(clientId) {<br>    const client = await pool.connect();<br>    try {<br>        const res = await client.query(`SELECT ${clientId}`);<br>        console.log(`Client ${clientId} result: ${res.rows[0][clientId]}`);<br>    } finally {<br>        client.release();<br>    }<br>}<br><br>// Spawn multiple promises to simulate multiple clients<br>const numClients = 101;  // One more than the max_connections setting<br>const promises = [];<br>for (let i = 0; i &lt; numClients; i++) {<br>    promises.push(runQuery(i));<br>}<br>Promise.all(promises);</pre><p>When you run this code, it should simulate the scenario where multiple clients are trying to connect to a PostgreSQL database with limited resources. Depending on the actual system resources available, some promises might have to wait for an available connection slot before they can execute their query. The output of the code will show the results of each client’s query, along with the client ID, to demonstrate that the queries are being executed concurrently.</p><p>If you need to support more concurrent connections than the default value of <em>max_connections</em>, you can increase the value of this parameter in the <em>postgresql.conf</em> configuration file or at runtime using the ALTER SYSTEM command or the SET command. However, you should be careful not to set the value too high, as this can lead to resource contention and degrade the performance of the server.</p><p>Overall, while forking a process can be an expensive operation in general, PostgreSQL is designed to manage the overhead of forking new processes efficiently and effectively against the benefits of isolation, security, scalability, and flexibility.</p><blockquote>If you know what connection pooling is you can skip the rest of the article as you might have understood why it is important to use connection pooling in PostgreSQL by now.</blockquote><h3>Connection Pooling</h3><p>When a client makes a database call, an API call, or any other type of network request, it typically establishes a TCP connection to the server and uses this connection to exchange data. This connection remains open for the duration of the request and may be reused for subsequent requests to the same server.</p><p>The below image looks familiar, right? Yes, it’s a TCP 3-way handshake protocol and every new request has to go through this. But, why is this relevant now?</p><p><strong>Connection Pooling </strong>in simple terms is making use of some open TCP connection rather than initiating a new one. <strong>This means you’re skipping most of the layer 4 authentication, which makes your request response rate extremely faster if implemented properly.</strong></p><figure><img alt="TCP 3-way handshake" src="https://cdn-images-1.medium.com/max/875/0*Vs7NOQlEegDnTZr6.png" /><figcaption>TCP 3-way handshake</figcaption></figure><p>For stateless queries, you don’t have to worry about which connection is being used. But when working with transactions, you can request a dedicated client from the pool. We should also make sure we release it back to the pool so that other requests can use the same connection before the connection eventually times out.</p><p>As we’ve discussed earlier, be it a DB call or an API call, or any other network request for that matter, it typically establishes a TCP connection. So the same can be done for API calls as well (HTTP connection pooling or persistent connections). We just need to make sure we handle it properly.</p><blockquote>This Blog was written by <a href="https://www.linkedin.com/in/prathapchandra/">Prathap Chandra</a> (<a href="https://cawstudios.com/">CAW Studios</a>)</blockquote><blockquote>CAW Studios is a Product Engineering Company of 100+ geeks based out of Hyderabad. We run engineering for other start-ups.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9047bd697c32" width="1" height="1" alt=""><hr><p><a href="https://medium.com/caw-engineering-blogs/connection-pooling-in-postgresql-9047bd697c32">Connection Pooling in PostgreSQL</a> was originally published in <a href="https://medium.com/caw-engineering-blogs">CAW Engineering Blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hosting a Static Website using AWS CloudFront and S3 Bucket]]></title>
            <link>https://medium.com/caw-engineering-blogs/hosting-a-static-website-using-aws-cloudfront-and-s3-bucket-7ad45b1d744a?source=rss----b077e345995d---4</link>
            <guid isPermaLink="false">https://medium.com/p/7ad45b1d744a</guid>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[hosting]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloudfront]]></category>
            <dc:creator><![CDATA[CAW Blogs]]></dc:creator>
            <pubDate>Tue, 14 Feb 2023 14:04:13 GMT</pubDate>
            <atom:updated>2023-02-16T14:59:30.200Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By </em><a href="https://www.linkedin.com/in/aayush-bajaj-505/"><em>Aayush Bajaj</em></a><em> (</em><a href="https://cawstudios.com/"><em>CAW Studios</em></a><em>)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LEJAvwhyOrxDbY9k5YB_og.jpeg" /></figure><h3>Introduction</h3><p>With growing options these days, there are infinite ways to host a site. You could use a basic hosting provider like GitHub Pages or Netlify. This is good enough for smaller sites, as this requires minimal setup, and the site can be live in mere minutes.</p><p>But what if the size is much larger and you don’t want to compromise on load times? In that case, using Amazon Web Services (AWS) CloudFront and S3 Bucket is an efficient way to ensure that your website is always available to users with low latency and high performance.</p><h3>Overview</h3><p>We will explore how to set up hosting for a static website using AWS CloudFront and S3 Bucket, along with it using CloudTrail to log all changes. Additionally, we will look at the process of provisioning the infrastructure for Static hosting using IaaC tools like Terraform in GitOps, with some shift-left practices in CI pipelines.</p><p>Let’s start by getting to know the tools we’ll be using.</p><h3>Cloud Front</h3><p>CloudFront is a service by Amazon that speeds up static and dynamic web content distribution. It includes HTML, CSS, JS, images, and other media content.</p><p>CloudFront delivers content through a worldwide network of data centers called <strong><em>Edge Locations</em></strong>. This helps reduce <strong><em>Latency,</em></strong> which is the time delay between the user’s request for content and the delivery of that content from the server.</p><h3>Route 53</h3><p>Amazon Route 5 is a highly available and scalable Domain Name System (DNS) web service. You can use Route 53 to perform three main functions in any combination: domain registration, DNS routing, and health checking.</p><h3>Certificate Manager</h3><p>AWS Certificate Manager (ACM) is a service that lets you easily provision, manage, and deploy public and private Secure Sockets Layer/Transport Layer Security (SSL/TLS) certificates for use with AWS services and your internal connected resources.</p><h3>Cloud Trail</h3><p>CloudTrail enables auditing, security monitoring, and operational troubleshooting by tracking user activity and API usage. CloudTrail logs, continuously monitors, and retains account activity related to actions across your AWS infrastructure, giving you control over storage, analysis, and remediation actions.</p><h3>WAF</h3><p>AWS WAF is a web application firewall that lets you monitor the HTTP(S) requests that are forwarded to your protected web application resources</p><h3>S3</h3><p>Amazon Simple Storage Service (Amazon S3) is an object storage service that offers data scalability, availability, security, and performance. Customers of all sizes and industries can use Amazon S3 to store and protect any amount of data for various use cases, such as data lakes, websites, mobile applications, backup and restore, archive, enterprise applications, IoT devices, and big data analytics.</p><h3>TerraForm</h3><p>Terraform is an open-source infrastructure-as-code software tool created by HashiCorp. Users define and provide data center infrastructure using a declarative configuration language known as HashiCorp Configuration Language, or optionally JSON.</p><h3><strong>GitHub Actions</strong></h3><p>GitHub Actions is a continuous integration and continuous delivery (CI/CD) platform that allows you to automate your build, test, and deployment pipeline. You can create workflows that build and test every pull request to your repository, or deploy merged pull requests to production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LclhZoBLFSfK2mSfTFzyXg.png" /></figure><p>The above diagram represents the two pipelines being run to host a static website we are focussing on the infrastructure deployment here. But the deployment.yaml file comes into play after our infra is provisioned; it is used to push the code into the bucket so that the website can be hosted .</p><p>Note: Here the builder in deployment.yml refers to any builder for the technology you are working on for example: hugo, npm etc.</p><h3>Block Diagram</h3><p>The below diagram explains the high level AWS Architecture diagram including all the AWS services that will be used to host a static website. This diagram depicts the AWS services that will be used to host the static content and the static content is pushed to S3 bucket using CodePipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GUokvkbkn5_7BPlU1MqdDg.png" /><figcaption>Flow of actions with Github, Amazon S3, and CloudFront</figcaption></figure><h3>A high-level overview of Infra Provisioning via Terraform</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NAteoo3ShMSBJcZx1ogbfg.png" /></figure><p>The above diagram represents an end to end CI pipeline to provision the required AWS infrastructure required for hosting a static website using CloudFront and S3 bucket. The diagram shows the Git Pull Request approach which triggers a GitHub actions job to clone the Terraform code and execute the TF plan after passing the TFsec gating in the CI pipeline. The TFsec gating is added to ensure it meets an organization security standard with regards to static code analysis.</p><p>The Github Actions job will run the TF plan and seek an approval from the users to validate the Terraform plan, once approved the TF apply is run again to provision the final infrastructure. The plan output is logged in GH Actions for audit purposes and the required notifications are sent via Email or Slack Notification.</p><h3>CloudFront + S3 via Terraform &amp; GitHub Actions Pipelines:</h3><p>The general steps are as follows:</p><ol><li>The repo has Terraform code for Cloudfront, S3, AWS WAF, Cloudtrail etc. Read the Readme.md file in the repository for more details.</li><li>The first step is to create a s3 bucket where our state file for terraform infrastructure will be saved and set up a backend configuration. Refer Terraform state file documentation on Statefile and State File locking using AWS DynamoDB.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BzhNOfOnc10sxF2KNoBp6A.png" /></figure><p>We also need to enable bucket versioning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xN4dbb3JVBS5PsYxJmVWYw.png" /></figure><p>3. Once the bucket is created we set up the backend configuration for terraform in backend.tf. Here the bucket parameter contains the name of the bucket and the key parameter contains the name with which the state file will be created.</p><pre>terraform {<br> backend &quot;s3&quot; {<br>   bucket     = &quot;caw-aws-aps1-demo-s3-tfstate&quot;<br>   key        = &quot;s3-backend-demo-infra-module.tfstate&quot;<br>   region     = &quot;ap-south-1&quot;<br> }<br>}</pre><p>4. We also set up the provider in provider.tf. Alias is used to set up providers for two different aws regions as WAF needs to be configured in us-east-1. (<a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/wafv2_web_acl#scope">https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/wafv2_web_acl#scope</a>). For more information on multiple provider configuration — <a href="https://developer.hashicorp.com/terraform/language/providers/configuration#alias-multiple-provider-configurations">Link</a></p><pre>terraform {<br> required_providers {<br>   aws = {<br>     source  = &quot;hashicorp/aws&quot;<br>     version = &quot;~&gt; 4.45.0&quot;<br>   }<br> }<br>}<br>provider &quot;aws&quot; {<br> region     = &quot;ap-south-1&quot;<br> access_key = var.access_key_id<br> secret_key = var.access_key_secret<br>}<br><br><br>provider &quot;aws&quot; {<br> alias = &quot;aws-waf-web-acl-provider&quot;<br> region     = &quot;us-east-1&quot;<br> access_key = var.access_key_id<br> secret_key = var.access_key_secret<br>}</pre><p>5. Creating the bucket for static website hosting in s3.tf :</p><pre>resource &quot;aws_s3_bucket&quot; &quot;this-s3-bucket&quot; {<br> bucket        = &quot;${local.parent_org_name}-${local.cloud_provider}-${local.region}-${local.environment}-s3-${local.project}-${var.s3_bucket_name}&quot;<br> force_destroy = true<br>}<br>Resource&quot;aws_s3_bucket_website_configuration&quot; &quot;this-s3-website-configuration&quot; {<br> bucket   = var.bucket-name<br> index_document {<br>   suffix = &quot;index.html&quot;<br> }<br> error_document {<br>   key = &quot;index.html&quot;<br> }<br> depends_on = [<br>   aws_s3_bucket.this-s3-bucket<br> ]<br>}<br>resource &quot;aws_s3_bucket_policy&quot; &quot;this-s3-policy&quot; {<br> bucket=var.bucket-name<br> policy   = &lt;&lt;POLICY<br>{<br>   &quot;Version&quot;: &quot;2008-10-17&quot;,<br>   &quot;Id&quot;: &quot;PolicyForCloudFrontPrivateContent&quot;,<br>   &quot;Statement&quot;: [<br>       {<br>           &quot;Sid&quot;: &quot;AddPerm&quot;,<br>           &quot;Effect&quot;: &quot;Allow&quot;,<br>           &quot;Principal&quot;: &quot;*&quot;,<br>           &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>           &quot;Resource&quot;: &quot;arn:aws:s3:::${var.bucket-name}/*&quot;<br>       }<br>   ]<br>}<br>POLICY<br> depends_on = [<br>   aws_s3_bucket.this-s3-bucket<br> ]<br>}<br>resource &quot;aws_s3_bucket_acl&quot; &quot;this-s3-acl_policy&quot; {<br> bucket=var.bucket-name<br> access_control_policy {<br>   grant {<br>     grantee {<br>       id   = data.aws_canonical_user_id.current.id<br>       type = &quot;CanonicalUser&quot;<br>     }<br>     permission = &quot;READ&quot;<br>   }<br>   grant {<br>     grantee {<br>       id   = data.aws_canonical_user_id.current.id<br>       type = &quot;CanonicalUser&quot;<br>     }<br>     permission = &quot;READ_ACP&quot;<br>   }<br>   grant {<br>     grantee {<br>       id   = data.aws_canonical_user_id.current.id<br>       type = &quot;CanonicalUser&quot;<br>     }<br>     permission = &quot;WRITE&quot;<br>   }<br>   grant {<br>     grantee {<br>       id   = data.aws_canonical_user_id.current.id<br>       type = &quot;CanonicalUser&quot;<br>     }<br>     permission = &quot;WRITE_ACP&quot;<br>   }<br>   grant {<br>     grantee {<br>       type = &quot;Group&quot;<br>       uri  = &quot;http://acs.amazonaws.com/groups/global/AllUsers&quot;<br>     }<br>     permission = &quot;READ_ACP&quot;<br>   }<br>   grant {<br>     grantee {<br>       type = &quot;Group&quot;<br>       uri  = &quot;http://acs.amazonaws.com/groups/global/AllUsers&quot;<br>     }<br>     permission = &quot;READ&quot;<br>   }<br>   owner {<br>     id = data.aws_canonical_user_id.current.id<br>   }<br> }<br>}</pre><p>6. Creation of the CloudFront distribution in cloudfront.tf . Note: These parameters are for demo / blog purpose only follow CloudFront best practices for production use.</p><pre>resource &quot;aws_cloudfront_distribution&quot; &quot;this-cdn-portal&quot; {<br> origin {<br>   domain_name = data.aws_s3_bucket.demo-portal-s3-bucket.bucket_domain_name<br>   origin_id   = data.aws_s3_bucket.demo-portal-s3-bucket.bucket_domain_name<br> }<br> wait_for_deployment = false<br> enabled             = true<br> is_ipv6_enabled     = true<br> default_root_object = &quot;index.html&quot;<br> default_cache_behavior {<br>   allowed_methods        = [&quot;GET&quot;, &quot;HEAD&quot;]<br>   cached_methods         = [&quot;GET&quot;, &quot;HEAD&quot;]<br>   target_origin_id       = data.aws_s3_bucket.demo-portal-s3-bucket.bucket_domain_name<br>   compress               = true<br>   cache_policy_id        = data.aws_cloudfront_cache_policy.cache_policy_cloudfront.id<br>   viewer_protocol_policy = &quot;allow-all&quot;<br> }<br> web_acl_id = aws_wafv2_web_acl.this-waf-web-acl.arn<br> price_class = &quot;PriceClass_All&quot;<br> viewer_certificate {<br>   cloudfront_default_certificate = true<br> }<br> restrictions {<br>   geo_restriction {<br>     restriction_type = &quot;none&quot;<br>   }<br> }<br>}</pre><p>7. Createion of WAF in aws-waf.tf:</p><pre>resource &quot;aws_wafv2_web_acl&quot; &quot;this-waf-web-acl&quot; {<br> provider = aws.aws-waf-web-acl-provider <br> name        = &quot;${local.parent_org_name}-${local.cloud_provider}-${local.region}-${local.environment}-waf_web_acl&quot;<br> description = &quot;Bot Control waf aws acl&quot;<br> scope       = &quot;CLOUDFRONT&quot;<br><br><br> default_action {<br>   allow {}<br> }<br>  rule {<br> name = &quot;AWS-AWSManagedRulesBotControlRuleSet&quot;<br> priority = 0<br> statement {<br>   managed_rule_group_statement {<br>     vendor_name = &quot;AWS&quot;<br>     name = &quot;AWSManagedRulesBotControlRuleSet&quot;<br>   }<br> }<br> override_action {<br>   count {}<br> }<br> visibility_config {<br>   sampled_requests_enabled = true<br>   cloudwatch_metrics_enabled = true<br>   metric_name = &quot;AWS-AWSManagedRulesBotControlRuleSet&quot;<br> }<br>}<br> visibility_config {<br>   sampled_requests_enabled = true<br>   cloudwatch_metrics_enabled = true<br>   metric_name = &quot;AWS-AWSManagedRulesBotControlRuleSet&quot;<br> }<br>}</pre><p>8. We create a workflow to rebuild the site and deploy it automatically after each update with main.yml. The workflow will only be triggered if files are modified after a push action in these directories</p><pre>name: Plan using Terraform<br>on:<br> pull_request:<br>   branches:<br>     - develop<br>   paths:<br>     - &#39;terraform/dev/**&#39;</pre><p>9. The terraform code is checked for security issues using <a href="https://github.com/aquasecurity/tfsec">TFSEC (https://github.com/aquasecurity/tfsec)</a> This is the static code analysis phase of Terraform code.</p><pre>- name: Clone repo<br>  uses: actions/checkout@master<br><br>- name: tfsec<br>  id: tfsec<br>  uses: aquasecurity/tfsec-action@v1.0.0<br>  with:<br>    soft_fail: true</pre><p>10. More gatings like this can be added to the CI pipeline, for ex: Tfcost, etc which can project approx. cost of the infra being provisioned by Terraform. If the security check fails, the build is halted.</p><p>11. Use GitHub Actions Setup Terraform project to run Terraform jobs in GitHub Actions. (https://github.com/hashicorp/setup-terraform.git)</p><pre>- name: Check out code<br>     uses: actions/checkout@v2<br><br><br> - name: Setup Terraform<br>   uses: hashicorp/setup-terraform@v2<br>   with:<br>     terraform_version: 1.3.7</pre><p>12. Configure AWS credentials and Initialize Terraform.</p><pre>- name: Configure AWS Credentials<br>       uses: aws-actions/configure-aws-credentials@v1<br>       with:<br>         aws-region: ap-south-1<br>         aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>         aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}<br><br><br> - name: Initialize Terraform<br>   id: init<br>   run: |<br>     terraform init \<br>     -backend-config=&quot;access_key=&quot;${{ secrets.AWS_ACCESS_KEY_ID }}&quot; \<br>     -backend-config=&quot;secret_key=&quot;${{ secrets.AWS_SECRET_ACCESS_KEY }}&quot;</pre><p>13. The credentials are being sourced from github secrets, so that sensitive information does not end up on a public repository even by mistake. To set these up head to your repository-&gt;settings-&gt;secrets and variables-&gt;actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4iJjIxk_oSnUZhiAvKl_Mw.png" /></figure><p>14. Configure Terraform Plan and Github outputs that comment on the changes to be made in infrastructure.</p><pre>- name: Plan Terraform<br> id: plan<br> continue-on-error: true<br> run: |<br>   terraform plan -no-color</pre><p>15. Once we create a new branch and create a pull request.The Pull request triggers a github action which provisions GitHub Action Runners.</p><pre>git branch checkout -b demo-project<br>git add .<br>git commit -m &quot;First commit&quot;<br>git push origin demo-project</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NWP92gUX9YysyhwIs6BAFg.png" /></figure><p>16. Output of the plan is logged in a PR comment automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L4Hqq4KbSBTSbA6cYoguNg.png" /></figure><p>With the help of an action github script which basically saves the output from previous steps of Tfsec, init and plan and publishes it as a comment shown above.</p><pre>  - uses: actions/github-script@v6<br>       if: github.event_name == &#39;pull_request&#39;<br>       env:<br>         PLAN: &quot;terraform\n${{ steps.plan.outputs.stdout }}&quot;<br>       with:<br>         script: |<br>           const output = `#### Terraform Tfsec 🤖\`${{ steps.tfsec.outcome }}\&#39;<br>           #### Terraform Initialization ⚙️\`${{ steps.init.outcome }}\`<br><br><br>           #### Terraform Plan 📖\`${{ steps.plan.outcome }}\`<br><br><br>           &lt;details&gt;&lt;summary&gt;Show Plan&lt;/summary&gt;<br><br><br>           \`\`\`\n<br>           ${process.env.PLAN}<br>           \`\`\`<br><br><br>           &lt;/details&gt;<br><br><br>           *Pusher: @${{ github.actor }}, Action: \`${{ github.event_name }}\`, Working Directory: \`${{ env.tf_actions_working_dir }}\`, Workflow: \`${{ github.workflow }}\`*`;<br><br><br>           github.rest.issues.createComment({<br>             issue_number: context.issue.number,<br>             owner: context.repo.owner,<br>             repo: context.repo.repo,<br>             body: output<br>           })</pre><p>17. An Email and a slack notification are sent to reviewers to review the changes.</p><p>18. After approval of the reviewers the Pull request is merged and another pipeline is triggered which provisions the infrastructure.</p><pre>     - name: Apply Terraform<br>       if: steps.plan.outcome == &#39;success&#39;<br>       id: apply<br>       continue-on-error: true<br>       run: |<br>         terraform destroy -auto-approve</pre><p>19. After manual approval has been given and the infrastructure changes are applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQA476PjDyq3ENpQIG20BQ.png" /></figure><p>20. Post the infrastructure deployment, route53 entries need to be configured with the ACM Certificate and added to cloudfront. Terraform Code for route 53 is beyond the scope for this blog and can be configured manually.</p><p>21. After the Infrastructure has been deployed the next step would include pushing the built code to the s3 bucket so that it can be hosted. For that we need another pipeline where we synchronize the build files of the project to S3</p><pre> aws s3 sync --follow-symlinks --delete --no-progress ./dist/apps/&lt;foldername&gt;/ s3://${{ secrets.&lt;bucketname&gt;  }}/</pre><p>22. And create an invalidation for cloudfront using the following commands.</p><pre>aws cloudfront create-invalidation --distribution-id ${{secrets.&lt;distribution_idName&gt;}} --paths &quot;/*&quot;</pre><h3>Github Repositoy</h3><ul><li><a href="https://github.com/cawstudios/static-website-hosting-using-cloudFront-and-s3-bucket.git">https://github.com/cawstudios/static-website-hosting-using-cloudFront-and-s3-bucket.git</a></li></ul><h3>References</h3><ul><li><a href="https://github.com/aquasecurity/tfsec">https://github.com/aquasecurity/tfsec</a></li><li><a href="https://aws.amazon.com/premiumsupport/knowledge-center/cloudfront-serve-static-website/">https://aws.amazon.com/premiumsupport/knowledge-center/cloudfront-serve-static-website/</a></li><li><a href="https://developer.hashicorp.com/terraform/tutorials/automation/github-actions">https://developer.hashicorp.com/terraform/tutorials/automation/github-actions</a></li></ul><h3>Conclusion</h3><p>The combination of Terraform and GitHub Actions has provided a powerful and secure way to set up a static website using AWS CloudFront and S3 buckets. By using Terraform’s Infrastructure as Code (IaC) approach and GitOps practices, the process of provisioning and configuring the necessary resources is automated and secure. Additionally, security checks like TFSEC are added to CI pipelines to ensure the code is secure. This is an efficient solution for anyone looking to set up a static website in a similar way.</p><blockquote>This Blog was written by <a href="https://www.linkedin.com/in/aayush-bajaj-505/">Aayush Bajaj</a> (<a href="https://cawstudios.com/">CAW Studios</a>)</blockquote><blockquote>CAW Studios is a Product Engineering Company of 100+ geeks based out of Hyderabad. We run engineering for other start-ups.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ad45b1d744a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/caw-engineering-blogs/hosting-a-static-website-using-aws-cloudfront-and-s3-bucket-7ad45b1d744a">Hosting a Static Website using AWS CloudFront and S3 Bucket</a> was originally published in <a href="https://medium.com/caw-engineering-blogs">CAW Engineering Blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Apache Airflow for running data jobs at scale]]></title>
            <link>https://medium.com/caw-engineering-blogs/using-apache-airflow-for-running-data-jobs-at-scale-408060266306?source=rss----b077e345995d---4</link>
            <guid isPermaLink="false">https://medium.com/p/408060266306</guid>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[apache-airflow]]></category>
            <category><![CDATA[aws-glue]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[CAW Blogs]]></dc:creator>
            <pubDate>Thu, 09 Feb 2023 06:33:11 GMT</pubDate>
            <atom:updated>2023-02-16T15:05:59.225Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By </em><a href="https://www.linkedin.com/in/kartikbansal/"><em>Kartik Bansal</em></a><em>, </em><a href="https://medium.com/linkedin.com/in/amar-jaiswal-065b37112/"><em>Amar Jaiswal</em></a><em> (</em><a href="https://cawstudios.com/"><em>CAW Studios</em></a><em>)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vJb9oP4eyjnACSGONnH_SA.jpeg" /></figure><p>At CAW, we work on hard problems. Sometimes, the problem is simple, but when we have to implement it at a scale with consistent reliability, a simple problem can grow into a hard one.</p><p>This is the case with one of our products. The problem was implementing data collection and processing jobs at scale. Each job either scraps data from a website, calls an API, downloads a file, or gets data from RSS or Twitter feeds.</p><p>Individually, they are small and simple problems. But traditional approaches break down when you have to consistently add 100+ new jobs every month and have the ability to orchestrate 1000+ jobs in production with reliability.</p><p>We evaluated several solutions on the following dimensions -</p><ol><li>Complex Scheduling with retry logic</li><li>Horizontal scale as we added newer data sources</li><li>Real-time monitoring for failures</li><li>Instrumentation so we could optimize slow-performing jobs</li><li>Visibility on the overall health of the system</li></ol><p>We narrowed it down to two — AWS Glue and Apache Airflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hm-n0Tv-jDCxTK0JV0uRng.png" /></figure><p>It was a tough battle between the two.</p><p>However, Airflow being an Open Source solution that allowed us to avoid vendor lock-in, we decided to go with it.</p><h3>Apache Airflow</h3><p>Apache Airflow was conceived at Airbnb. It is a batch workflow orchestration platform with each job represented as a Directed Acyclic Graph or DAG.</p><p>The Airflow framework contains operators to connect with many technologies and is easily extensible for connecting with new technology. If the workflows have a clear start and end and run at regular intervals, they can be programmed as an Airflow DAG.</p><p>Airflow Docs: <a href="https://airflow.apache.org/docs/apache-airflow/stable/index.html">https://airflow.apache.org/docs/apache-airflow/stable/index.html</a></p><h3>Architecture</h3><p>Apache Airflow, as some people like to call it, “CRON on steroids” works on a fundamental principle of DAGs (Directed Acyclic Graphs). In this, one can create functions/methods which will act as Nodes of the DAG.<br>And we can define the direction using simple arrow notations “&gt;&gt;”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KxSzvJMRz0K7-mzrVJATw.png" /></figure><ul><li><a href="https://docs.aws.amazon.com/mwaa/latest/userguide/get-started.html">Get started with Amazon Managed Workflows for Apache Airflow (MWAA)</a></li><li>Writing and Running DAGSs: <a href="https://airflow.apache.org/docs/apache-airflow/stable/best-practices.html#best-practices">Best Practices — Airflow Documentation</a></li></ul><p>Airflow has a variety of provider packages that helps in easy integration with third-party projects, including AWS, Microsoft Azure, Facebook, Google, etc. Full list <a href="https://airflow.apache.org/docs/#providers-packagesdocsapache-airflow-providersindexhtml">here</a></p><h3>Configurability and Observability</h3><p>Airflow comes bundled with a powerful dashboard that enables us to observe and configure schedule time, retry logics, and enable-disable jobs. The same dashboard provides rich metrics <strong>to</strong> monitor the jobs on error rates and performance. We can do custom app logging from individual jobs to troubleshoot easily.</p><p>Monitoring: <a href="https://airflow.apache.org/docs/apache-airflow/stable/logging-monitoring/index.html#logging-monitoring">Logging &amp; Monitoring — Airflow Documentation</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8eD9n4pUyUvHzlGqp02TXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fmtVCSHp1q_aMQaV8kQ4Og.png" /></figure><h3>Implementation</h3><p>We decided to implement our v1 using the <a href="https://aws.amazon.com/managed-workflows-for-apache-airflow/">MWAA (Managed workflows for apache airflow)</a> from AWS with the flexibility to go completely self-hosted in the future.</p><p>MWAA enabled us to ve ops-lite for the v1. We used ECSOperator to help run tasks as an ephemeral ECS task outside Airflow’s network. Traditionally regular tasks would run by Airflow’s worker node, but if our task or job is huge and needs more resources, it might take more processor bandwidth and slow down the execution.</p><p>ECSOperator is a perfect candidate in such cases.</p><ul><li><a href="https://docs.aws.amazon.com/mwaa/latest/userguide/samples-ecs-operator.html#samples-ecs-operator-code">https://docs.aws.amazon.com/mwaa/latest/userguide/samples-ecs-operator.html#samples-ecs-operator-code</a></li><li><a href="https://medium.com/@sohflp/how-to-work-with-airflow-docker-operator-in-amazon-mwaa-5c6b7ad36976">https://medium.com/@sohflp/how-to-work-with-airflow-docker-operator-in-amazon-mwaa-5c6b7ad36976</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uYlA82V0X6X9MjSp4M6hqg.png" /></figure><p><strong><em>Connectors and Converters</em></strong></p><p>For each feed, we created a DAG executing two tasks — a Connector and a Converter.</p><ul><li><strong>Connectors</strong>: They contain the crawler logic, which fetches the raw data from various data sources, including websites, APIs, shred files, RSS feeds, and Twitter, and saves the data to S3.</li><li><strong>Converters: </strong>They download data from s3, perform cleaning and transformation to STIX format, and feed it into a Queue.</li></ul><p>The logic to convert raw data to a structured format takes multiple iterations to stabilize.</p><p>You start with a few data feeds and design your data conversion logic based on their data format. And as you add more feeds, you encounter newer formats and iteratively expand your conversion logic.</p><p>We made a decision upfront to decouple the connectors from the converters so we could rerun the converter’s logic after we added support for the unhandled scenarios without requiring us to re-download the data.</p><p><strong>RAW Data Storage<br></strong>We used AWS S3 buckets to store the raw data scraped from various data sources. The connector task saves the data in the bucket.</p><p><strong>Processed Data Queue<br></strong>Carries structured, cleaned, and valuable information that can be saved into DB. The converter sends the data into the queue for further processing by the Data Injector.<br>We used <strong>AWS SQS </strong>service to carry this data</p><p><strong>Data Injector<br></strong>A consumer to the queue, its job is to de-duplicate, rank, compute the confidence index and insert data into DB. We created an AWS Lambda function with an SQS trigger, so whenever new data is injected into the queue, it does its job automatically.</p><p><strong>Database<br></strong>We used MongoDB to store the final structured data. Since the data was not relational, we wanted it to be highly available. Therefore, a NoSQL DB was the perfect choice for our use case. Hence Mongo DB was a no-brainer here.</p><h3>Challenges</h3><p>The main challenge was that MWAA supports only specific airflow versions, and It comes with out-of-the-box plugins that were no less than a headache to set up manually.</p><p>An array of hurdles would crop up, such as a dependency version mismatch or a Python version mismatch. It was challenging for new developers to get the hang of it and set up a new environment just to write a few DAGs.</p><p>Upon researching, we found a way to mimic a local MWAA setup — <a href="https://github.com/aws/aws-mwaa-local-runner">https://github.com/aws/aws-mwaa-local-runner</a>.</p><p>This repository provides a Command Line Interface (CLI) utility that replicates an Amazon Managed Workflows for Apache Airflow (MWAA) environment locally.</p><p>This repo includes the following:</p><ul><li>A <a href="https://github.com/aws/aws-mwaa-local-runner/blob/v2.4.3/docker/Dockerfile">DockerFile</a> derived from <strong><em>amazonlinux </em></strong>image miming the MWAA server.</li><li>A <a href="https://github.com/aws/aws-mwaa-local-runner/blob/v2.4.3/mwaa-local-env">Command line shell script</a> that can build Airflow Image with predefined dependencies and constraints.</li><li>A <a href="https://github.com/aws/aws-mwaa-local-runner/blob/v2.4.3/docker/docker-compose-local.yml">DockerCompose</a> file with a local Postgres instance and the locally built Airflow Docker image. It mounts the local DAGs directory so we can test and run our DAGs locally.</li></ul><p>Now, to run the airflow instance locally, we have to run two commands:</p><ul><li><strong><em>./mwaa-local-env build-image</em></strong>: This command will generate a docker image using the docker file, as mentioned earlier.</li><li><strong><em>./mwaa-local-env start</em></strong>: This command will run a local env with a Postgres DB and locally mounted DAGs folder.</li></ul><p>This also gave us the flexibility of containerizing our setup, making it easy to migrate to a self-hosted Airflow Setup with minimal configuration changes on any given day.</p><h3>Repository Structure</h3><p>Most data sources had similar patterns for querying, processing, and storing data. We developed a smart codebase structure to ensure code reusability and common standards across data feeds.</p><p>We used a MonoRepo structure for Connector/ Converters and Data Inserters.</p><p>Connectors and Converters run as an Airflow Task.</p><pre>|-common<br>|   |---&gt; A Common pip package that contains common code sharable b/w multiple services<br>|<br>|-data_injector<br>|   |---&gt;  Code for the Serverless that picks STIX entry from SQS and inserts into MongoDB<br>|<br>|-connectors_and_converters/<br>|   |---&gt; This is the Airflow&#39;s DAGs folder, contains code for data feed dags<br>|   |<br>|   |-shared/<br>|   |   |---&gt; Contains common code amongst all DAGs<br>|   |   |<br>|   |   |- utilities<br>|   |   |- providers<br>|   |<br>|   |-feeds/<br>|       |<br>|       |-data_feed_1/<br>|       |   |- _init_.py<br>|       |   |- connector.py<br>|       |   |- convertor.py<br>|       |<br>|       |-data_feed_2/<br>|       |   |- _init_.py<br>|       |   |- connector.py<br>|       |   |- convertor.py<br>|       |<br>|       |-data_feed_3/<br>|           |- _init_.py<br>|           |- connector.py<br>|           |- convertor.py<br>|-aws<br>|   |---&gt; All CloudFormation Scripts required to bring up the infra on AWS<br>|<br>|-docker<br>    |---&gt; Docker Compose files to run the local setup</pre><p>The idea was that all the shared logic between these data feeds sit in the shared folder.</p><p>As we implement more feeds and common patterns emerge, we promote this new logic to the shared and reuse them. We started with a few common utilities for scrapping and uploading data to s3, and as the number of feeds grew, so did our shared logic.</p><h3>Deployment</h3><p>Since we decided to use MWAA, all DAGs code must be deployed to an S3 bucket; we just had to write a Github Action that uses the <strong>AWS CLI </strong>to sync the <strong><em>connectors_and_convertors </em></strong><em>directory to AWS s3.</em></p><pre>aws s3 sync ./connectors_and_converters/ <br>s3://${{secrets.AWS_S3_BUCKET_DAGS}}/dags/ --delete --exclude &quot;*.pyc&quot;</pre><h3>Final Thoughts</h3><p>Apache Airflow helped us achieve a manageable solution to run a large number of feeds.</p><p>So much so that we were able to add two new feeds every week. At this rate, we are positive to reach ten new feeds per week by the next quarter.</p><blockquote>This Blog was written by By <a href="https://www.linkedin.com/in/kartikbansal/">Kartik Bansal</a>, <a href="https://medium.com/linkedin.com/in/amar-jaiswal-065b37112/">Amar Jaiswal</a> (<a href="https://cawstudios.com/">CAW Studios</a>)</blockquote><blockquote>CAW Studios is a Product Engineering Company of 100+ geeks based out of Hyderabad. We run engineering for other start-ups.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=408060266306" width="1" height="1" alt=""><hr><p><a href="https://medium.com/caw-engineering-blogs/using-apache-airflow-for-running-data-jobs-at-scale-408060266306">Using Apache Airflow for running data jobs at scale</a> was originally published in <a href="https://medium.com/caw-engineering-blogs">CAW Engineering Blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>