<?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 Manikandan Paramasivan on Medium]]></title>
        <description><![CDATA[Stories by Manikandan Paramasivan on Medium]]></description>
        <link>https://medium.com/@manikandan_35899?source=rss-ab6cc19fc3bd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fIjx3nsNxMNyXCnW</url>
            <title>Stories by Manikandan Paramasivan on Medium</title>
            <link>https://medium.com/@manikandan_35899?source=rss-ab6cc19fc3bd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 13:35:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manikandan_35899/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 We Built the Modern Data Platform at KOHO]]></title>
            <link>https://koho.dev/how-we-built-the-modern-data-platform-at-koho-83a1be799303?source=rss-ab6cc19fc3bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/83a1be799303</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-architecture]]></category>
            <category><![CDATA[data-platforms]]></category>
            <category><![CDATA[data-ware-housing]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <dc:creator><![CDATA[Manikandan Paramasivan]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 15:02:23 GMT</pubDate>
            <atom:updated>2024-01-04T15:02:23.319Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KJ-JXa4CoPD8m8y6KZbVzg.png" /></figure><p>At <a href="https://www.koho.ca/">KOHO</a>, virtually every business decision is rooted in data-driven insights. Data is the cornerstone across all facets, influencing Product Research and Development, Marketing and Advertising, Financial Decision-Making, Risk Management, Customer Support, and Operations. At the heart of this data-driven approach lies our Modern Data Platform, which serves all the company&#39;s data needs. In this blog post, we’ll explore what a Data Platform is and its capabilities. We’ll discuss our strategy and architectural principles in building this platform, providing an architecture overview and a technical deep dive into each layer and capability.</p><blockquote>A quick note about our landscape and scale of growth: KOHO is a Fintech Startup first launched in 2017 with a mission to financially empower a generation of Canadians. We built financial products for spending, savings, cashback, credit building, budgets, goals, etc. Our user base grew from 250K in 2021 to 1 Million in 2023. Our users have spent, transferred, or deposited billions of dollars. With that context, let’s dive in.</blockquote><h3>What is a Data Platform, and what are its capabilities?</h3><p>A data platform, often called a ‘modern data stack,’ is the central nexus for an organization’s data ecosystem. This platform orchestrates the intricate processes of data collection, storage, processing, and application, catering to a spectrum of data products — from traditional business insights and dashboards to the more sophisticated domains of ML and AI engineering. Technically, it manifests as a collection of tools finely tuned to the nuances of data manipulation. Depending on the intended use of data, this toolbox encompasses:</p><p><strong>Managed and Scalable Ingestion Pipelines: </strong>Streamlined mechanisms for ingesting data into the ecosystem.</p><p><strong>Cloud-Based Data Lake/Data Warehouse: </strong>Robust infrastructure for secure, scalable storage and effective data management.</p><p><strong>Data Catalog, Access Controls, and Security Mechanisms: </strong>Governance components ensuring controlled access and security protocols.</p><p><strong>Data Transformation Tools: </strong>Robust utilities for refining, cleaning, and transforming raw data.</p><p><strong>Business Intelligence or Data Visualization Tools: </strong>Platforms facilitating the creation of insightful reports and dashboards.</p><p><strong>Machine Learning and Data Science Capabilities: </strong>Advanced tools for exploring data with machine learning and data science methodologies.</p><h3>Our Strategy and Architecture Principles</h3><p>We laid out our plan and rules when building our modern data platform. Here are some important choices we made based on the size of our organization, how complicated our data is, and what we need.</p><ol><li><strong>Avoid Multi-Cloud and Embrace Cloud Native</strong>: In our startup journey, we made some interesting decisions, like running apps on one cloud and the data warehouse on another — a practical move given our resources at the time. As we grew, the inefficiencies, complexities, and costs became apparent. Hiring became a two-cloud challenge. Check out <a href="https://www.lastweekinaws.com/blog/a_multicloud_rant/">this</a> for the famous multi-cloud rant. To tackle this, we shifted gears in early 2022 and started building a modern data platform, consolidating to one cloud and embracing cloud-native principles and managed services. The result? Streamlined operations, efficient integration, and welcome cost savings.</li><li><strong>Strategic Data Infrastructure: Build Core, Buy Smart:</strong> While numerous vendor products offer pre-built data warehouses and services, we chose a unique path — building our core data infrastructure and services in-house using AWS for components like Ingestion Pipelines, Data Lake, Warehouse, and Catalog. We complemented this with selective tool acquisition, opting for specialty tools like <a href="https://www.getdbt.com/">DBT</a> for transformation and <a href="https://www.sisense.com/">Sisense</a> for business intelligence. This strategy grants us complete control, flexibility, and extensibility of core data capabilities, coupled with best-in-class, purpose-built tools for seamless consumption.</li><li><strong>Unify and Centralize Data: </strong>Data silos pose a significant barrier to realizing the full potential of an organization’s data. Our solution: consolidating all data into a unified and centralized platform for comprehensive data management, a 360-degree view of customers, products, and business, and streamlined integration with effective governance.</li><li><strong>Data Quality and Security Come First: </strong>We prioritized data quality and security from the outset. Our platform incorporates data set registration services, schema validation pipelines, schema evolution, and data reconciliation checks to ensure the ingestion of high-quality data. Our security architecture adheres strictly to best practices, least privileged principles, and centralized access controls.</li><li><strong>Democratizing Data through Self-Service &amp; Automation</strong>: We architected the platform to allow data producers to self-register sources, automating the creation of pipelines, storage, processing, and warehouse tables. This guarantees smooth data availability for consumer teams, removing the necessity for central platform team intervention. Achieving seamless data availability and a Centralized Data Catalog marks essential strides in democratizing data.</li><li><strong>Design for Scalability and Extensibility: </strong>We maximize AWS fully managed services (like Lambda, Glue, Kinesis, and S3) rather than handling services on instances, saving time and boosting reliability and scalability. Additionally, we choose software and frameworks with built-in extensibility, such as Airflow, which enables seamless orchestration of diverse pipelines and easy reuse of connectors or custom-build operators.</li></ol><h3>The Overall Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2XB_ewMS3tPFI0tLhGpE2w.png" /></figure><p>As a cloud-born startup, our data platform is entirely cloud-based, akin to putting together puzzle pieces. Producers, our backend microservices, third-party sources like partners and vendors, mobile app click stream, etc., contribute data. Consumers, including data analytics, marketing, finance, product teams, etc., access data from the centralized platform. It orchestrates data ingestion from various sources (OLTP databases, event broker, third-party data) in different formats (JSON, Parquet, CSV) through diverse integration methods (Event Streaming, Database CDC replication, API, SFTP). AWS Kinesis Streams and DMS handle ingestion, AWS Managed Airflow orchestrates jobs, S3 serves as our Data Lake, Glue and DynamoDB catalogue data, Redshift stores it, DBT transforms, and Sisense visualizes. Think of it as crafting a cohesive story from diverse chapters. Additionally, our data platform facilitates ML and AI with Sagemaker and Bedrock. Now, let’s delve into the details of the primary building blocks in this intricate puzzle.</p><h3>Technical Deep Dive into each Building Block</h3><h4>Data Ingestion Pipelines</h4><p><strong>Event Streaming: </strong>Amazon MQ empowers our producer microservices. A custom event consumer feeds data to our data platform’s API supported by AWS API Gateway and a Fargate validation service; this API ensures that events adhere to registered schemas. Validated, high-quality events seamlessly flow through Kinesis streams to S3 in near real-time, enhancing data integrity for smooth integration into Redshift. Data from S3 is copied to Redshift using <a href="https://docs.aws.amazon.com/redshift/latest/dg/t_loading-tables-from-s3.html">COPY</a> jobs orchestrated by Airflow. Predefined structured tables in Redshift, aligned with event schemas, optimize query efficiency for our consumers, emphasizing our preference for structured tables in this pattern.</p><p><strong>Relational DB Data Movement</strong>: Our microservices leverage Aurora Serverless PostgreSQL. AWS Database Migration Service (DMS) acts as a CDC replication tool, mirroring data to S3. Custom ETL jobs orchestrated by Airflow split the multitenant data and upsert CDC data into Redshift. Explore this pipeline&#39;s detailed architecture, lessons learned, and insights in our blog post: <a href="https://medium.com/koho-tech-blog/getting-the-data-moved-postgresql-to-redshift-replication-with-aws-dms-466df13c38b0">Getting the Data Moved: PostgreSQL to Redshift Replication with AWS DMS</a>.</p><p><strong>Third-Party Data Integration:</strong> We’ve developed integration patterns for widely-used methods, such as SFTP Pull/Push and API-based integration, utilizing Airflow Custom Operators. This involves data ingestion into landing zone buckets, validation against registered schemas, transition to raw zone buckets, and loading into Redshift using COPY jobs.</p><p><strong>Schema Evolution: </strong>We dedicated a separate blog post to this common challenge in Data engineering<strong>. </strong>Please read our blog post, <a href="https://koho.dev/handling-schema-evolution-in-the-data-pipelines-at-koho-314472111477">Handling Schema Evolution in the Data Pipelines at KOHO</a>, on how we tackled it.</p><p><strong>Pipelines Orchestration:</strong> Another common but essential component. We use Amazon Managed Workflows for Apache Airflow(MWAA) as our central orchestration tool. Check out our blog post, <a href="https://medium.com/koho-tech-blog/running-airflow-at-scale-empowering-data-platform-at-koho-fc90ab669162">Running Airflow at Scale: Empowering Data Platform at KOHO</a>, for a deep dive, lessons learned, and insights.</p><p><strong>Monitoring and Operations: </strong>We use Datadog for monitoring and observability, along with PagerDuty for incident response. All the data infra, service logs, and metrics are shipped to Datadog with PagerDuty alerts for operational issues. Any airflow job failures are sent to respective teams through dedicated Slack channels.</p><h4>Data Catalog Powering Self-Served Data Infrastructure and Access</h4><p>A Data Catalog is like a library index for a company’s data, offering detailed information on datasets, schema definition, location, owner, etc. It’s a central resource for discovering, understanding, and utilizing data across the organization. We built it with a serverless API layer (API Gateway, Lambda, and Dynamo) to register and store dataset metadata. This metadata not only serves as a data catalogue but also automates infrastructure provisioning for storage (S3 buckets &amp; Redshift schema and tables), Ingestion (Kinesis Streams, Firehose, Airflow DAGs, COPY Jobs), and Access (IAM Policies). Every platform component is created with Infrastructure as Code using Terraform. The registration process is fully automated for sources with in-built metadata, such as Databases. However, for events and third-party data, the registration is done by data owners.</p><h4>Organizing the Data Lake</h4><p>Our S3 Data Lake is the central repository for various data types, including structured, semi-structured, and unstructured data in different zones, landing, raw, and curated data in different formats. From the outset, we prioritized effective organization and partitioning for streamlined access and usage. Essential techniques include standardized bucket naming and a logical hierarchy of data source, dataset group and dataset name, driven by producer-registered values, shaping bucket name and folder structures. For example, events follow a hierarchy of event owner(bucket name), event group(root directory), and event type(subdirectory). Data are further partitioned by version/YYYY/MM/DD/HH based on ingestion time, with metadata tags on all buckets. These practices collectively contribute to streamlined data access, enabling users to efficiently retrieve the information they need from the correct partitions. Additionally, effective organization reduces storage and retrieval costs, ensuring that only relevant portions are accessed when necessary. These allow writing IAM Policies and Access Controls programmatically, making the foundation for data security. The registration process also captures the data life cycle and retention requirements, which drives the automation of data transition to different storage tiers and data deletion based on the retention policies for the datasets.</p><h4>Our Redshift Journey</h4><p>Opting for Redshift as our Data Warehouse aligns with Cloud Native Architecture, offering seamless integration with AWS services. Despite the journey’s intricacies, Redshift’s price-performance and fit with our architecture make it worthwhile. Leveraging RA3 Nodes, we embraced the advantages of decoupled compute and storage — scaling and paying independently. Starting with ra3.xlplus, we transitioned to ra3.4xlarge as workloads increased. We implemented <a href="https://docs.aws.amazon.com/redshift/latest/dg/concurrency-scaling.html">Concurrent Scaling</a>, <a href="https://docs.aws.amazon.com/redshift/latest/dg/automatic-wlm.html">Auto WLM</a>, and fine-tuned performance with <a href="https://docs.aws.amazon.com/redshift/latest/dg/cm-c-wlm-query-monitoring-rules.html">Query Monitoring Rules</a>, detailed in our blog post ‘<a href="https://koho.dev/demystifying-redshift-a-closer-look-at-query-lifecycle-and-monitoring-rules-b5302cfd2d4b">Demystifying Redshift: A Closer Look at Query Lifecycle and Monitoring Rules.</a>’ Cost-effective provisioned clusters with Reservation Instances suit our workload, and we plan to maintain this approach as serverless offerings mature. We have adopted the Redshift Spectrum Lakehouse architecture for specific use cases requiring direct access to data from S3 without loading into the Redshift, mainly for infrequently accessed large volumes of data, for example, monthly and quarterly reporting. Currently, we are exploring the new Redshift ML feature for some of our classification model-based use cases. Our ongoing journey involves cluster segmentation based on workload using the DataSharing feature across multiple redshift clusters.</p><h4>Seamless Data Consumption</h4><p>We utilize Redshift Query Editor v2 for ad-hoc data exploration, with DBT steering the data transformation in our ELT architecture. Our Analytics Engineering team harnesses DBT to structure and model data, creating views and defining transformations for simplified data utilization in analytics and reporting tools. Data Analysts build Sisense Dashboards on tables created by DBT, ensuring seamless insights for our Business teams to make swift, data-driven decisions.</p><p>Our Data Science teams use Sagemaker Studio to access the data from S3 and Redshift to build, train, and deploy models using Sagemaker. Our AI Platform team is integrating selective data from the lake and warehouse for RAG and fine-tuning the FM models based on the use cases.</p><h3>Conclusion</h3><p>In today’s data-driven world, building a modern data platform isn’t just about understanding customers, products, and business and making decisions — it’s a key factor for fuelling innovation and excelling in the era of artificial intelligence. This tech blog has taken you through the core components of solid data foundations, the heart of success in the AI age. We explored KOHO’s data strategy and principles, unveiling how we built a scalable, flexible, and centralized modern data platform. As the Architect of this platform, I’m grateful for the teamwork of our data engineering, analytics engineering, data analysts, and various teams at KOHO. We hope sharing our journey will help your data strategy and efforts in building future-ready data platforms and products.</p><p>Thanks for reading !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83a1be799303" width="1" height="1" alt=""><hr><p><a href="https://koho.dev/how-we-built-the-modern-data-platform-at-koho-83a1be799303">How We Built the Modern Data Platform at KOHO</a> was originally published in <a href="https://koho.dev/">KOHO Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting the Data Moved: PostgreSQL to Redshift Replication with AWS DMS]]></title>
            <link>https://koho.dev/getting-the-data-moved-postgresql-to-redshift-replication-with-aws-dms-466df13c38b0?source=rss-ab6cc19fc3bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/466df13c38b0</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[redshift]]></category>
            <category><![CDATA[etl]]></category>
            <dc:creator><![CDATA[Manikandan Paramasivan]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 14:01:52 GMT</pubDate>
            <atom:updated>2023-10-31T14:01:52.277Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*fwdRepeItp5UIKlsMZM-QA.png" /></figure><p>In today’s data-driven landscape, the seamless replication of data from Online Transaction Processing (OLTP) databases to Online Analytical Processing (OLAP) data warehouses is a cornerstone of business intelligence and informed decision-making. Whether you’re harnessing insights for reporting, business analysis, ad hoc queries, operational excellence, or customer services, the accuracy and timeliness of your data are paramount. While numerous tools and services exist to address this timeless challenge, at KOHO, we have selected AWS DMS as the foundational solution. In this blog post, we will take a comprehensive look at AWS DMS, our process of replicating data from PostgreSQL databases to Redshift, and offer insights and lessons from our experience with AWS DMS.</p><h3><strong>Our Use Case and Context</strong></h3><p>We employ Aurora Serverless PostgreSQL as the primary OLTP database technology for numerous backend services, encompassing over 450 tables spread across ten databases designated for replication into our Data Warehouse. Our centralized Data Platform incorporates Data Ingestion Pipelines from diverse sources (internal, external, DBs, events, files), Data Lake, Data Warehouse, Data Catalog, BI tools, and more. Redshift is our central Data Warehouse, supporting data analytics across multiple organizational departments, including Product, Marketing, Finance, Ops, and Risk. Our primary objective is to expedite data ingestion into the warehouse, and after a thorough evaluation of various factors and trade-offs, we established a 1–2 hour SLA for PostgreSQL Data ingestion into Redshift. With this context in mind, let’s delve into the strategies we employed, the challenges we encountered, and the solutions implemented.</p><h3>AWS DMS Introduction and Terminologies</h3><p><a href="https://docs.aws.amazon.com/dms/latest/userguide/Welcome.html">AWS Database Migration Service (DMS)</a> is a fully managed service provided by Amazon Web Services(AWS) that simplifies migrating and replicating data between different database engines. Fundamentally, DMS functions as an intermediary between the source and target databases. It captures data from the source, temporarily stores it in its local memory or storage, applies transformations if configured, and loads it into the target database. Post-load, it also performs data validation to ensure the integrity and accuracy of the migrated data. Following are the components at a high level,</p><ol><li>Replication Instance: An intermediary compute resource handling data transfer and migration tasks.</li><li>Source Endpoint: Represents the source database and contains connection and authentication details.</li><li>Target Endpoint: Specifies the destination database and its connection settings.</li><li>Replication Task: Defines data migration, filters/mapping, transformation, schema conversion, and validation requirements.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*9-66REYWFia0BjeFxBwEOw.png" /></figure><p>There are three types of replication tasks,</p><ol><li>Full Load: Full load migration transfers all existing data from the source to the target database, creating an initial replica of the source dataset.</li><li>CDC (Change Data Capture): CDC migration captures and replicates real-time changes from the source to the target, ensuring the destination stays synchronized with the source.</li><li>Full Load and CDC: A combination of both full load and CDC migration types, initially transferring existing data and continuously replicating changes to maintain data consistency between the source and target databases.</li></ol><p>DMS supports migration between identical (homogeneous) and different (heterogeneous) database engines, supporting over 20 databases and analytics platforms like Oracle, MySQL, SQL Server, PostgreSQL, MongoDB, Redshift, S3, Kinesis, OpenSearch, and more. Refer to these AWS documentation for a comprehensive list of supported <a href="https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.html">sources</a> and <a href="https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.html">targets</a>.</p><p>While the overview may seem straightforward, it’s just the 10,000-foot perspective. Each replication type involves many settings tailored to the source, target, and diversity of data in play. Considering the complexity and constraints inherent to DMS, a deep dive into the AWS documentation is strongly advised. It’s crucial to align the service with your specific needs, particularly regarding limitations.</p><p>Now that you’ve got the lay of the land, let’s dive into how we roll with DMS for the PostgreSQL to Redshift migration.</p><h3>Our Solution Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r1rJvkn2rX4a1fjZpa67zA.png" /></figure><p>When efficiently replicating data from PostgreSQL to Redshift using DMS, you have a couple of paths to choose from. The straightforward route involves setting up PostgreSQL as the data source and Redshift as the target using the DMS Task. This method works well for basic data replication needs. However, it has limitations, such as not supporting certain ALTER TABLE statements and encountering issues with large VARCHAR columns exceeding 64 KB. For a complete list of these limitations, refer to <a href="https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Redshift.html#CHAP_Target.Redshift.Limitations">this</a>.</p><p>If your data replication demands more control and flexibility, especially if you need to denormalize, split, transform, or enhance your data before it arrives in Redshift, there’s a more versatile approach. Our own situation falls under this category. We opted to employ DMS Full Load and CDC tasks to continuously replicate data from PostgreSQL to Amazon S3 Buckets. Then, we applied our customized Extract, Transform, Load (ETL) processes to perform upserts into Redshift using the Redshift COPY command on an hourly schedule to load the previous hour&#39;s data from S3.</p><p>This architecture allows us to fine-tune the data transformation according to our needs. For instance, we have source tables with multi-tenanted data that require splitting and loading into separate Redshift tables. This involved various logic, from simple tenant identifier selection to complex cross-table joins and dependencies. This approach also allowed us to circumvent limitations with ALTER TABLE statements. When a breaking schema change occurs in the table, such as renaming a column or modifying data type, our pipeline automatically loads the data into the corresponding versioned Redshift table. This empowers us to manage schema evolution and maintain our data catalogue. For an in-depth exploration of our schema evolution practices at KOHO, please refer to our blog post <a href="https://koho.dev/handling-schema-evolution-in-the-data-pipelines-at-koho-314472111477">here</a>.</p><p>To execute this process, we run our custom ETL scripts using either AWS Glue or AWS Lambda. We seamlessly orchestrate the workflow through Amazon Managed Workflow for Apache Airflow (MWAA). For a comprehensive dive into our implementation of MWAA at KOHO, you can explore our detailed blog post <a href="https://medium.com/koho-tech-blog/running-airflow-at-scale-empowering-data-platform-at-koho-fc90ab669162">here</a>.</p><h3>Learnings &amp; Insights from Our Experience</h3><p>Below are some of the learnings and insights from our experience using DMS to replicate data from PostgreSQL to S3 to Redshift.</p><h4>1. Handling Partitioned Tables</h4><p>Migrating CDC Data from PostgreSQL using DMS can pose challenges when dealing with partitioned tables. Consider a scenario in which a “ sales” table is partitioned by the “year_month” column.</p><p>In your DMS tale mapping configuration, when you define the list of tables to be replicated and mention only “sales,” you’ll find that only the Full Load files are sent to the S3 target. The CDC data (inserts, updates, deletes) are not replicated to the S3 target. To overcome this issue, you need to add all the partition names to the DMS table mapping. DMS treats each partition as a separate table and stores the files in different folders within the S3 bucket. Here’s an example structure:</p><p><em>public</em>/<em>sales_2023_01</em>/20230123–1134010000.csv <em>public</em>/<em>sales_2023_02</em>/20230221–1214010000.csv</p><p>To make this data more accessible and usable, you’ll need to create a custom process. This process should aggregate all these files from different partition folders into a single folder. You can use S3 event notifications to trigger a Lambda function that moves the files to a unified folder structure with the table’s name, like this:</p><p><em>public</em>/<em>sales</em>/<em>2023_01</em>/20230123–1134010000.csv <em>public</em>/<em>sales</em>/<em>2023_02</em>/20230221–1214010000.csv</p><p>This transformation ensures that downstream processes can efficiently load the data into a single table in Redshift.</p><h4>2. Know your Data and Limitations</h4><p>Migrating data from PostgreSQL to Redshift can present challenges related to data types. PostgreSQL and Redshift differ in their supported data types, which can lead to issues during migration. Common problems include data type incompatibility, precision and scale differences, and handling unsupported data types. It’s essential to address these issues by mapping and transforming data types appropriately to ensure a smooth and accurate data migration process. Below are some of the data type issues we faced and how we solved</p><ol><li><strong>PostgreSQL JSON Data Types to Redshift JSON</strong>: When moving JSON data from PostgreSQL to Redshift, which has limited JSON support, we adapt by either using “SUPER” data types or flattening the JSON and loading it into separate columns.</li><li><strong>PostgreSQL Decimal to Redshift Decimal</strong>: While both databases support the “decimal” type, be mindful of precision and scale differences. Redshift has a max precision of 38 and a default scale of 0, while PostgreSQL allows higher precision and has no scale limits. Ensure your data fits within Redshift’s limits, possibly rounding or truncating if needed. In our case, we tackled this challenge by developing a schema crawler for our source PostgreSQL databases. We registered this crawler in our central data catalogue and analyzed all numeric data types to ensure they fell within the boundaries of Redshift’s numeric data types.</li><li><strong>PostgreSQL Text to Redshift Varchar: </strong>PostgreSQL’s “text” data type is equivalent to Redshift’s “varchar” type, but you should be mindful of potential length discrepancies. Ensure the length of your text data in PostgreSQL fits within the Varchar data type limit of 65535 bytes in Redshift to prevent truncation or issues with data integrity.</li><li><strong>Money Data Type and DMS CDC Plugin: </strong>During our testing, we encountered an unexpected issue with PostgreSQL’s “money” data type when using the “pglogical” plugin in DMS. The data was incorrectly written by DMS as “0.0” in the S3 target. After considerable research and discussions with AWS support, we found the solution by configuring the DMS source endpoint to use the “test_decoding” plugin. This experience serves as a reminder of the importance of rigorous testing. Data integrity is paramount, and it’s essential to focus on the volume of data and ensure its accuracy during the replication process.</li></ol><h4>3. Lambda and COPY Command Combo</h4><p>The <a href="https://docs.aws.amazon.com/redshift/latest/dg/r_COPY.html">COPY</a> command is the optimal choice for loading data from S3 into Redshift, thanks to its speed and simplicity, making it an excellent solution. When using Lambda or Glue to trigger the COPY command, Lambda stands out as a cost-effective alternative, especially for smaller CDC files. The smaller size of CDC files means Lambda’s timeout isn’t a concern, making it a compelling and budget-friendly option to automate COPY commands in Redshift, with potential cost savings in mind.</p><h4>4. Tuning the DMS Task Settings is the Key to Success</h4><p>DMS offers a plethora of configuration settings at both the endpoint and task levels, allowing you to fine-tune the migration process according to your specific source, target, and task type. These settings dictate which tables to include or exclude, the level of parallelism, validation rules, change processing methods, and more. Tailoring these settings to your unique scenario is crucial for optimizing performance and efficiency in your data migration. Below are some of the critical settings that deserve close attention.</p><p><strong>TargetMetadata: </strong>LOB settings — Mode, LobChunkSize, LobMaxSize, BatchApplyEnabled, ParallelLoadThreads, ParallelApplyThreads</p><p><strong>FullLoadSettings: </strong>MaxFullLoadSubTasks, CommitRate, TransactionConsistencyTimeout</p><p><strong>ChangeProcessingTuning</strong>: BatchApplyEnabled, BatchApplyPreserveTransaction, BatchApplyMemoryLimit, BatchSplitSize, MinTransactionSize, CommitTimeout, MemoryLimitTotal, MemoryKeepTime</p><p>ErrorBehavior, Logging Severity<strong>, </strong>ValidationSettings, and ChangeProcessingDdlHandlingPolicy are additional critical settings to consider. For a comprehensive list of settings, please consult <a href="https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tasks.CustomizingTasks.TaskSettings.html">this documentation</a>.</p><h4>5. Right Size the Infrastructure and Monitor the Key Metrics</h4><p>Properly sizing replication instance, which comes in different vCPUs and memory, is the key to ensuring sufficient resources to handle the workload. Choosing the appropriate replication instance depends on several factors like task type — Full load, CDC or full load and CDC, performance requirements, parallelism, database and table size, LOB Data, and various settings we discussed above. It’s important to note that you have flexibility in organizing your replication tasks within your instances, allowing you to align them with your workload requirements and the nature of the tasks. In our specific case, we’ve chosen to run all of our tasks within a single, larger instance equipped with Multi-AZ deployment based on our needs. At the end of the day, right-sizing is all about understanding your workload, load testing, and monitoring key metrics. AWS DMS integrates well with Cloudwatch, and there are metrics at the DMS instance level and each task level. Following are some of the key metrics to monitor</p><p><strong>Instance Metrics: </strong>CPUUtilization, FreeableMemory, SwapUsage, ReadIOPS, WriteIOPS, ReadThroughput, WriteThroughput, ReadLatency, WriteLatency, DiskQueueDepth</p><p><strong>Task Metrics: </strong>FullLoadThroughputBandwidthTarget, FullLoadThroughputRowsTarget, CDCIncomingChanges, CDCLatencySource, CDCLatencyTarget, CDCChangesMemorySource, CDCChangesMemoryTarget, CDCChangesDiskSource, CDCChangesDiskTarget</p><p>Maintaining your DMS Replication Task in “Running” status is crucial, particularly when utilizing a CDC Task, to prevent increased transaction log disk usage. This is essential because if the task is not consuming from the replication slot, it can lead to the uncontrolled growth of the replication slot and affect your database. Monitoring both the transaction log disk usage on the source database and the DMS Task Status ensures timely issue detection and resolution.</p><p>For a comprehensive list and in-depth information about these metrics, refer to <a href="https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Monitoring.html#CHAP_Monitoring.Metrics">this</a>.</p><h3>Closing Thoughts</h3><p>In our journey of replicating data from an OLTP database to an OLAP data warehouse, our experience of using AWS DMS has been largely positive, which frees us from worrying about the infrastructure management and the intricacies of the replication engine. It’s a powerful ally that allows us to focus on what matters most — our data. Along the way, we encountered challenges and learning opportunities. Understanding data type disparities, adeptly navigating DMS capabilities and limitations, fine-tuning task settings, making thoughtful instance choices, and diligent monitoring have been the linchpins of ensuring the smooth operation of our data replication. We hope sharing our journey will help your data migration strategy and efforts.</p><p>Thanks for reading !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=466df13c38b0" width="1" height="1" alt=""><hr><p><a href="https://koho.dev/getting-the-data-moved-postgresql-to-redshift-replication-with-aws-dms-466df13c38b0">Getting the Data Moved: PostgreSQL to Redshift Replication with AWS DMS</a> was originally published in <a href="https://koho.dev/">KOHO Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Airflow at Scale: Empowering Data Platform at KOHO]]></title>
            <link>https://koho.dev/running-airflow-at-scale-empowering-data-platform-at-koho-fc90ab669162?source=rss-ab6cc19fc3bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc90ab669162</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[data-platforms]]></category>
            <category><![CDATA[aws-mwaa]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <dc:creator><![CDATA[Manikandan Paramasivan]]></dc:creator>
            <pubDate>Wed, 05 Jul 2023 14:02:11 GMT</pubDate>
            <atom:updated>2023-07-05T14:02:11.993Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*gwtMmiUiK-mK2YCq0D53SQ.png" /></figure><p>In the modern data-driven era, organizations face unprecedented challenges in managing vast amounts of data efficiently and reliably. Data engineering and developing robust data pipelines are critical components of successful data platforms. Data engineering lays the foundation for effective data analysis, data-driven decision-making, and the development of intelligent applications. Data pipelines form the backbone of data engineering, enabling the seamless flow of data from various sources, through processing and transformation, to its final destination for consumption and analysis.</p><p><strong>The Challenges of Scaling Data Workflows:</strong> As organizations grow and the volume, variety, and velocity of data increase, scaling data workflows becomes increasingly complex. Managing dependencies, orchestrating tasks, handling data transformations, and ensuring fault tolerance are just a few of the challenges data engineers face. Additionally, the need for scalability, automation, and monitoring further complicates the development and management of data pipelines.</p><h3>Enter Apache Airflow</h3><p><a href="https://airflow.apache.org/docs/apache-airflow/stable/index.html">Apache Airflow</a> has emerged as a powerful solution for managing and orchestrating data workflows at scale. With its intuitive interface and rich set of features, Airflow enables data engineers to design, schedule, and monitor complex workflows easily. Its unique <a href="https://en.wikipedia.org/wiki/Directed_acyclic_graph">Directed Acyclic Graph (DAG)</a> structure visually represents task dependencies, making it easier to manage complex workflows and ensure the correct order of execution. Here are some of the key terminologies in Airflow:</p><ol><li>DAG: Represents a workflow consisting of tasks and their dependencies.</li><li>DAG Run: Represents a specific instantiation of a DAG for execution.</li><li>Task: An instance of an operator within a DAG.</li><li>Task Instance: Represents the execution of a specific task within a DAG.</li><li>Operator: Defines individual tasks within a DAG.</li><li>Hooks: Enables interaction with external systems or services within tasks.</li></ol><p>For a complete list and details, refer to <a href="https://airflow.apache.org/docs/apache-airflow/stable/core-concepts/index.html">Apache Airflow Docs</a>.</p><h3>Our Use Case &amp; How We Run Airflow</h3><p>At KOHO, our Centralized Data Platform is responsible for ingesting data from multiple data sources into our Data Lake and Data Warehouse hosted in AWS. These sources include our Online Transaction Processing (OLTP) Databases, Events produced by Backend and Front End systems, Data from our 3rd Parties, and Vendor and Partner systems. These data come in different formats — <a href="https://www.json.org/json-en.html">JSON</a>, <a href="https://parquet.apache.org/">Parquet</a>, CSV(Comma Separated Values) Files, Text Files, Fixed Width Format Files, Google Sheets, Excel files etc. through different integration methods — DB Change Data Capture (<a href="https://en.wikipedia.org/wiki/Change_data_capture">CDC</a>), API, <a href="https://en.wikipedia.org/wiki/SSH_File_Transfer_Protocol">SFTP</a>, etc. and in different schedule. We use Apache Airflow for orchestrating, scheduling, and monitoring all the data ingestion pipelines consisting of task sequences from data source integration, data validation, transformation, and versioning to loading into Data Lake(<a href="https://aws.amazon.com/s3/">S3</a>) and Data Warehouse (<a href="https://aws.amazon.com/redshift/">Redshift</a>).</p><p>Our Data Platform has around 1000 DAGs with 2 to 4 tasks each, Running over 28000 DAG runs/day and over 75000 Task Instances/day. That&#39;s a lot of tasks. We made some trade-offs on various factors and decided to have DAG per dataset, with observability as a critical factor. Also, we aim to get the data into the warehouse as quickly as possible, so our schedules are typically every 30 to 60 mins. Our tasks are built to run fast, usually between a few seconds to a few minutes, triggering <a href="https://aws.amazon.com/lambda/">lambda</a> or <a href="https://aws.amazon.com/glue/">glue</a> and <a href="https://docs.aws.amazon.com/redshift/latest/dg/r_COPY.html">redshift copy commands</a>.</p><p><strong>How we Deploy:</strong> We don&#39;t (ourselves). With so many pipelines and tasks with different schedules, formats, and complexities, we wanted to focus on processing our data rather than hosting and managing the Airflow Cluster infrastructure in something like <a href="https://aws.amazon.com/ec2/">EC2</a>, <a href="https://aws.amazon.com/ecs/">ECS</a> or <a href="https://kubernetes.io/">Kubernetes</a> etc. We have decided to use <a href="https://docs.aws.amazon.com/mwaa/latest/userguide/what-is-mwaa.html">Amazon Managed Workflow for Apache Airflow (MWAA)</a>.</p><h3>Amazon Managed Workflow for Apache Airflow (MWAA)</h3><p>MWAA is a fully managed service provided by <a href="https://aws.amazon.com/">Amazon Web Services (AWS)</a> that simplifies the deployment, scaling, and management of Airflow in the cloud. With Amazon MWAA, running Airflow at scale becomes seamless and efficient. Here are some key advantages:</p><ol><li>Scalability and elasticity to handle large workloads efficiently.</li><li>Fully managed service, relieving the burden of infrastructure management.</li><li>Built-in high availability features for reliable and uninterrupted operation.</li><li>Robust security measures and compliance capabilities.</li><li>Seamless integration with other AWS services for enhanced functionality.</li><li>Comprehensive monitoring and logging for visibility into workflow performance.</li></ol><p><strong>Under the Hood:</strong></p><p>Here is the architecture of MWAA from <a href="https://docs.aws.amazon.com/mwaa/latest/userguide/what-is-mwaa.html#architecture-mwaa">AWS Docs</a>. Amazon MWAA deploys the Schedulers and Workers in our VPC, and the Meta DB and Webserver are managed in Service VPC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rOzlv3lT9hNXV_JwRQ5r4Q.png" /></figure><p>As a customer of MWAA, We have options to configure the Airflow Environment Classes — Small, Medium, and Large which come with different CPU and DAG Capacity. Then we can select the number of schedulers and workers based on our workload. The pricing has two components — The environment hourly rate and the number of additional workers and schedulers provisioned. Autoscaling is built-in for workers, and we must set the minimum and max workers. MWAA requires you to write the DAG python files and the requirements.txt for the dependencies in the S3 bucket configured for the cluster. Airflow Configuration Parameters can be <a href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">customized</a> as environment variables.</p><h3>Learnings &amp; Best Practices from Our Experience</h3><p>Below are some of the learnings and best practices from our Experience running Airflow (in MWAA) at Scale.</p><h4>1. Right-Sizing the Infrastructure</h4><p>Properly sizing the environment class, the number of schedulers, worker nodes based on the number of DAGs, task execution time, and concurrency requirements is the key to ensuring sufficient resources to handle the workload. This alignment helps to avoid resource constraints on undersized clusters or unnecessary costs associated with oversized clusters. There is no magic formula to get that right, and it&#39;s all about understanding the workload, load testing, and monitoring key metrics.</p><p>This <a href="https://docs.aws.amazon.com/mwaa/latest/userguide/environment-class.html">AWS Doc</a> guides the number of DAGs and CPU allocated for each environment class. As per this doc, a large environment can handle up to 1000 DAGs under typical usage. We started with 800 DAGs in a large environment with two schedulers and ten additional workers. For our workload, we quickly recognized that the environment is under-provisioned and unable to handle spikes in workload caused by backfill runs or if our tasks take a few minutes longer due to the downstream systems being slow or unavailable. The metrics that highlighted the under-provisioning were workers and database CPU utilization. Because the bottleneck is really at the meta DB level, which MWAA users don&#39;t have control of, adding more workers didn&#39;t help either. So we decided to split the workloads equally into two separate large MWAA Clusters, with fewer workers in each cluster. This gives us more room for scaling during the backfills and adding additional DAGs.</p><h4>2. Dynamic DAGs Generation</h4><p>Traditional DAG generation in Airflow requires uploading static Python code for each DAG, while dynamic DAGs allow programmatically generating and modifying workflows based on dynamic conditions or data. Dynamic DAGs are best suited when dealing with a large number of similar tasks and complex, data-driven workflows, offering increased agility, reduced development effort, and easier maintenance. Though we have many DAGs, most of our DAGs fall into 5–6 patterns and run similar tasks. So Dynamic DAGs are an excellent choice for our use case. They significantly reduce the development time, and adding a new DAG is automatically done.</p><p><strong>How to Generate DAGs dynamically: </strong>We add dynamic DAGs in Airflow using the globals() function. You can follow the sample code snippet below. We keep all our dataset&#39;s metadata in a central data catalogue and expose that through API. We developed a dag generator that calls the API to get the metadata and adds the DAGs in globals().</p><pre>for dag_id in dynamic_dag_ids:<br>    dag = DAG(dag_id=dag_id, schedule_interval=&#39;@daily&#39;)  # Create a new DAG dynamically<br>    # Add tasks and dependencies to the DAG dynamically<br>    task1 = BashOperator(task_id=&#39;task1&#39;, bash_command=&#39;echo &quot;Task 1&quot;&#39;, dag=dag)<br>    task2 = BashOperator(task_id=&#39;task2&#39;, bash_command=&#39;echo &quot;Task 2&quot;&#39;, dag=dag)<br>    task1 &gt;&gt; task2  # Set task dependencies<br>    globals()[dag_id] = dag  # Add the DAG to the global namespace\</pre><p><strong>Dynamic DAGs Performance Tuning Tip: </strong>With Dynamic DAGs, we noticed that our DAG parsing time was high, and it&#39;s because of the API call to get the metadata every time airflow parses the dags. It&#39;s recommended to keep these metadata or any config files used for generating DAGs in the local file system in the airflow cluster. Traditionally, you would ship it along with the image in a self-hosted airflow cluster. In Amazon MWAA, you can write those files in the same S3 prefix as the DAGs, and MWAA will put those in each node&#39;s file system. So we built automation to push the schema file to S3 every time the dataset catalogue changes and replaced the API call with the code to read from the local file system in our DAG Generator. This reduced the DAG parsing time from over a minute to less than a second. Considering the number of times the DAG parsing runs continuously in a loop, this tuning significantly reduced the load on the scheduler.</p><h4>3. Distribute the Schedule and Workload</h4><p>It&#39;s always quick and easy to schedule all the hourly schedules starting at the 0th or xth minute of an hour. But this has a significant implication on resource usage. Distributing the hourly schedule throughout the hour in Apache Airflow, rather than always at the start, helps to distribute the workload and prevent resource usage spikes evenly. This approach ensures a smoother execution of tasks, avoids congestion, and optimizes resource utilization, leading to better overall performance and stability in Airflow. While generating the DAGs dynamically, we also set the schedule of the DAGs evenly distributed throughout the hour but still considered the SLAs for datasets. So some DAGs would start at the 5th minute, some 16th minute, and some at the 45th minute, etc. This optimized the Workers &amp; DB Writer and Reader CPU Average from spiking at 85-90% every hour to 30–40% throughout the hour, enabling us to reduce the number of workers further and save on cost.</p><p>Another strategy we follow is to use Airflow as an orchestration, scheduling, and monitoring tool and offload any data processing to the components like Lambda, Glue, EMR, etc. This enables scaling those components independently per the data processing needs rather than putting all the pressure on the Airflow Cluster.</p><h4>4. Tuning the Airflow Configuration is the Key to Success</h4><p>Tuning the Apache Airflow configuration parameters is crucial for achieving optimal performance, scalability, and resiliency in your data workflows. Here are some of the important parameters,</p><ol><li>parallelism: Controls concurrent task execution, enabling efficient resource utilization and increased throughput. In MWAA, this value depends on worker_autoscale, environment class, and the number of schedulers.</li><li>dag_concurrency: Sets the maximum number of simultaneous DAG executions, allowing for scalable workflow concurrency.</li><li>worker_autoscale: The maximum and minimum number of tasks that can run concurrently on any worker using the <a href="https://airflow.apache.org/docs/apache-airflow/stable/core-concepts/executor/celery.html">celery_executor</a>.</li><li>max_active_runs_per_dag: Prevents system overload by limiting the number of active DAG runs at any given time.</li><li>executor: Selecting the appropriate executor optimizes task execution based on infrastructure capabilities and workload characteristics. MWAA uses celery_executor by default.</li><li>dag_file_processor_timeout: Extending the timeout accommodates large or complex DAG parsing to avoid timeouts.</li><li>dag_dir_list_interval: Refreshing DAG lists at regular intervals ensures responsiveness to changes in the DAG directory, i.e., S3 DAG Prefix in case MWAA.</li></ol><p>MWAA default values for these configurations may or may not work for your workload. Considering it&#39;s a Managed Service and complexities in airflow in general, it&#39;s hard for the service to set the right values for all kinds of workloads. The good news is that it allows you to tune these settings per your workload needs. We spent quite a lot of time tuning the above and more. One of the lessons we learned is that, while aiming for high concurrency and scaling, it&#39;s also essential to set the upper boundaries to avoid overloading and impacting the Airflow Meta DB. For example, creating pools for different groups of tasks and setting limits for the known long-running tasks pool is one of the ways to prevent impacts due to downstream systems failure.</p><h4>5. Monitoring and Observability</h4><p>Monitoring and observability play a crucial role in ensuring the smooth and efficient operation of Apache Airflow. Amazon MWAA provides the below key features for monitoring,</p><ol><li>CloudWatch Integration: MWAA seamlessly integrates with CloudWatch, enabling you to monitor and analyze metrics, logs, and events related to your Airflow environment.</li><li>Environment and DAG Metrics: MWAA provides metrics at the environment and DAG level, allowing you to monitor the health, performance, and execution status of your Airflow workflows.</li><li>Logging with S3 and CloudTrail: MWAA stores Airflow logs in Amazon S3 and integrates with CloudTrail for enhanced visibility and auditing capabilities.</li></ol><p>Below are some of the critical metrics we monitor in Amazon MWAA.</p><ol><li>Average CPU Utilization for Schedulers, Workers, WebServers, DB Writer and Reader</li><li>Scheduler Heartbeat</li><li>Queued and Running Tasks Count</li><li>Task Landing Time and Task Duration</li><li>DAG Parsing Time</li></ol><p>Note that MWAA has CloudWatch Metrics under two namespaces — Free metrics are under the MWAA and Custom Metrics are under AmazonMWAABased on the number of task runs, custom metrics costs can go high because MWAA enables all the metrics by default. There is an option to <a href="https://docs.aws.amazon.com/mwaa/latest/userguide/access-metrics-cw-202.html#choosing-metrics">choose</a> which custom airflow metrics to send to CloudWatch. Apart from the environment-level health check and monitors, We also built an integration with Slack to notify the DAG Failures so that teams can enhance their incident response capabilities, foster collaboration, and improve overall workflow management.</p><h3>Closing Thoughts</h3><p>In conclusion, running Apache Airflow at scale empowers our data platform by enabling efficient and reliable data workflows. With the ability to manage complex dependencies, schedule tasks, and monitor workflow execution, Airflow is a vital tool for data engineers and scientists. Amazon Managed Workflows for Apache Airflow (MWAA) offers valuable benefits for streamlining data workflows with simplified infrastructure management, automated scaling, and reduced operational overhead. Continuous improvement through infra optimization for the workload, Airflow configuration tuning, and following the best practices is crucial.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc90ab669162" width="1" height="1" alt=""><hr><p><a href="https://koho.dev/running-airflow-at-scale-empowering-data-platform-at-koho-fc90ab669162">Running Airflow at Scale: Empowering Data Platform at KOHO</a> was originally published in <a href="https://koho.dev/">KOHO Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>