Change Data Capture

4 posts

meta3 min readCurated summary

Migrating Data Ingestion Systems at Meta Scale

Meta rebuilt its hyperscale MySQL data ingestion system to improve reliability, efficiency, and data-langing latency. The migration moved workloads from customer-owned pipelines to a simpler, self-managed warehouse service and ultimately transitioned 100% of jobs. Success depended on staged validation, continuous data comparison, and fast rollback mechanisms. ## Why Meta Migrated - The system incrementally moved several petabytes of social graph data from MySQL into Meta’s data warehouse each day. - This data supports analytics, reporting, machine learning, and product development. - The legacy architecture became increasingly unstable as data-landing requirements grew stricter. - Customer-owned pipelines worked at smaller scales but became difficult to manage reliably at hyperscale. ## Migration Success Criteria Each job had to meet defined requirements before advancing: - **Data correctness:** Old and new systems had matching row counts and checksums. - **Landing latency:** The new system performed at least as well as the legacy system. - **Resource usage:** Compute and storage consumption did not regress. - **Critical-table requirements:** Additional criteria were agreed upon with dependent teams. ## Three-Phase Migration Lifecycle ### Shadow Phase - New-system shadow jobs ran against the same production sources as existing jobs. - Their output was written to separate shadow tables. - Row counts and checksums were continuously compared with production data. - Compute and storage requirements were measured before production rollout. - Once validated in pre-production, shadow jobs were tested in production. ### Reverse Shadow Phase - The new system began writing to the production table. - The legacy system continued running, but wrote to a shadow table. - This preserved continuous comparison between both systems. - If discrepancies appeared, Meta could quickly restore the old system without rebuilding its configuration. ### Migration Cleanup - Both systems continued to be monitored for mismatches. - After validation, the legacy shadow job was removed. - The new system became the sole production pipeline. ## Data Quality and Debugging Tooling - Meta built tooling to compare corresponding table partitions from the two systems. - Comparisons included row counts, checksums, and example rows responsible for mismatches. - Mismatch records and debugging details were logged to Scuba for real-time analysis. - Hourly queries helped engineers identify root causes and determine whether issues were already known. - The same tooling remains part of post-migration release validation. ## Rollout and Rollback Controls - Both systems used change data capture (CDC), with internal full-dump and delta tables feeding customer-facing target tables. - Because CDC builds new data from previously landed data, an existing defect could propagate after migration. - Meta therefore emphasized: - Detecting problems before they reached data consumers. - Stopping further propagation quickly during rollback. - The reverse-shadow design provided early quality signals and preserved a ready-to-use legacy pipeline for rapid recovery. Meta’s migration demonstrates that large-scale infrastructure changes are safest when treated as controlled, observable lifecycle transitions rather than one-time cutovers. Parallel execution, automated data validation, explicit resource checks, and reversible rollouts enabled the company to migrate the entire workload while protecting downstream consumers.

Read original(opens in new tab)
pinterest3 min readCurated summary

Next Generation DB Ingestion at Pinterest

