Handling Duplicate Data
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 12 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Handling Duplicate Data in Batch Ingestion Pipelines
Introduction: The Silent Corruption of Data Integrity
In the world of data engineering, batch ingestion is the process of moving large volumes of data from source systems to a destination, such as a data warehouse or a data lake, at scheduled intervals. While the mechanics of moving data—extracting, transforming, and loading—are well-understood, the reality of production environments is far messier than the theoretical diagrams suggest. One of the most persistent and damaging issues engineers face is the presence of duplicate data. Whether it is caused by network retries, source system glitches, or overlapping extraction windows, duplicates can quietly poison your analytics.
If your data pipeline processes sales records and captures the same transaction twice, your revenue reporting will be inflated. If you are tracking user behavior, duplicates can lead to incorrect conversion rates and skewed A/B test results. Handling duplicate data is not just a "nice-to-have" cleanup task; it is a foundational requirement for building trust in your data platform. In this lesson, we will explore the lifecycle of duplicate data, identify the root causes of its occurrence, and master the technical patterns required to detect, prevent, and remediate duplicates during batch ingestion.
Not read yet
Understanding the Anatomy of Duplicates
Before we can solve the problem, we must understand how it manifests. Duplicates rarely look identical across the entire row. Instead, they often appear in specific patterns that reflect the nature of the systems generating them.
Types of Duplicates
- Exact Duplicates: These occur when the exact same row of data is ingested multiple times. This is common when a batch job fails midway and is restarted without proper cleanup, causing the system to re-process records that were already committed.
- Partial Duplicates (Near-Duplicates): These occur when two records share a unique identifier (like a UserID or TransactionID) but have different timestamps or minor discrepancies in attribute values. This often happens when a source system updates a record and sends both the original and the modified version as separate events.
- Temporal Duplicates: These are records that are logically the same but are associated with different ingest timestamps. In systems using "SCD Type 2" (Slowly Changing Dimensions) logic, this might be intentional, but in raw ingestion layers, this often indicates a failure in the deduplication logic of the staging area.
Callout: The Source of Truth Paradox A common misconception is that deduplication should happen at the source. While it is ideal to prevent duplicates at the point of origin, data engineers rarely have full control over source application logic. Therefore, you must treat your ingestion pipeline as a defensive perimeter. Always assume the incoming data is dirty and design your ingestion jobs to be idempotent by default.
Not read yet
Root Causes: Why Duplicates Happen
Understanding why duplicates appear helps in choosing the right remediation strategy. If you know the source of the error, you can often fix it at the root rather than just patching it in the pipeline.
- Network Instability: When a source system sends a batch of data, a network timeout might occur after the data is received but before the acknowledgment signal reaches the sender. The sender, assuming the delivery failed, will re-send the entire batch.
- Overlapping Batch Windows: If your scheduling system triggers a job before the previous one has fully committed its data, you may end up processing the same source files or database rows twice.
- Lack of Idempotency: If your ingestion code does not check for the existence of a record before inserting it, it will create a new row every time it runs. This is the most common cause of "ingestion bloat."
- Source System Retries: Many modern distributed systems use automatic retry logic. If the system experiences internal latency, it might fire the same event multiple times, hoping that one of them succeeds.
Not read yet
Strategy 1: Prevention through Idempotency
The most effective way to handle duplicates is to design your ingestion jobs to be idempotent. An idempotent operation is one that can be performed multiple times without changing the result beyond the initial application. In data engineering, this means that running your pipeline five times on the same input data should result in the exact same state as running it once.
The Upsert Pattern (Merge)
The "Upsert" (Update + Insert) pattern is the industry standard for handling duplicates during ingestion. Instead of a blind INSERT, you query the target system to see if the record exists. If it does, you update it; if it doesn't, you insert it.
Example: SQL-based Upsert
Most modern data warehouses (Snowflake, BigQuery, Redshift) support a MERGE statement. Here is how you might implement this in a SQL-based pipeline:
MERGE INTO target_sales_table AS target
USING staging_sales_table AS source
ON target.transaction_id = source.transaction_id
WHEN MATCHED THEN
UPDATE SET
target.amount = source.amount,
target.status = source.status,
target.updated_at = CURRENT_TIMESTAMP()
WHEN NOT MATCHED THEN
INSERT (transaction_id, amount, status, updated_at)
VALUES (source.transaction_id, source.amount, source.status, source.updated_at);
In this example, the transaction_id acts as the natural key. By using the MERGE command, we ensure that we never create a duplicate row for the same transaction. Even if the ingestion job runs twice, the second run simply updates the existing records rather than appending new ones.
Not read yet
Strategy 2: Deduplication during Transformation
Sometimes, you cannot perform an upsert, perhaps because you are writing to a storage format like Parquet in an S3 data lake where individual row updates are not possible. In this scenario, you must perform deduplication during the transformation phase of your batch job.
Using Window Functions
When working with frameworks like Apache Spark or Python's Pandas, you can use window functions to identify and remove duplicates. The strategy here is to sort the records by a timestamp or a version number and keep only the "latest" version for each unique key.
Example: Deduplication in PySpark
from pyspark.sql import Window
from pyspark.sql.functions import col, row_number
# Define a window partitioned by the unique ID, ordered by the event timestamp
window_spec = Window.partitionBy("transaction_id").orderBy(col("event_timestamp").desc())
# Assign a row number to each record within the partition
df_with_rn = df.withColumn("row_num", row_number().over(window_spec))
# Filter to keep only the latest record (row_num == 1)
deduplicated_df = df_with_rn.filter(col("row_num") == 1).drop("row_num")
This code snippet is powerful because it handles partial duplicates gracefully. By ordering by event_timestamp.desc(), we ensure that the record with the most recent information is preserved, while older, redundant versions are discarded.
Note: Memory Usage While window functions are elegant, be aware that
partitionByoperations can be expensive in distributed systems. If your dataset is massive, ensure your cluster has enough memory to handle the shuffle operation required to group all records with the sametransaction_idonto the same node.
Not read yet
Strategy 3: The "Raw-to-Staging" Cleanup Pattern
In professional data architecture, we rarely ingest data directly into the final analytical tables. Instead, we use a multi-stage approach. This is often referred to as the Medallion Architecture (Bronze, Silver, Gold).
- Bronze (Raw): This layer stores data exactly as it arrived. If duplicates arrived from the source, they remain here. This is crucial for auditing and re-processing.
- Silver (Cleansed): This is where the deduplication logic is applied. You create a job that reads from Bronze and writes to Silver, applying the
MERGEor window-based deduplication logic mentioned earlier. - Gold (Curated): This layer contains the final, deduplicated, and business-ready data.
By isolating the deduplication into a specific layer, you protect your downstream analytics from the messiness of the raw source data. If you discover a bug in your deduplication logic, you can simply truncate the Silver table and re-run the process from the raw data in the Bronze layer.
Not read yet
Comparison of Deduplication Techniques
| Technique | Best For | Pros | Cons |
|---|---|---|---|
| Upsert (Merge) | SQL Data Warehouses | Atomic, efficient, handles updates | Requires a primary key |
| Window Functions | Data Lakes (Spark/Python) | Flexible, handles complex logic | High memory usage, shuffle-heavy |
| Hashing | Large-scale batch jobs | Very fast for exact duplicates | Requires a stable hash function |
| Staging Tables | Complex transformations | Allows for audit/rollback | Slower, requires more storage |
Best Practices for Managing Duplicates
1. Define Your Natural Keys Early
A natural key is a column (or set of columns) that uniquely identifies a record in the real world. For a customer, this might be email_address. For a transaction, it might be transaction_id. You must identify these keys during the design phase. If your data lacks a natural key, you may need to create a surrogate key (a hash of all columns) to identify duplicates.
2. Monitor and Alert
Do not assume your deduplication logic is perfect. Implement monitoring that tracks the number of records dropped during the deduplication phase. If your job normally drops 1% of records but suddenly drops 50%, you have a major issue with your source system or your pipeline logic. Set up alerts for these "anomaly thresholds."
3. Maintain Audit Trails
When you discard records, log the metadata. Store the count of duplicates found, the source system they came from, and the time the deduplication occurred. This audit trail is invaluable when stakeholders ask why a certain record is missing from their report.
Callout: The Hash Collision Risk If you create a surrogate key by hashing your data rows, be aware of the "birthday paradox" and collision risks. While rare, using a weak hashing algorithm like MD5 on extremely large datasets can result in different rows producing the same hash. Always prefer stronger algorithms like SHA-256 for surrogate key generation.
4. Idempotency is Non-Negotiable
Always write your code assuming that the job will be run at least twice. If your job creates files in a directory, use a naming convention that includes a timestamp or a batch ID so that if you run the job again, it overwrites the previous files rather than creating a secondary, duplicate set of files.
Not read yet
Common Pitfalls and How to Avoid Them
Pitfall 1: Over-Deduplication
Sometimes, we become so obsessed with removing duplicates that we delete valid data. For example, if a user makes two identical purchases within the same minute, they are not duplicates; they are two separate events.
- The Fix: Always include a high-resolution timestamp or a unique sequence number in your deduplication logic. If you only look at
user_idandamount, you will erroneously delete one of those two valid purchases.
Pitfall 2: Relying on System Time
Using the "arrival time" (the time the data reached your pipeline) as the primary way to determine which duplicate is "latest" is dangerous. Network latency means that a record created at 10:00:01 might arrive after a record created at 10:00:05.
- The Fix: Always use the source-generated timestamp if it is available. If it is not, try to include a version column or a sequence number from the source system.
Pitfall 3: Ignoring "Soft Deletes"
In many source systems, deleting a record does not actually remove the row; it simply sets a flag like is_deleted = True. If your ingestion logic only looks for duplicates, you might keep the "active" version of a record while ignoring the fact that it was marked as deleted.
- The Fix: Your deduplication logic must respect the
is_deletedflag. When comparing two records with the same ID, the one withis_deleted = Trueshould generally win, or you should filter out deleted records entirely.
Not read yet
Practical Implementation: A Step-by-Step Scenario
Let’s walk through a scenario where we are ingesting user profile updates from a legacy CRM into a centralized data warehouse.
Step 1: Ingestion
The CRM sends a CSV file every hour. Due to a bug in the CRM exporter, it occasionally includes records from the previous hour. We land this file in our raw_crm_data folder in S3.
Step 2: Staging We load the CSV into a temporary staging table in our database. We do not worry about duplicates yet.
Step 3: Identification We run a query to identify duplicates:
SELECT email, COUNT(*)
FROM staging_crm_data
GROUP BY email
HAVING COUNT(*) > 1;
This query reveals the extent of the problem. If the count is high, we know we have an ingestion issue.
Step 4: Transformation (The Merge)
We execute a MERGE into our dim_users table.
MERGE INTO dim_users AS target
USING (
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER(PARTITION BY email ORDER BY last_updated_at DESC) as rank
FROM staging_crm_data
) WHERE rank = 1
) AS source
ON target.email = source.email
WHEN MATCHED THEN
UPDATE SET ...
WHEN NOT MATCHED THEN
INSERT ...
By using ROW_NUMBER() inside the USING clause, we perform the deduplication before we even attempt the merge, ensuring that the source side of our merge is clean.
Step 5: Cleanup
Finally, we truncate the staging_crm_data table to ensure the next batch starts fresh.
Not read yet
The Role of Data Quality Frameworks
In modern engineering, we often use data quality frameworks (like Great Expectations or Deequ) to automate the detection of duplicates. These tools allow you to define "expectations" for your data.
- Example Expectation: "The column
transaction_idmust be unique." - Action: If this expectation fails, the framework can automatically stop the pipeline, notify the engineering team via Slack, and prevent the dirty data from reaching the downstream tables.
Integrating these frameworks into your batch pipeline is a best practice that moves you from a reactive posture (fixing data after it breaks) to a proactive one (preventing broken data from ever landing).
Advanced Topic: Handling Duplicates in Distributed Streams
While this lesson focuses on batch, it is worth noting that the principles of deduplication are even more critical in streaming. In streaming, you often use "watermarking" and "state stores" to keep track of seen IDs for a specific window of time. If you are eventually moving from batch to streaming, the habits you build in your batch pipelines—specifically around idempotency—will be the most transferable skills you have.
Summary Checklist for Deduplication
When building your next batch pipeline, use this checklist to ensure you have covered your bases:
- Identify the natural key: Do we have a unique identifier? If not, can we create a deterministic hash?
- Determine the precedence: Which record "wins" if two are identical? Is it the one with the latest timestamp? The one with the most non-null fields?
- Choose the tool: Are we using a
MERGEstatement, a window function, or a post-load SQL cleanup script? - Test for idempotency: If I run this job twice, does the output change?
- Set up monitoring: Do I have a threshold for "acceptable" duplicates versus "alert-worthy" duplicates?
- Audit: Am I logging what was removed so I can explain the data to users later?
Not read yet
Conclusion: Building Trust Through Rigor
Handling duplicate data is one of the most practical applications of "defensive programming" in data engineering. It requires a shift in mindset: stop trusting the source, stop assuming the network is reliable, and start building pipelines that are inherently self-correcting. By mastering the MERGE pattern, implementing window-based deduplication, and adopting a multi-layer architecture, you can ensure that your data remains a reliable asset for your organization.
Remember that the goal is not just to have "clean" data, but to have "trusted" data. When your stakeholders know that your reports are free from the noise of duplicated transactions and phantom records, they will rely on your work for critical business decisions. This level of reliability is what separates junior data engineers from the experts. Keep your pipelines idempotent, keep your deduplication logic explicit, and never stop auditing the quality of the data flowing through your systems.
Key Takeaways
- Idempotency is the goal: Design every ingestion job so that it can be safely re-run without creating duplicates or corrupting the existing state.
- Use the Merge Pattern: Whenever possible, leverage the native
MERGEorUPSERTcapabilities of your data warehouse to handle deduplication at the point of ingestion. - Understand your keys: You cannot deduplicate effectively without a clear understanding of what constitutes a "unique" record in your dataset. If a natural key is missing, create a deterministic surrogate key.
- Layered Architectures: Use a Bronze-Silver-Gold approach to isolate raw data from cleaned, deduplicated data. This allows for easier auditing and re-processing if deduplication logic needs to be adjusted.
- Monitor for anomalies: Deduplication logic is not "set and forget." Monitor the volume of dropped records to detect changes in source system behavior or pipeline failures.
- Respect the Source: When deduplicating, always favor source-generated timestamps over arrival timestamps to ensure the most accurate version of the record is preserved.
- Automate Quality Checks: Integrate data quality tools to automatically flag or reject batches that contain unexpected levels of duplicate data.
Not read yet
Common Questions (FAQ)
Q: If I deduplicate in the transformation layer, should I still keep the duplicates in the raw/bronze layer? A: Absolutely. The raw layer serves as your insurance policy. If you find a bug in your deduplication logic, you will need the original, un-deduplicated data to re-run the process and recover the records you accidentally discarded.
Q: My database doesn't support the MERGE statement. What should I do?
A: You can achieve the same result using a "Staging Table" pattern. Load the new data into a temporary table, perform a DELETE on the target table for all records that exist in the staging table, and then INSERT everything from the staging table. This is functionally equivalent to an upsert.
Q: Is it ever okay to keep duplicates? A: Yes, in some cases. For example, if you are building an audit log or an event store where the history of every interaction matters, duplicates might represent distinct events that occurred in rapid succession. Always consult with your business stakeholders to understand if duplicates are "bad data" or "historical reality."
Q: How often should I run my deduplication jobs? A: This depends on your business requirements. If you need real-time reporting, you may need a streaming deduplication approach. If daily reporting is sufficient, a single batch job at the end of the ingestion window is standard. Match the frequency of your deduplication to the frequency of your data consumption.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
- Workspace Level Access Controls
- Workspace Level Access Controls Quiz5q
- Item Level Access Controls
- Item Level Access Controls Quiz5q
- Row and Column Level Security
- Row and Column Level Security Quiz5q
- Object and File Level Security
- Object and File Level Security Quiz5q
- Dynamic Data Masking
- Dynamic Data Masking Quiz5q
- Sensitivity Labels
- Sensitivity Labels Quiz5q
- Fabric Audit Logs
- Fabric Audit Logs Quiz5q
- OneLake Security Configuration
- OneLake Security Configuration Quiz5q
- Endorsing Items
- Endorsing Items Quiz5q
- Choosing Orchestration Tools
- Choosing Orchestration Tools Quiz5q
- Schedules and Event Triggers
- Schedules and Event Triggers Quiz5q
- Orchestration with Notebooks
- Orchestration with Notebooks Quiz5q
- Parameters and Dynamic Expressions
- Parameters and Dynamic Expressions Quiz5q
- Pipeline Patterns
- Pipeline Patterns Quiz5q
- Choosing Data Stores
- Choosing Data Stores Quiz5q
- Transformation Tool Selection
- Transformation Tool Selection Quiz5q
- OneLake Shortcuts
- OneLake Shortcuts Quiz5q
- Implementing Mirroring
- Implementing Mirroring Quiz5q
- Pipeline Data Ingestion
- Pipeline Data Ingestion Quiz5q
- PySpark Transformations
- PySpark Transformations Quiz5q
- SQL Transformations
- SQL Transformations Quiz5q
- KQL Transformations
- KQL Transformations Quiz5q
- Data Denormalization
- Data Denormalization Quiz5q
- Grouping and Aggregating Data
- Grouping and Aggregating Data Quiz5q
- Handling Duplicate Data
- Handling Duplicate Data Quiz5q
- Handling Missing and Late Data
- Handling Missing and Late Data Quiz5q
- Dataflows Gen2 Ingestion
- Dataflows Gen2 Ingestion Quiz5q
- Delta Lake Table Management
- Delta Lake Table Management Quiz5q
- Choosing Streaming Engine
- Choosing Streaming Engine Quiz5q
- Native Tables vs OneLake Shortcuts
- Native Tables vs OneLake Shortcuts Quiz5q
- Query Acceleration for Shortcuts
- Query Acceleration for Shortcuts Quiz5q
- Eventstreams Processing
- Eventstreams Processing Quiz5q
- Spark Structured Streaming
- Spark Structured Streaming Quiz5q
- KQL for Streaming
- KQL for Streaming Quiz5q
- Windowing Functions
- Windowing Functions Quiz5q
- Tumbling and Hopping Windows
- Tumbling and Hopping Windows Quiz5q
- Pipeline Error Resolution
- Pipeline Error Resolution Quiz5q
- Dataflow Gen2 Error Resolution
- Dataflow Gen2 Error Resolution Quiz5q
- Notebook Error Resolution
- Notebook Error Resolution Quiz5q
- Eventhouse Error Resolution
- Eventhouse Error Resolution Quiz5q
- Eventstream Error Resolution
- Eventstream Error Resolution Quiz5q
- T-SQL Error Resolution
- T-SQL Error Resolution Quiz5q
- OneLake Shortcut Error Resolution
- OneLake Shortcut Error Resolution Quiz5q
- Lakehouse Table Optimization
- Lakehouse Table Optimization Quiz5q
- Pipeline Optimization
- Pipeline Optimization Quiz5q
- Data Warehouse Optimization
- Data Warehouse Optimization Quiz5q
- Eventstreams and Eventhouses Optimization
- Eventstreams and Eventhouses Optimization Quiz5q
- Spark Performance Optimization
- Spark Performance Optimization Quiz5q
- Query Performance Optimization
- Query Performance Optimization Quiz5q
- V-Order Optimization
- V-Order Optimization Quiz5q
- Compaction and Vacuum
- Compaction and Vacuum Quiz5q
- Partitioning and Z-Order
- Partitioning and Z-Order Quiz5q
- Caching Strategies
- Caching Strategies Quiz5q
- Query Optimization Techniques
- Query Optimization Techniques Quiz5q
- Parallel Processing Configuration
- Parallel Processing Configuration Quiz5q
- Data Skew Resolution
- Data Skew Resolution Quiz5q
Spend your points to unlock exam-style practice questions
Spend points to unlock DP-700 exam-style practice questions.
Practice for DP-700