How to Build a Deduplication Pipeline
Normalize keys before comparing, dedupe exactly with unique constraints, pre-filter with bloom filters, and quantify miss and false-positive rates.
On this page
Introduction
Ingest pipelines accumulate duplicates by design: at-least-once delivery redelivers on retry, upstream systems resend full exports, users submit the same form twice, and multiple sources describe the same entity. Duplicates corrupt counts, inflate costs, and create contradictory state when downstream logic treats two copies as two facts. Deduplication is therefore not one filter but a layered design: an identity decision that defines what counts as the same, exact enforcement at the store that makes duplicates impossible regardless of races, cheap pre-filtering that keeps the exact path affordable at high volume, and measurement of both error directions, because every layer either wastes work or risks dropping unique data. This tutorial builds those layers in order, normalizing keys honestly, enforcing uniqueness at the database, sizing a bloom filter pre-check, handling the near-duplicate case where exact equality is the wrong definition, and instrumenting the whole thing so dedup quality is a number, not a hope.
Identity is normalization first
Deduplication fails silently when identity is fuzzy: two records that are the same fact fail to match because one has trailing whitespace, a different case, or keys in a different order inside a JSON blob. The first pipeline stage is canonicalization, and it deserves specification, because it defines the equality the rest of the system inherits. Text fields: trim, case-fold where the domain is case-insensitive, Unicode-normalize to NFC, and collapse internal whitespace. Composite keys: define the exact field set and their order, and serialize deterministically. JSON payloads: sort keys and strip volatile fields, timestamps and sequence numbers that legitimately differ between copies, before hashing. Structured identifiers: validate format first, a malformed email that gets lowercased is still malformed, and normalize representation, such as phone numbers to E.164. The output is a canonical key, a hash of the canonical form usually, and every later layer compares canonical keys only. The test for this stage is adversarial pairs: known-duplicate pairs that differ in whitespace, case, key order, and volatile fields must collapse, and known-distinct pairs, a genuinely different event at the same second, must not.
Exact enforcement at the store
The only layer that makes duplicates impossible is the destination’s uniqueness constraint, because it is the single choke point every write path crosses, retries, redeliveries, concurrent workers, and backfills included. The pattern is a unique constraint or index on the canonical key plus an idempotent write, the upsert, so a redelivered record updates or skips rather than inserting a second copy.
CREATE TABLE ingested_events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
dedup_key text NOT NULL,
payload jsonb NOT NULL,
first_seen_at timestamptz NOT NULL DEFAULT now(),
delivery_count int NOT NULL DEFAULT 1
);
CREATE UNIQUE INDEX ingested_events_key
ON ingested_events (dedup_key);
INSERT INTO ingested_events (dedup_key, payload)
VALUES ($1, $2)
ON CONFLICT (dedup_key) DO UPDATE
SET delivery_count = ingested_events.delivery_count + 1
RETURNING id, (xmax = 0) AS was_new;
The delivery_count column turns duplicates into telemetry: redelivery rates become visible per source, which is exactly the signal that upstream retry behavior changed. Note what this layer does not do: it does not decide near-duplicates, does not clean dirty data, and does not remove duplicates that already exist, those are one-off migrations, DELETE with a window function ranking rows by the canonical key keeping the earliest. The constraint is the invariant going forward; cleanup is a separate, scripted repair.
Bloom filters as the cheap first gate
At high volume, the exact path, a database round trip per item, dominates pipeline cost even when most items are new and would insert anyway. A bloom filter over seen canonical keys pre-answers probably seen or definitely new, and only the probably-seen items pay the exact check. A bloom filter is a bit array plus k hash functions: add sets k bits, membership checks them, and false positives, reporting seen for a never-added key, occur at a rate governed by the size and hash count, while false negatives never occur, bits are only ever set.
export class BloomFilter {
private bits: Uint8Array;
constructor(readonly m: number, readonly k: number) {
this.bits = new Uint8Array(Math.ceil(m / 8));
}
add(key: string) {
for (const h of this.hashN(key)) this.bits[h >> 3] |= 1 << (h & 7);
}
mightContain(key: string): boolean {
return this.hashN(key).every(h => (this.bits[h >> 3] & (1 << (h & 7))) !== 0);
}
private *hashN(key: string): Generator<number> {
const base = fnv1a(key);
for (let i = 0; i < this.k; i++) {
yield (base + i * fnv1a(key + ':' + i)) % this.m;
}
}
}
Size it from the planned distinct-key count and a chosen false-positive rate, one percent costs about ten bits per key, and reset or rotate it on a schedule, since it grows monotonically and old keys stop mattering. Redis ships a native scalable bloom filter when the pipeline runs across processes. The critical property to preserve in composition: a might-contain answer routes to the exact check, never to a drop, because the filter’s false positives must never discard unique data.
Near-duplicates when equality is wrong
Exact equality is the wrong identity for some domains: the same customer entered twice with a typo, product descriptions copied with small edits, news articles syndicated with cosmetic changes. Near dedup matches by similarity, and it is a threshold business, every method trades false positives, distinct items merged, against misses, duplicates left separate. The practical ladder, cheapest first: normalized exact matching catches a surprising share, case, whitespace, and punctuation folding; n-gram or token-set similarity, Jaccard on shingles, catches edit-level variants, with blocking first, comparing only items sharing a coarse key like a sorted-token prefix, so quadratic pairwise comparison never runs over the full corpus; MinHash with locality-sensitive hashing makes the blocked comparison scalable to millions; embedding similarity handles semantic matches that share no surface tokens, at the cost of an index and drift. Every step up the ladder multiplies cost and false-positive risk, so start at exact, measure the residual duplicate rate with sampled human judgment, and climb only as far as the measured residual justifies. The merge step that follows a near match is its own design, survivorship rules, field-level conflict resolution, and it deserves the same deliberation as the matching itself.
Measure both error directions
Deduplication quality is two numbers with asymmetric costs, and the pipeline must export both. Dedup ratio: input records over distinct keys, per source and per window, which tracks duplication pressure and flags upstream changes, a source whose ratio doubles changed its retry or export behavior. False positives: distinct items wrongly merged, measured by sampling merged groups and judging identity, expensive but the only honest measure for near dedup; exact dedup with honest normalization has zero by construction, and the normalization test suite is what keeps that true. Misses: duplicates that passed through, measured by downstream anomaly signals, counts that disagree with source systems, duplicate-key errors from consumers that trusted uniqueness the pipeline did not provide, and sampled audits. Alert on ratio shifts rather than absolute values, and treat any observed false positive as a defect in normalization rather than an acceptable rate, because in the exact layer there is no acceptable rate above zero. The bloom filter adds its own telemetry, fill ratio and estimated false-positive rate, so its sizing decisions are revisitable with data.
Test identity, not just throughput
The dedup test suite attacks the identity definition directly. Canonicalization pairs: every known-duplicate shape, case, whitespace, Unicode forms, key order, volatile fields, must produce equal canonical keys, and every known-distinct pair must differ, a golden-file suite that grows with every production bug found. Race tests: two workers insert the same key concurrently and the store ends with exactly one row and both callers receive a coherent outcome, one insert, one update, exercising the upsert under true concurrency. Redelivery: process the same batch twice and assert the second pass updates delivery_count without inserting, and that a partial failure mid-batch replayed converges. Bloom composition: with a filter sized for a high false-positive rate on purpose, assert that unique items still land in the store, proving the exact check catches the filter’s errors. Near-duplicate thresholds: boundary pairs just above and below the similarity cutoff must classify correctly, because thresholds drift silently when tokenization changes.
expect(canonicalKey({a: ' x ', b: 'Y'})).toBe(canonicalKey({b: 'y', a: 'x'}));
expect(canonicalKey({a: 'x', ts: 1})).not.toBe(canonicalKey({a: 'x', ts: 2}));
Common pitfalls
- Fuzzy identity without specification. Ad-hoc normalization lets duplicates through silently; the canonical form is a contract with a test suite.
- Dedup only in application memory. Multi-worker races and restarts defeat in-process sets; the store constraint is the backstop.
- Bloom positives treated as seen. The filter says possibly; only the exact check may decide.
- Volatile fields inside the key. Timestamps and sequence numbers make every redelivery unique; strip before hashing.
- Near-dup thresholds without measurement. Every threshold is a cost trade; unmeasured, it is a guess that ships.
- No dedup telemetry. Ratio drift and residual duplicates are invisible until a downstream count disagrees publicly.
Conclusion
Deduplication is an identity contract enforced in layers. Specify canonicalization precisely, case, whitespace, Unicode, key order, volatile-field stripping, and guard it with adversarial golden tests, because every downstream layer inherits this definition. Enforce exact uniqueness at the destination with a constraint plus upsert, the single choke point that makes duplicates impossible under any race, and use delivery counters to turn redelivery into telemetry. Pre-filter with a correctly sized bloom filter, routing positives to the exact check and never to a drop, and climb the near-duplicate ladder, normalized exact, blocked similarity, MinHash, embeddings, only as far as measured residual duplicates justify. Export both error directions as metrics, and treat any false positive in the exact layer as a normalization defect. The result is a pipeline whose counts agree with reality, at a cost that scales with new data rather than with redelivery.
Sources: PostgreSQL: SELECT semantics, Redis: Bloom filter, MDN: Set.
FAQ
- What is the difference between exact and near deduplication?
- Exact dedup requires byte or key equality after normalization. Near dedup matches semantically similar items, misspelled names, slightly different documents, using similarity thresholds, MinHash, or embeddings, and it always trades false positives against misses.
- Does a bloom filter ever drop a genuinely new item?
- No. A bloom filter has false positives, membership reported for items never added, but never false negatives. A positive answer means possibly seen, so the item goes to the exact check, which is why the filter only saves work and never corrupts results.
- Where should dedup live, producer or consumer?
- Enforce at the final store with constraints, because that is the only layer every path flows through. Filters earlier in the pipeline, bloom filters, in-memory sets, are optimizations; the constraint is the correctness backstop.
Report a problem with this articleOpens a pre-filled issue on GitHub.