Pinterest replaced fragmented, batch-oriented database ingestion with a unified Change Data Capture (CDC) framework. The new architecture uses Debezium/TiCDC, Kafka, Flink, Spark, and Iceberg to process only changed records, reducing latency from over 24 hours to minutes while lowering infrastructure costs. It also provides native row-level deletion, scalable operations, and improved compliance. ## Problems with the Legacy System - Batch workflows often delayed updates by more than 24 hours. - Full-table processing was inefficient because many tables changed by less than 5% each day. - Lack of row-level deletion support complicated data compliance. - Multiple independently maintained pipelines created operational complexity and inconsistent data quality. ## Unified CDC-Based Architecture - Supports MySQL, TiDB, and KVStore. - Captures database changes through a generic CDC service and publishes them to Kafka, typically in under one second. - Flink processes events in near real time and stores them in append-only CDC Iceberg tables on S3. - Spark jobs run periodically—often every 15 minutes—to merge recent changes into base Iceberg tables. - A bootstrap pipeline initializes base tables from historical database dumps. - Maintenance jobs handle compaction and snapshot expiration. - The framework is designed for at-least-once processing, petabyte-scale data, thousands of pipelines, and YAML-based configuration. ## CDC Tables and Base Tables - CDC tables act as time-series ledgers containing every change event. - CDC data typically becomes available within five minutes. - Base tables mirror the current state of the source database while retaining historical records. - Base-table latency is generally between 15 minutes and one hour. ## Upserting Changes into Base Tables - Spark first identifies the newest event for each primary key. - Events are ranked by timestamp and GTID, then deduplicated. - Iceberg’s `MERGE INTO` applies the resulting changes: - Deletes matching records when the event represents a deletion. - Updates existing records. - Inserts new records unless the event is a deletion. - The process uses a recent CDC window and a processing watermark to avoid reprocessing unnecessary data. ## Choosing Merge-on-Read - Pinterest standardized on Iceberg’s Merge-on-Read (MOR) strategy. - Copy-on-Write (COW) was rejected for most workloads because: - It requires more computation during writes. - It produces substantially larger replacement files, increasing storage costs. - MOR better balances update performance and storage efficiency for frequent incremental changes. ## Partitioning for Faster Upserts - Large base tables can be partitioned using a hash bucket of the primary key. - For example, `bucket(100, id)` distributes records across 100 partitions. - This allows Spark to process partitions in parallel and reduces the data scanned or rewritten during merges. - Iceberg tables are configured with format version 2, identifier fields, merge-on-read update and delete modes, and target file sizes. ## Small-File Challenge - Bucketing improved parallelism but caused each upsert to generate many small files within partitions. - The article indicates that Pinterest investigated this bottleneck and introduced further optimizations, though the supplied excerpt ends before describing them. Pinterest’s CDC-based design provides a substantially faster and more efficient alternative to full-table batch ingestion. Teams adopting a similar system should combine incremental CDC processing with partitioning, merge-on-read storage, bootstrapping, and ongoing file-maintenance strategies.

Read original(opens in new tab)
daangnOriginal article

No Need to Fetch Everything Every Time (opens in new tab)

To optimize data synchronization and ensure production stability, Daangn’s data engineering team transitioned their MongoDB data pipeline from a resource-intensive full-dump method to a Change Data Capture (CDC) architecture. By leveraging Flink CDC, the team successfully reduced database CPU usage to under 60% while consistently meeting a two-hour data delivery Service Level Objective (SLO). This shift enables efficient, schema-agnostic data replication to BigQuery, facilitating high-scale analysis without compromising the performance of live services. ### Limitations of Traditional Dump Methods * The previous Spark Connector-based approach required full table scans, leading to a direct trade-off between hitting delivery deadlines and maintaining database health. * Increasing data volumes caused significant CPU spikes, threatening the stability of transaction processing in production environments. * Standard incremental loads were unreliable because many collections lacked consistent `updated_at` fields or required the tracking of hard deletes, which full dumps handle poorly at scale. ### Advantages of Flink CDC for MongoDB * Flink CDC provides native support for MongoDB Change Streams, allowing the system to read the Oplog directly and use resume tokens to restart from specific failure points. * The framework’s checkpointing mechanism ensures "Exactly-Once" processing by periodically saving the pipeline state to distributed storage like GCS or S3. * Unlike standalone tools like Debezium, Flink allows for an integrated "Extract-Transform-Load" (ETL) flow within a single job, reducing operational complexity and the need for intermediate message queues. * The architecture is horizontally scalable, meaning TaskManagers can be increased to handle sudden bursts in event volume without re-architecting the pipeline. ### Pipeline Architecture and Processing Logic * The core engine monitors MongoDB write operations (Insert, Update, Delete) in real-time via Change Streams and transmits them to BigQuery. * An hourly batch process is utilized rather than pure real-time streaming to prioritize operational stability, idempotency, and easier recovery from failures. * The downstream pipeline includes a Schema Evolution step that automatically detects and adds new fields to BigQuery tables, ensuring the NoSQL-to-SQL transition is seamless. * Data processing involves deduplicating recent change events and merging them into a raw JSON table before materializing them into a final structured table for end-users. For organizations managing large-scale MongoDB clusters, implementing Flink CDC serves as a powerful solution to balance analytical requirements with database performance. Prioritizing a robust, batch-integrated CDC flow allows teams to meet strict delivery targets and maintain data integrity without the infrastructure overhead of a fully real-time streaming system.

