A duplicate finder has one dangerous line in it: the one that compares records with each other. Everything else scales with the number of records. That line scales with the square, and it's fine until someone hands it a block of data you never imagined.
Someone did. A sign-up script created a workspace and filled it with 8,000
contacts, all attached to one company, all named in the same pattern
(tenantB12 markerB, tenantB13 markerB, …). The nightly duplicate scan
reached that workspace and asked Postgres for every pair of similarly named
contacts in the same company. Postgres returned them: about 32 million
rows, into a Ruby process in a container with a 1 GB limit.
The kernel killed the worker. The queue re-claimed the job, and the kernel killed it again, 450 times in about nine hours. Every other background job shared that container, so email sync, webhooks and reminders barely ran.
This post covers how the scan was built, why only one of its rules was quadratic, and the two constants that now make "quadratic" impossible, each taken from the real data.
How the scan was already linear (mostly)
The scan finds probable duplicates on several keys: a shared email, the same
normalised phone, the same normalised company name, and the same open deal
title for the same contact. For each key it runs one GROUP BY … HAVING count(*) > 1 and carries the members out with array_agg(id ORDER BY id):
SELECT array_agg(id ORDER BY id)
FROM contacts
WHERE tenant_id = $1 AND discarded_at IS NULL
GROUP BY right(regexp_replace(phone, '[^0-9]', '', 'g'), 10)
HAVING count(*) > 1;
Then it star-pairs each group. Every member is linked to the group's smallest id rather than to every other member, so a group of N gives N − 1 pairs. A review screen only needs to show that these records belong together. The full clique adds nothing.
Exact keys collide in groups, and a group only needs a star to say "these belong together". Fuzzy matching has no group, only pairs.
Exact keys can do this because the key defines the group. Fuzzy name matching can't: "Jon Smith" is like "John Smith", and "John Smith" is like "John Smyth", but that doesn't make "Jon Smith" like "John Smyth". Similarity isn't transitive, so there's no group to star, only pairs. That rule was a self-join:
SELECT c1.id, c2.id
FROM contacts c1
JOIN contacts c2
ON c2.tenant_id = c1.tenant_id
AND c2.company_id = c1.company_id -- the blocking key
AND c2.id > c1.id
WHERE c1.tenant_id = $1
AND full_name(c1) % full_name(c2) -- pg_trgm, index-assisted
AND similarity(full_name(c1), full_name(c2)) >= 0.6;
The company_id equality is a blocking key. Record linkage uses blocking
to avoid comparing everyone with everyone: you only compare records inside the
same block. Here a block is a company. It's a sound idea, and it's why this
query had run nightly for months without trouble. Blocking makes the cost
the sum of each block's square, not the square of the total. That's only
small while every block is small.
The block nobody imagined
The largest real company in production had 64 contacts. That's 2,016 candidate pairs, which is nothing. The generated workspace put 8,000 contacts in one block, and every name passed the trigram filter because the names were almost identical.
A block 125× bigger gives nearly 16,000× more pairs. Blocking keeps cost low only while every block is small.
Postgres was fine with this. Trigram indexes make the comparison cheap, and
the database streams. The process holding the result wasn't fine.
select_rows builds an array of 32 million two-element arrays, roughly
several gigabytes of Ruby objects, inside a 1 GB container.
Why one bad job took the whole worker down
The queue claims a job with a session-level Postgres advisory lock. When a worker dies, its connection closes and Postgres releases the lock, so the job is immediately available again. That's the right behaviour for crash recovery: a job whose worker was killed by a deploy should run again. It's the wrong behaviour for a job that kills its own worker every time. (An earlier post covers this re-claim loop in detail.)
Lock-on-connection is what makes crash recovery automatic. It also makes a job that always crashes run forever.
Discarding that one job stopped the loop at once. The rest of this post is about making sure the scan can't produce that job again, whatever data it meets.
Bound 1: a ceiling on the block
Fuzzy-comparing names inside a company of 8,000 isn't useful even when the data is real. Nobody reviews 32 million "maybe duplicates". A company that large is a bulk import, and inside a bulk import name similarity is noise. So blocks above a ceiling are left out of the fuzzy rule, and the exact-key rules still cover them:
WITH comparable AS (
SELECT company_id
FROM contacts
WHERE tenant_id = $1 AND discarded_at IS NULL AND company_id IS NOT NULL
GROUP BY company_id
HAVING count(*) <= 200 -- MAX_NAME_COMPARE_COMPANY
)
SELECT c1.id, c2.id
FROM contacts c1
JOIN comparable cc ON cc.company_id = c1.company_id
JOIN contacts c2 ON c2.tenant_id = c1.tenant_id
AND c2.company_id = c1.company_id
AND c2.id > c1.id
AND c2.discarded_at IS NULL
WHERE c1.tenant_id = $1 AND c1.discarded_at IS NULL
AND full_name(c1) % full_name(c2)
AND similarity(full_name(c1), full_name(c2)) >= 0.6
LIMIT 20000; -- MAX_PAIRS_PER_QUERY
200 wasn't picked out of the air. The largest real block was 64, so 200 gives about 3× headroom for growth before anyone loses a real comparison. And a block of 200 produces at most 19,900 pairs, which leads to the second constant.
Bound 2: a cap on the result
The ceiling bounds any one block, but a workspace can hold many blocks just
under it. The second bound is on what reaches the process: LIMIT 20000 on
every pairwise query. That's one maximum-size block's worth of pairs. In Ruby,
20,000 pairs of integers is a few megabytes, whatever the input.
The same cap went on the other pairwise rule, which matches leads to contacts on shared email or phone, because it joins two tables and has the same shape.
The ceiling removes blocks where comparison is noise. The cap makes the worst case a constant, whatever the input.
Bound 3: don't scan what nobody can use
The workspace that triggered this had already been suspended. Nobody could
sign in to it, and nobody would ever review its duplicates. Yet the nightly
fan-out still enqueued a scan for it, and so did the per-record scan that runs
after an edit. Now the fan-out filters suspended_at IS NULL, and both jobs
return early when the workspace is suspended. That's cheaper than any bound,
and it removes the input that started the problem.
The guards
Each bound has a test that fails when the bound is removed. The tests shrink the constants so they stay fast:
it "leaves companies above the ceiling out of name comparison" do
stub_const("Dedupe::PairScanService::MAX_NAME_COMPARE_COMPANY", 3)
big = create(:company, tenant:)
4.times { |i| create(:contact, tenant:, company: big, first_name: "Alex", last_name: "Rivera#{i}") }
described_class.call(tenant:)
expect(DuplicateCandidate.where(matched_on: %w[name_trgm company])).to be_empty
end
it "caps the pairs a single query returns" do
stub_const("Dedupe::PairScanService::MAX_PAIRS_PER_QUERY", 2)
co = create(:company, tenant:)
4.times { |i| create(:contact, tenant:, company: co, first_name: "Alex", last_name: "Rivera#{i}") }
described_class.call(tenant:)
expect(DuplicateCandidate.where(matched_on: %w[name_trgm company]).count).to eq(2)
end
We reverted each bound and watched its test fail, then put it back.
What this changes for real users
Nothing visible. Every real company sits far under the ceiling, so every real name comparison still runs. The pair cap is above anything a real workspace produced. What changed is the worst case: before, it was "whatever the largest block squares to", and now it's a number you can read in the source.
The constants, and what set each one
| Constant | Value | The constraint that set it |
|---|---|---|
MAX_NAME_COMPARE_COMPANY | 200 | largest real block was 64; ~3× headroom before a real comparison is lost |
MAX_PAIRS_PER_QUERY | 20,000 | one maximum-size block (200 → 19,900 pairs); a few MB in Ruby on any input |
NAME_SIMILARITY | 0.6 | unchanged; precision of the review queue, not cost |
| star pairing for exact keys | N − 1 per group | a review only needs "these belong together", not the full clique |
| suspended workspaces skipped | n/a | no one can act on their duplicates; the cheapest bound is not running |
Blocking is the standard answer to quadratic comparison, and it works. But it moves the square inside each block, it doesn't remove it. If any block can grow without limit, so can the job. So give every pairwise query two limits you can name: one on how big a block may be before you stop comparing inside it, and one on how many pairs may come back at all.