figma4 min readCurated summary

From Multi-Day Latency to Near Real-Time Insights: Figma’s Data Pipeline Upgrade | Figma Blog

Figma replaced a daily full-table export system that could take hours or days with an incremental synchronization pipeline designed for near real-time analytics. The new architecture combines database snapshots, change data capture (CDC), and Snowflake merge logic to transfer only recent changes. By building the system in-house, Figma gained greater flexibility, lower projected costs, and a design that can scale with continued growth. ## Why the Legacy Pipeline Failed - Since 2020, a daily cron job ran `SELECT * FROM <TABLE>`, exported results to S3, and loaded them into Snowflake. - As Figma’s tables and insert volume grew: - Daily syncs reached roughly six hours by 2023. - The largest tables took several days or longer. - Additional database replicas were required for exports. - Replica maintenance cost millions of dollars annually. - The delays limited access to timely company KPIs and analytical insights. ## Choosing Incremental Synchronization Figma evaluated three options: - Continue using the legacy process, which was increasingly expensive and too slow. - Add parallelism, which might improve throughput temporarily but would not scale sustainably. - Rebuild the synchronization system around incremental updates. Incremental synchronization transfers only new and changed records instead of repeatedly copying entire tables, reducing data movement, processing time, and infrastructure usage. ## Buy vs. Build Figma decided to build the pipeline internally because available proprietary tools did not meet its requirements. - **Flexibility:** Generic SQL tools did not take advantage of capabilities such as Amazon RDS for PostgreSQL snapshot exports. - **Cost:** Commercial solutions were projected to cost five to ten times more than an in-house implementation. - **Scale:** Building internally allowed Figma to optimize the system for its infrastructure and adapt it as the company grows. ## Pipeline Components The bespoke system combines several lower-level technologies: - **Snapshots:** Amazon RDS exports initial table copies to S3. - **Change data capture:** Kafka Connect streams database changes through Amazon MSK. - **Warehouse ingestion:** A Snowflake Connector loads CDC events into Snowflake. - **Incremental merging:** Custom Snowflake stored procedures and scheduled tasks merge changes into base tables. ## Architecture Principles The redesign was guided by four goals: - Reduce end-to-end synchronization latency. - Control costs as data volume increases. - Meet regulatory and compliance requirements. - Preserve data accuracy, completeness, consistency, and trustworthiness. The resulting architecture uses two workflows: a bootstrap workflow for onboarding tables and a validation workflow for checking data correctness. ## Bootstrap Workflow The automated onboarding process includes: - The CDC service begins capturing the new Postgres table and publishes events to a per-table Kafka topic. - Amazon RDS exports the latest database snapshot to S3. - Snowflake’s `COPY INTO <table>` loads the snapshot into a per-entity base table. - An MSK Connect Snowflake Sink Connector streams Kafka events into a separate CDC table, with offsets arranged so changes before the snapshot timestamp are retained. - A scheduled Snowflake task runs a custom `MERGE` procedure to combine the snapshot and CDC data. - Once the process catches up with current changes, Figma creates a lightweight user-facing view over the base table. ## Zero-Downtime Re-Bootstrapping - Bootstrap artifacts are versioned, while the final user-facing view remains stable. - New versions can be built in parallel without interrupting queries. - Promotion is completed through an atomic view update. - This supports schema evolution and other situations requiring a fresh bootstrap without downtime. ## Data Validation - Even well-designed pipelines can suffer corruption from partial failures, configuration errors, software bugs, or unexpected source-data anomalies. - Figma therefore added a validation workflow to verify correctness as data moves through snapshot exports, CDC capture, and incremental merging. Figma’s experience shows that incremental synchronization is a more sustainable alternative to repeated full-table exports. Combining managed infrastructure with custom orchestration can deliver lower latency, better cost control, and stronger operational flexibility than a one-size-fits-all commercial pipeline.

Read original(opens in new tab)