Ask a candidate to build a knowledge graph and they will draw nodes and edges and move on. Then the real question lands: “You ingest a company record from Salesforce, a different record for the same company from a web crawl, and a third from a government registry. None of them share an ID. One calls it Acme Corp, one ACME Corporation, one Acme Corp. (Delaware). How do you know these three rows are the same real-world company, and how do you do it when you have two billion records and cannot afford to compare every pair?” Comparing every pair is 2B choose 2, which is 2 * 10^18 comparisons. At a million comparisons a second that is 60,000 years. The entire difficulty of this system is not storing the graph - it is deciding which records refer to the same entity without comparing all pairs, and then serving traversal over the merged graph fast.
This post designs that system: a knowledge graph whose nodes are canonical real-world entities (companies, people, places, products) and whose edges are typed relationships, fed by an entity resolution pipeline that ingests records from many sources with incompatible schemas and identifiers, deduplicates and links the records that refer to the same entity, and merges them into one canonical node. The hard part the whole design is organized around is the blocking strategy: a way to partition the candidate pairs by shared attributes so that pairwise similarity scoring is tractable at scale, without dropping true matches that happen to disagree on the attribute you blocked on. Everything else - the match model, the clustering, the graph store, the traversal path - is built to serve that.
This is the engine behind a product like a company-data graph (Crunchbase, Clearbit), a people graph (LinkedIn’s entity layer), or a product catalog that fuses many feeds. It is the record-linkage core, not the UI. Let me build it properly.
Functional Requirements (FR)
In scope:
- Ingest heterogeneous records. Accept entity records from many sources (CRM exports, web crawls, third-party data feeds, government registries, internal events), each with its own schema, field names, formats, and identifier scheme - or no stable identifier at all. Normalize them into a common record shape.
- Entity resolution (dedup + linkage). Decide which incoming records refer to the same real-world entity. This is both deduplication (two records in the same batch are the same company) and linkage (a new record matches an entity already in the graph). The output is a cluster of source records mapped to one canonical entity.
- Canonical entity construction (merge / survivorship). From a cluster of matched records, build one canonical node: pick the best value per attribute (survivorship rules), keep provenance (which source said what), and expose a stable internal entity ID.
- Typed relationships (the graph). Edges between canonical entities:
company EMPLOYS person,company SUBSIDIARY_OF company,person FOUNDED company,company LOCATED_IN place. Edges themselves may come from any source and get resolved to canonical endpoints. - Graph traversal queries. Given an entity, return neighbors by edge type; do bounded multi-hop traversal (the org chart under a company, the acquisition tree, people within two hops of a founder); bounded shortest path between two entities. Low latency, over billions of edges.
- Point lookup and search. Resolve an external record or a text query (
"acme corp delaware") to a canonical entity ID. - Corrections and splits. A human (or a higher-confidence signal) can confirm a merge, reject one (split a node back into two), or merge two nodes the system kept separate. These overrides are first-class and permanent.
Explicitly out of scope (naming it means I own the boundary):
- Full-graph analytics. PageRank over the whole graph, community detection, global centrality. Those are offline batch jobs on a snapshot (Spark/GraphX/Pregel), not online queries. This engine does bounded local traversal and I will say where the line is.
- Training the ML match model from scratch. I design the serving and labeling pipeline and treat the scoring model (how two records’ similarity becomes a match probability) as a trained artifact I version and deploy. I do not design the gradient descent.
- Arbitrary SPARQL / full ontology reasoning. I support typed edges and bounded traversal, not a general inference engine deriving new facts from OWL axioms.
- Real-time sub-second ingestion of every source. Bulk sources arrive as batches; a streaming path exists for high-value updates, but I am not promising that every government-registry dump reflects in the graph in one second.
The decision that drives everything: the dominant cost is pairwise comparison, which is quadratic, so the whole pipeline is built to avoid comparing pairs that could not possibly match - that is blocking - while the graph itself is read-dominated traversal where layout and caching decide latency. Every hard choice below follows from “generate as few candidate pairs as possible without losing true matches, then serve the merged graph locally.”
Non-Functional Requirements (NFR)
- Scale: ~2B source records across ~50 sources, resolving to ~500M canonical entities. ~10B edges between them, heavy-tailed degree (a big employer has millions of
EMPLOYSedges; a tiny shop has three). Ingest ~50M new/updated records per day (batch heavy, some streaming). Raw record store a few TB, graph a few TB, times replication -> tens of TB, far beyond one machine. - Latency: entity lookup / resolve-a-single-record p99 < 50ms. 1-hop neighbor read p99 < 20ms. Bounded 2-3 hop traversal p99 < 200ms. Blocking + scoring of a single incoming record against existing entities (the online linkage path) p99 < 100ms. Bulk resolution runs offline; its SLO is throughput (records/hour), not per-record latency.
- Throughput: ~5K online resolve/link requests/sec at peak; ~300K graph read QPS; bulk pipeline resolves tens of millions of records/day.
- Availability: 99.95% on graph reads and lookups. A traversal that returns a slightly stale neighbor is fine; a query that hangs on one slow shard is not. Reads degrade, never block. The bulk resolution pipeline can be down for an hour without user-visible impact (it just lags).
- Consistency: the canonical graph is eventually consistent - a newly ingested record showing up as merged a few minutes late is acceptable. The one hard requirement: merges and splits are deterministic and reproducible. Given the same records and the same model version, resolution must produce the same clusters; and human overrides must always win over the model. We do not get “the same two records merged on Tuesday and split on Wednesday” from nondeterminism.
- Durability: source records are the source of truth and are never lost - the canonical graph is a derived artifact we can always rebuild by re-running resolution over the raw records. Every raw record and every human decision is on durable, replicated storage. This rebuildability is a core design lever.
- Correctness of matching: two tunable error types. A false merge (fusing two different real companies into one node) is usually worse than a false split (keeping one company as two nodes) because a false merge corrupts every query touching that node and is hard to notice. The pipeline is tuned conservative on merges, with human review for the ambiguous middle.
Back-of-the-Envelope Estimation (BoE)
Real arithmetic, because the quadratic blowup is the whole reason this system exists.
The quadratic wall (why blocking is mandatory):
Records: 2B.
All-pairs comparisons = 2B choose 2 ≈ (2e9)^2 / 2 = 2 * 10^18 pairs.
At 1,000,000 comparisons/sec/core: 2e18 / 1e6 = 2e12 core-seconds
= ~63,000 core-YEARS. Infeasible by any budget.
Even for one DAILY batch of 50M new records matched against 500M entities:
5e7 * 5e8 = 2.5 * 10^16 comparisons -> still ~800 core-years/day. Infeasible.
Blocking must cut this by ~6-8 orders of magnitude. Target: generate at most ~a few hundred candidate pairs per record, not hundreds of millions.
Goal: ~200 candidate pairs per record (tunable).
Daily batch: 5e7 records * 200 = 1e10 candidate pairs/day
1e10 / 86,400 ≈ 115K scored pairs/sec sustained -> a few hundred cores. Feasible.
Full bootstrap (2B records * 200): 4e11 pairs, a one-time offline Spark job over days.
That single contrast - 63,000 years vs a few hundred cores - is why the deep dive is mostly about blocking.
Storage:
Raw records: 2B * ~1.5 KB (varied fields + provenance + source blob)
2e9 * 1.5 KB = 3 TB raw records
Canonical entities: 500M * ~2 KB (merged attributes + survivorship + provenance refs)
5e8 * 2 KB = 1 TB canonical nodes
Edges: 10B * ~40 B (src_id, dst_id, type, props, provenance)
1e10 * 40 B = 400 GB logical, store both directions
for traversal -> ~800 GB adjacency
Blocking index (keys -> record ids): varies, ~a few hundred GB
-> raw ~5-6 TB, times replication 3 = ~16-18 TB. Must shard.
Match-model scoring volume: ~115K pair scores/sec sustained in the batch path, ~5K/sec in the online path. Each score is a cheap feature-vector -> model inference (sub-ms with a gradient-boosted tree). The expensive part is not the model; it is not generating the pairs.
Graph read bandwidth:
300K reads/sec, avg neighbor result ~2 KB
300K * 2 KB ≈ 600 MB/sec served -> fits a sharded + cached fleet comfortably;
the binding constraint is cross-shard round trips on multi-hop, not bytes.
Cache: the hot working set of canonical entities and their 1-hop adjacency - say the top ~5% of entities taking ~80% of traffic:
5% * 500M = 25M hot entities * (2 KB node + ~4 KB hot adjacency) ≈ 150 GB
-> a distributed in-memory cache (Redis/Memcached) of ~200 GB covers the hot set.
The headline: scoring is cheap, storage is shardable, reads cache well. The one genuinely hard number is the 10^18 all-pairs wall, and blocking is the only thing standing between the design and 63,000 years.
High-Level Design (HLD)
Two distinct planes share one graph. The resolution plane (write side) ingests records, blocks them into candidate pairs, scores pairs, clusters matches, and merges clusters into canonical nodes. The serving plane (read side) answers lookups and traversals over the merged graph. A durable raw-record store underneath both means the graph is always rebuildable.
Heterogeneous sources (CRM, crawl, feeds, registries, events)
│ batches + stream
▼
┌──────────────────────┐
│ Ingestion / Normalize│ schema-map to common record, standardize
│ (per-source adapter) │ (phone->E.164, address parse, name clean)
└──────────┬────────────┘
│ normalized records
▼
┌──────────────────────┐ ┌─────────────────────┐
│ Raw Record Store │◀──────│ Source of truth │
│ (object store + KV, │ │ (never deleted; │
│ sharded by record_id) │ │ graph rebuildable) │
└──────────┬────────────┘ └─────────────────────┘
│
▼
┌──────────────────────┐
│ BLOCKING │ generate blocking keys per record,
│ (multi-pass, LSH) │ group records sharing a key -> candidate pairs
└──────────┬────────────┘
│ candidate pairs (~200/record, not N^2)
▼
┌──────────────────────┐ ┌────────────────────────┐
│ PAIRWISE SCORING │────▶│ Match model (versioned)│
│ similarity features │ │ pair -> P(match) │
└──────────┬────────────┘ └────────────────────────┘
│ scored pairs (match / unsure / no)
▼
┌──────────────────────┐ ┌────────────────────────┐
│ CLUSTERING │────▶│ Human review queue │
│ connected components │ │ (the "unsure" band) │
│ + transitivity guard │◀────│ overrides: merge/split │
└──────────┬────────────┘ └────────────────────────┘
│ entity clusters (record_ids -> entity_id)
▼
┌──────────────────────┐
│ MERGE / SURVIVORSHIP│ one canonical node per cluster,
│ + xref table write │ provenance kept, xref record->entity
└──────────┬────────────┘
│ writes
▼
┌─────────────────────────────────────────────┐
│ KNOWLEDGE GRAPH STORE │
│ canonical nodes + typed edges, sharded by │
│ entity_id, adjacency co-located, replicated │
└───────┬───────────────────────────┬──────────┘
│ reads │
┌───────▼─────────┐ ┌───────▼────────────┐
│ Graph Query Svc │ │ Entity Cache (Redis)│
│ lookup+traversal│◀────────▶│ hot nodes+adjacency │
└───────┬─────────┘ └─────────────────────┘
│
┌───────▼─────────┐
│ Online Resolve │ new record -> block -> score vs existing -> link
│ (low-latency) │
└─────────────────┘
Bulk resolution flow (offline, the dominant write path):
- Source adapters pull/receive batches, map each source’s schema to a common record shape, and standardize fields (phone to E.164, addresses parsed and normalized, names cleaned and case-folded, dates to ISO). The normalized record and its raw original both land in the Raw Record Store with provenance.
- Blocking generates one or more blocking keys per record (covered in depth below). Records sharing a key land in the same block; every intra-block pair is a candidate. This replaces
N^2withsum over blocks of (block_size choose 2). - Pairwise scoring computes a similarity feature vector per candidate pair (name similarity, address match, phone match, etc.) and the versioned match model turns it into
P(match). Pairs split into three bands: match (above high threshold), no match (below low threshold, dropped), unsure (middle band, sent to human review). - Clustering takes the “match” edges and computes connected components to form entity clusters, with a transitivity guard (below) so one bad edge cannot chain-merge a thousand unrelated records. Human overrides (must-link / must-not-link) are injected as hard constraints.
- Merge / survivorship collapses each cluster into one canonical node, applying per-attribute survivorship rules, keeping full provenance, and writing the cross-reference (xref) table mapping every source
record_id -> entity_id. Nodes and resolved edges are written to the graph store.
Online resolution flow (low-latency, for a single incoming record):
- A record arrives (a new signup, an API call
resolve this company). Normalize it the same way. - Compute its blocking keys, look up the blocking index to fetch the small set of existing entities sharing a key (~hundreds, not millions).
- Score the record against those candidates with the same model. If a confident match -> return that
entity_id(link). If none -> mint a new entity. If unsure -> provisional entity + enqueue for review.
Serving flow (read): the Graph Query Service resolves an external key or text to entity_id via the xref table / search, then does 1-hop or bounded multi-hop traversal over the sharded graph, served from the entity cache on hits. Covered in the traversal deep dive.
The structural insight: the write side is a pipeline whose entire job is to avoid the quadratic, and the read side is a sharded, cached graph tuned to keep traversals local. The raw store underneath makes the whole graph a rebuildable projection - so a model upgrade or a blocking-strategy change is a reprocessing job, not a migration.
Component Deep Dive
The hard parts, naive-first then evolved: (1) blocking - the heart of the system, (2) pairwise similarity scoring and the match decision, (3) clustering matches into entities without chain-merges, (4) low-latency traversal over billions of edges.
1. Blocking - making pairwise comparison tractable without missing matches
The job: out of 2B choose 2 possible pairs, generate only the tiny fraction that could plausibly be the same entity - and do it without dropping true matches that happen to disagree on whatever attribute you grouped by.
Naive approach: compare every pair
Loop over all pairs, score each.
for i in records:
for j in records where j > i:
if score(i, j) > threshold:
link(i, j)
Where it breaks:
- It is the 63,000-core-year wall from the BoE.
2 * 10^18comparisons is not “slow,” it is physically impossible on any budget. This is a non-starter, full stop. Even one daily incremental batch is ~800 core-years. The naive approach does not scale down to merely “big,” it is categorically out.
So nobody does this. The first instinct is:
Second attempt: block on an exact key (and watch it miss matches)
Group records by an exact value - say postal_code, or the first few characters of the normalized name - and only compare within each group.
blocks = group_by(records, key=lambda r: r.postal_code)
for block in blocks.values():
for i, j in pairs(block):
if score(i, j) > threshold: link(i, j)
This collapses the comparison count enormously. But it breaks in two directions at once:
- It misses true matches (recall failure). Blocking on
postal_codemeans two records for the same company are only ever compared if they agree on postal code. But the CRM has the HQ ZIP, the crawl has a branch-office ZIP, and the registry has an old address. Same company, three different ZIPs -> they never share a block -> never compared -> never merged. Any single blocking key silently drops every true match that disagrees on that key. This is the cardinal sin of entity resolution and it is invisible: you do not see the matches you failed to generate. - Skewed block sizes re-create the quadratic locally (precision/cost failure). Block on
country = USand you have one block with a billion records -(1e9 choose 2)is right back to the wall. Block on a popular city, or a common name token likeinc, and that one block dominates all the cost. A few giant blocks eat the entire compute budget while most blocks are tiny. - Dirty data splinters blocks. Block on exact normalized name and
ACME CORPvsACME CORP.(one has a period that survived normalization) fall in different blocks. The exact key is brittle to exactly the noise entity resolution exists to overcome.
A single exact blocking key is the trap: it trades the quadratic for silent recall loss and skew.
Evolved approach: multi-pass blocking with composite keys, LSH for fuzzy keys, and size capping
Blocking is not one key - it is a set of independent passes, each grouping on a different attribute, with the union of all passes forming the candidate set. Get compared in any pass and you are a candidate.
1. Multi-pass (multi-key) blocking. Run several blocking passes, each on a different, reasonably discriminative key. Two records are candidates if they collide in at least one pass. This directly fixes recall: the same company with three different ZIPs still collides on normalized_name_prefix or on phone or on domain, even though it misses on postal_code.
blocking_passes = [
lambda r: ("name3", r.norm_name[:3] + "|" + r.country), # name prefix + country
lambda r: ("phone", r.phone_e164), # exact phone
lambda r: ("domain", r.email_domain or r.website_domain), # web domain
lambda r: ("soundex", soundex(r.norm_name) + "|" + r.postal3), # phonetic + ZIP3
]
candidate_pairs = set()
for key_fn in blocking_passes:
for block in group_by(records, key_fn).values():
if len(block) <= MAX_BLOCK: # size cap, see below
candidate_pairs.update(pairs(block))
Each key is deliberately imperfect; their union achieves high recall because a true pair only has to agree on one of several attributes. This is the core trick - redundancy across keys buys recall that no single key can.
2. LSH (locality-sensitive hashing) for fuzzy keys. Exact keys miss near-duplicates (ACME CORP vs ACME CORPORATION). For name-like fields, use MinHash LSH on character/token n-grams: records whose names are similar (high Jaccard on shingles) hash to the same bucket with high probability, dissimilar ones almost never do. This gives a fuzzy blocking key - near-identical names block together without an exact match - which is what makes blocking robust to the typos and format drift that are the whole point.
# MinHash LSH blocking on name shingles
shingles = char_ngrams(r.norm_name, n=3) # {"acm","cme","me ",...}
sig = minhash(shingles, num_hashes=128)
bucket_keys = lsh_bands(sig, bands=32, rows=4) # banding: tune recall vs candidates
# records sharing any band bucket are candidates
Banding (split the signature into b bands of r rows; collide if any band matches) is the tuning knob: more bands -> higher recall, more candidate pairs; fewer bands -> fewer candidates, risk of missing. You tune it against a labeled set to hit the recall target at the lowest candidate count.
3. Size capping for skew. A block larger than MAX_BLOCK (say a few hundred) is either a useless key (country=US) or a genuine hotspot (every John Smith). Two defenses: (a) drop or deprioritize over-large blocks from that pass - if a key produces a billion-record block it is not discriminative and contributes nothing but cost; (b) make keys more specific by composing attributes (name_prefix + country instead of name_prefix alone, soundex(name) + postal3 instead of soundex(name)). Composite keys shrink blocks to a workable size while a parallel coarser pass preserves recall. The cap turns “a few giant blocks eat everything” into bounded per-block work.
4. Canopy / sorted-neighborhood as alternatives. Two classic techniques worth naming: sorted-neighborhood sorts records by a key and slides a fixed window, comparing only within the window (cheap, bounded, but one sort key = one chance to be adjacent, so run several sorts); canopy clustering uses a cheap distance to form overlapping canopies, then scores only within a canopy. In practice multi-pass + LSH + capping covers the same need with better recall control; I would lead with that and mention these as the family.
Why this is right: the union of several independent, individually-imperfect keys drives recall up (a true pair only needs to agree on one attribute, defeating the single-key recall trap); LSH makes fuzzy similarity a blocking key so format drift does not splinter blocks; size capping and composite keys defeat skew so no single block re-creates the quadratic. The candidate count drops from 10^18 to ~200 * N, which the BoE showed is a few hundred cores - exactly the 6-8 orders of magnitude we needed. And because every pass is independent, this is embarrassingly parallel in Spark: generate keys, group by key, emit intra-block pairs.
The blocking index for online linkage. For the low-latency path, precompute and store the blocking keys as an inverted index: blocking_key -> [entity_ids]. A new record computes its keys, fetches the union of entity lists (hundreds), and scores only those. That is how online resolve stays under 100ms - blocking is not just a batch concept, it is the lookup structure that makes single-record linkage fast too.
2. Pairwise similarity scoring and the match decision
The job: given a candidate pair, decide match / no-match / unsure. Blocking says “these two might be the same”; scoring says whether they are.
Naive approach: exact field equality, or one hand-tuned distance threshold
Declare a match if enough fields are exactly equal, or if an overall string distance on the name is under a fixed threshold.
def is_match(a, b):
return levenshtein(a.name, b.name) < 3 # or: a.name == b.name and a.zip == b.zip
Where it breaks:
- One field is not enough signal.
Smith Consultingin Austin andSmith Consultingin Boston are different companies with identical names; exact-name match false-merges them. ConverselyIBMandInternational Business Machinesare the same with distance ~20; a name threshold false-splits them. - A fixed threshold ignores field discriminativeness. Matching on
country = USis almost no evidence (half the data is US). Matching onphone = +1-512-...is very strong evidence. A single Levenshtein number cannot encode that different agreements carry wildly different weight. - No notion of missing data. The registry has no phone; the CRM has no founding date. A hard equality check treats “missing” as “disagree” and tanks recall.
- Not tunable per error cost. We said false merges are worse than false splits. A single distance threshold gives no principled way to trade precision for recall.
A single distance on a single field cannot weigh evidence, handle missing fields, or be tuned to the asymmetric error cost.
Evolved approach: a feature vector per pair + a probabilistic/ML model with a three-band decision
Score each candidate pair with a vector of per-field similarity features, then combine them with a model into P(match), and decide with two thresholds (match / unsure / no-match), not one.
Per-field comparison features (each field gets the comparator that fits it):
| Field | Comparator | Why |
|---|---|---|
| Name | Jaro-Winkler + token Jaccard + acronym expansion | handles typos, word reorder, IBM/International Business Machines |
| Address | parsed-component match (street/city/postal) + geocode distance | St vs Street, unit numbers, geospatial proximity |
| Phone | exact on E.164, or shared prefix | strong signal when present |
| Domain / email | exact on registrable domain | very strong, rarely shared by accident |
| Dates (founded) | within tolerance | fuzzy numeric |
| Missing either side | explicit “unknown” feature, not 0 | missing is not disagreement |
Combining the features. Two valid routes, name both:
- Fellegi-Sunter probabilistic record linkage (the classical, interpretable one): for each field estimate
m= P(fields agree | the pair is a true match) andu= P(fields agree | not a match). The per-field match weight islog2(m/u); sum the weights across fields for a total match score. A field that agrees-when-matched often but agrees-by-chance rarely (phone, domain) gets a large positive weight; a field that agrees by chance a lot (country) gets a small one. This is exactly the “weigh evidence by discriminativeness” the naive approach lacked, andm/ucan be estimated with EM on unlabeled data. - A supervised ML model (gradient-boosted trees / a small net) trained on labeled pairs: takes the same feature vector, outputs a calibrated
P(match). More accurate when you have labels, and the model is a versioned artifact so resolution is reproducible (an NFR). I would ship the ML model backed by Fellegi-Sunter-style features, keeping the interpretable weights for debugging and for bootstrapping labels.
Three-band decision, tuned to asymmetric cost:
score = model.predict(features(a, b))
if score >= T_high: decision = MATCH # auto-merge
elif score <= T_low: decision = NO_MATCH # drop
else: decision = UNSURE # -> human review queue
T_high is set high because a false merge corrupts a node and every query over it; the automatic band is deliberately conservative. The unsure band between the thresholds is routed to human review - and crucially, those human labels flow back as training data, so the model (and the m/u estimates) improve and the unsure band shrinks over time. This is the feedback loop a fixed threshold cannot have.
Why this is right: a feature vector lets each field contribute the right amount of evidence with the right comparator; Fellegi-Sunter / the ML model weighs that evidence by discriminativeness and handles missing fields as a distinct signal; two thresholds encode the asymmetric error cost and carve out an explicit human-review band; and labels from that band close the loop so accuracy compounds. The model being versioned keeps resolution reproducible.
3. Clustering matches into entities without chain-merges
The job: scoring produces pairwise match edges; we need entities, which are groups of records. Turn the match edges into clusters - carefully, because match is not transitive.
Naive approach: connected components over all match edges
Treat every MATCH edge as “same entity,” take connected components, each component is an entity.
graph = union_find()
for (a, b) in match_edges:
graph.union(a, b)
entities = graph.components()
Where it breaks:
- Transitivity is false and chains explode.
A~B(strong) andB~C(strong) does not implyA~C.Acme (Delaware)matchesAcme, andAcmematchesAcme (California)through the shared bare name, but Delaware-Acme and California-Acme are different companies. Connected components transitively chains them into one blob. One over-eager match edge (aJohn Smithhub) can connect thousands of unrelated records into a single monster entity. This is the dreaded over-merge, and connected components is maximally vulnerable to it. - No use of edge weights. A component formed by one weak (barely-over-threshold) edge is as “merged” as one with a hundred strong edges. The weakest link decides the cluster.
- Ignores must-not-link. A human who said “A and C are different” has no way to stop connected components from merging them through B.
Connected components is the right shape but it over-merges catastrophically because it trusts transitivity.
Evolved approach: correlation clustering with weighted edges, resolution-aware, and override constraints
Cluster so that the result respects both the match edges and the no-match / negative edges, and so that a cluster’s internal cohesion is required - not just connectivity.
- Use positive and negative edges. Scoring emits not only
MATCHedges but also strongNO_MATCHedges (pairs that blocked together but scored clearly belowT_low). Clustering must honor both: group records so you agree with as many positive edges and as few negative edges as possible. This is correlation clustering; it penalizes putting a negative-edge pair in the same cluster, which directly blocks the Delaware/California-Acme chain because the direct comparison of those two scored NO_MATCH. - Require cohesion, not just connectivity. Instead of raw connected components, require clusters to be dense/cohesive (e.g. average intra-cluster score above a floor, or near-clique) so a single weak bridge edge cannot fuse two otherwise-separate groups. A cheap practical version: compute connected components, then split any component whose internal structure is weak - find a sparse cut, or cap component size and re-cluster large ones with the stricter criterion. This tames the
John Smithhub: the hub connects many records, but those records have no cohesion among themselves, so the cohesion check splits them back apart. - Hard constraints from human overrides. A confirmed must-link forces two records into the same cluster; a must-not-link forbids it, overriding any model edge. These are injected as hard constraints into the clustering and stored permanently in an
overridestable so every future re-run honors them - this is how the “human always wins” and “reproducible” NFRs are met. - Incremental clustering for the online path. Re-clustering 500M entities nightly is fine for batch, but the online path cannot. For a single new record: block, score against existing entities, and if it confidently matches exactly one existing cluster, attach it (cheap, local); if it matches two clusters confidently, that is a merge signal (queue it, since merging two established entities is high-impact); if none, mint a new entity. Incremental attach keeps online linkage O(candidates), with periodic full re-clustering to repair drift.
# batch: correlation-clustering flavored
comp = connected_components(positive_edges)
for c in comp:
if cohesive(c, negative_edges, min_density): # honors NO_MATCH + cohesion
emit_entity(c)
else:
for sub in split_weak(c, negative_edges): # break weak bridges / hubs
emit_entity(sub)
apply_overrides(must_link, must_not_link) # hard constraints win
Why this is right: honoring negative edges and requiring cohesion is precisely what stops the transitive chain-merge that connected components falls for - the direct NO_MATCH between the two Acmes and the lack of internal cohesion around a John Smith hub both prevent the blob. Human overrides as hard constraints guarantee reproducibility and that people beat the model. Incremental attach keeps the online path fast while periodic full re-clustering keeps quality from drifting.
Survivorship (the merge itself). Once a cluster is fixed, build the canonical node: per attribute, pick the surviving value by a rule - most-trusted source wins (registry name over crawl name), or most-recent, or most-frequent across sources - and keep every source value with its provenance so a merge is never lossy and a split can reconstruct the originals. The canonical node stores entity_id, the survived attributes, and provenance pointers; the xref table maps every record_id -> entity_id.
4. Low-latency traversal over billions of edges
The job: serve 1-hop and bounded multi-hop queries over ~10B edges, p99 under the NFR budgets, when the graph does not fit on one machine.
Naive approach: edges in one SQL table, join to traverse
Store edges as rows (src, dst, type), traverse with self-joins.
-- 2-hop neighbors
SELECT e2.dst FROM edges e1 JOIN edges e2 ON e1.dst = e2.src
WHERE e1.src = :entity AND e1.type = 'EMPLOYS';
Where it breaks:
- Multi-hop = exploding self-joins. Each hop is another join over a 10B-row table; a 3-hop query is a 3-way self-join whose intermediate result explodes on any high-degree node. The query planner cannot keep it fast.
- One table on one machine does not hold 10B edges. You must shard, and a naive hash-sharded edge table scatters a single node’s neighbors across every shard - so even a 1-hop read fans out to the whole cluster.
- Supernodes kill it. A big employer with millions of
EMPLOYSedges returns a million rows for a 1-hop read; a 2-hop through it is hopeless.
A relational edge table traverses by join, and joins over a sharded billion-row table are the thing you are trying to avoid.
Evolved approach: adjacency-list graph store, entity-id sharding with co-located adjacency, caching, and supernode handling
Store the graph for traversal, shard it so a node’s neighbors are local, cache the hot set, and special-case supernodes.
- Adjacency-list storage, not an edge table. Each canonical node stores its outgoing (and incoming) edges as an adjacency list, typed and sorted by edge type, co-located with the node. A 1-hop read is one key lookup returning a contiguous adjacency slice - no join. This is a NoSQL wide-column / KV model (or a native graph store), chosen because the access pattern is “give me this node and its edges,” not ad-hoc relational joins.
- Shard by
entity_id, co-locate adjacency. Partition nodes across shards byentity_id; a node’s adjacency lives on the same shard. A 1-hop read is single-shard. Multi-hop still crosses shards (neighbors live elsewhere), but each hop is a batched fan-out to the distinct shards holding the frontier, not a per-edge round trip - gather the frontier, group by shard, one request per shard per hop. This bounds round trips tohops * shards_touched, and the cache cuts most of it. - Hot-entity cache. The ~150-200 GB hot working set (BoE) of popular nodes + their 1-hop adjacency lives in a distributed cache. Most traversals start or pass through hot nodes, so the cache absorbs the bulk of reads and keeps p99 inside budget. Invalidated when a merge/edge write touches the node.
- Supernode handling. A node with millions of edges is never returned whole. Partition its adjacency by edge type and by a secondary key (time, region) so a query fetches only the relevant slice with a cursor (
EMPLOYS edges, page 1). Traversals through a supernode are bounded/early-terminated (you do not expand all million neighbors for a shortest-path; you cap fan-out and note the degradation). This mirrors the celebrity problem in social graphs. - Bounded traversal with early termination. Multi-hop queries carry a hop bound and a frontier-size cap; shortest path uses bidirectional BFS (expand from both ends, meet in the middle) to cut the explored set from
b^dto2 * b^(d/2). Anything unbounded (PageRank, global components) is explicitly offline, not this path.
GET /entities/{id}/neighbors?type=EMPLOYS&limit=100&cursor=...
# single-shard adjacency slice, cache-first
# 2-hop, batched by shard per hop:
frontier = {id}
for hop in range(2):
nxt = {}
for shard, ids in group_by_shard(frontier): # one request per shard
nxt.update(shard.neighbors_batch(ids, type, cap_per_node))
frontier = cap_frontier(nxt, MAX_FRONTIER) # bound the explosion
Why this is right: adjacency-list storage turns traversal from joins into key lookups; sharding by entity_id with co-located adjacency makes 1-hop single-shard and bounds multi-hop round trips to per-shard batches per hop; the hot cache absorbs the skewed read load; supernode slicing and frontier caps keep high-degree nodes from blowing up; and bidirectional BFS keeps shortest-path tractable. Unbounded analytics stays offline where it belongs.
API Design & Data Schema
API
POST /api/v1/records # ingest one record (also bulk via batch loader)
Headers: Authorization: Bearer <token>
Body:
{
"source": "salesforce",
"source_record_id": "0013x00002",
"type": "company",
"attributes": {
"name": "ACME Corporation",
"website": "acme.com",
"phone": "+1-512-555-0100",
"address": "500 W 2nd St, Austin, TX 78701",
"founded": "1994"
}
}
Response 202:
{ "record_id": "rec_7f3...", "status": "queued_for_resolution" }
POST /api/v1/resolve # online: resolve a record to an entity NOW
Body: { same record shape }
Response 200:
{
"entity_id": "ent_9a2...",
"match_confidence": 0.97,
"decision": "LINK", // LINK | NEW | UNSURE
"candidates": [ // other near-matches, for transparency
{ "entity_id": "ent_9a2...", "score": 0.97 },
{ "entity_id": "ent_55b...", "score": 0.61 }
]
}
GET /api/v1/entities/{id} # canonical node + survived attrs + provenance
GET /api/v1/entities/{id}/neighbors?type=EMPLOYS&limit=100&cursor=...
GET /api/v1/entities/{id}/traverse?type=SUBSIDIARY_OF&hops=3&limit=200
GET /api/v1/path?from={id}&to={id}&max_hops=4 # bounded bidirectional BFS
GET /api/v1/search?q=acme+corp+delaware&type=company # text -> ranked entities
GET /api/v1/xref?source=salesforce&source_record_id=0013x00002 # -> entity_id
POST /api/v1/entities/merge { entity_ids:[...], reason } # human must-link
POST /api/v1/entities/{id}/split { record_ids:[...], reason } # human must-not-link / split
GET /api/v1/review/queue # the "unsure" band for human review
POST /api/v1/review/{pair_id} { decision: MATCH|NO_MATCH } # label -> training + override
Ingestion returns 202 (resolution is async/batch); /resolve returns 200 synchronously using the blocking index + online scoring. Merge/split return the new canonical state and record a permanent override.
Data stores
Different access patterns, different stores - stated explicitly.
1. Raw Record Store - object store + KV index, source of truth, sharded by record_id. Append-mostly, never deleted, the thing the whole graph is rebuilt from. NoSQL/object (S3 for blobs + a KV like DynamoDB/Cassandra for the indexed record) because the access is key-by-id and the write volume is high; no cross-record transactions needed.
Table: raw_records
record_id UUID PARTITION KEY
source STRING INDEX
source_record_id STRING (unique per source; dedup within source)
type STRING -- company|person|place|product
raw_payload JSON -- original, untouched
normalized JSON -- standardized common shape
ingested_at TIMESTAMP
Shard by: record_id
Secondary index: (source, source_record_id) -> record_id
2. Blocking Index - inverted index, KV, for online linkage. blocking_key -> [entity_id | record_id]. Read-heavy on the online path, rebuilt by the batch pipeline. KV (Redis for hot keys + a durable KV behind).
Table: blocking_index
blocking_key STRING PARTITION KEY -- e.g. "name3:acm|US", "phone:+15125550100"
entity_ids LIST<UUID> -- entities that produced this key
Shard by: blocking_key
3. Match / cluster state - columnar + graph, offline. Scored pairs and cluster assignments live in a columnar store (Parquet in a lake) for the Spark pipeline; not served online.
Table: scored_pairs -- offline, columnar
pair_id, record_a, record_b, features JSON, score FLOAT, decision STRING, model_version
Table: overrides -- SQL, permanent, authoritative
override_id UUID PK
kind STRING -- MUST_LINK | MUST_NOT_LINK
record_a, record_b UUID
actor, reason, created_at
(always applied as hard constraints on every re-cluster)
overrides is SQL on purpose: it is small, authoritative, must be consistent, and is the human-truth that outranks the model.
4. Knowledge Graph Store - adjacency-list, NoSQL wide-column (or native graph), sharded by entity_id, replicated. Serves lookup + traversal. Eventual consistency is acceptable; the access pattern is node+adjacency by key, so a relational store with its join-based traversal is the wrong tool (that was the naive failure).
Table: entities
entity_id UUID PARTITION KEY
type STRING
attributes JSON -- survived values
provenance JSON -- per-attribute: which record/source supplied it
version BIGINT -- bumped on merge/edit, used for cache invalidation
Shard by: entity_id
Table: edges (adjacency, co-located with src entity)
src_entity UUID PARTITION KEY -- co-located with entities shard
edge_type STRING CLUSTERING KEY
dst_entity UUID CLUSTERING KEY
properties JSON
provenance JSON
Shard by: src_entity -- 1-hop neighbor read = single partition scan
(store reverse edges too, sharded by dst, for incoming traversal)
Table: xref -- record -> entity, the merge result
record_id UUID PARTITION KEY
entity_id UUID INDEX
Shard by: record_id -- "which entity did this source record become"
5. Search index - inverted (Elasticsearch/OpenSearch). Name/attribute text -> ranked entity_id, for the /search and fuzzy-lookup path. Rebuilt from canonical entities.
6. Entity cache - Redis. Hot nodes + 1-hop adjacency, ~200 GB, invalidated by version.
Why NoSQL for the graph and raw store, SQL only for overrides: the raw records and the graph are huge, key-scoped, read-heavy (graph) / write-heavy (raw), and tolerant of eventual consistency - wide-column/KV scales those cheaply, and the traversal access pattern (node + adjacency by id) is exactly what adjacency-list NoSQL serves and what relational joins serve badly. The only place needing strong consistency is the overrides table - small, authoritative human decisions that must never be lost or reordered - so that is SQL. Match the guarantee to the data.
Bottlenecks & Scaling
Where it breaks first, in order, and the fix for each.
1. The quadratic pair explosion (breaks first, before anything else matters). All-pairs is 10^18; even a daily batch against 500M entities is 10^16.
Fix: multi-pass blocking + LSH + size capping cuts candidates to ~200 * N. This is the entire reason the system is feasible. The union of several imperfect keys preserves recall; composite keys and caps defeat skew; LSH makes fuzzy keys possible.
2. Skewed blocks re-creating the quadratic locally. One country=US or name=John Smith block holds a billion records.
Fix: size cap (drop/deprioritize non-discriminative over-large blocks), composite keys (name_prefix + country) to shrink blocks, and a coarser parallel pass to keep recall. Per-block work becomes bounded.
3. Over-merge via transitive chaining in clustering. One bad match edge or a hub record fuses thousands of unrelated records into one node. Fix: correlation clustering honoring NO_MATCH edges + a cohesion requirement that splits weakly-connected components, so transitivity cannot chain and a hub without internal cohesion is split apart. Human must-not-link overrides as hard constraints.
4. Supernode / hot node on reads. A big employer with millions of edges makes 1-hop reads return a million rows and multi-hop explode. Fix: partition adjacency by edge type + secondary key with cursored paging, never return it whole; cap fan-out / early-terminate traversals through supernodes; the hot-entity cache absorbs the repeated reads.
5. Cross-shard multi-hop round trips. Neighbors scattered across shards turn a 2-hop into a fan-out to the whole cluster.
Fix: shard by entity_id with co-located adjacency (1-hop is single-shard); batch the frontier per shard per hop (one request per shard, not per edge); bidirectional BFS for shortest path; frontier caps. Round trips bounded to hops * shards_touched, mostly served from cache.
6. Online resolve latency. Scoring a new record against 500M entities cannot be done live.
Fix: the blocking index (key -> entity_ids) fetches only the hundreds of candidates sharing a key; score only those. O(candidates), sub-100ms.
7. Model / blocking-strategy changes require reprocessing everything. A better match model or new blocking key must re-resolve 2B records. Fix: the raw store is the source of truth and the graph is a rebuildable projection - reprocessing is a big offline Spark job writing a new graph version, swapped in atomically; overrides are re-applied as hard constraints so human decisions survive the rebuild. Deterministic, reproducible resolution (an NFR) is what makes this safe.
8. False merges silently corrupting queries. A wrong auto-merge pollutes every traversal through that node and is hard to detect.
Fix: conservative T_high, the unsure band -> human review, provenance kept so a merge is never lossy and a split can reconstruct the originals, plus monitoring on merge rate / cluster-size distribution to catch a blocking or model regression that suddenly over-merges.
9. Ingestion throughput and dual-source dedup. 50M records/day from 50 sources with retries and re-sends.
Fix: dedup within a source on (source, source_record_id); the blocking/scoring pipeline is embarrassingly parallel in Spark (map to keys, group, emit pairs, score); a streaming path (Kafka) for high-value sources feeds the online resolver.
10. Single points of failure. No single stateful node loss may stop or lose data. Fix: raw store, graph store, blocking index, and cache all replicated; graph and cache serve stale-but-available on a shard blip (reads degrade, never block); stateless resolve/query services horizontally scaled behind load balancers; the batch pipeline can lag an hour without user impact.
Shard keys, stated plainly: raw_records -> record_id (secondary index on (source, source_record_id)). entities and edges -> entity_id / src_entity (adjacency co-located for single-partition 1-hop; reverse edges by dst for incoming). xref -> record_id. blocking_index -> blocking_key. overrides -> SQL, small, replicated. Spark pipeline partitions by blocking key for the pair-generation stage, by cluster for the merge stage. Never block on a non-discriminative key (country) - it concentrates everything into one giant partition, which is failure mode #2.
Wrap-Up
The trade-offs that define this design:
- Blocking is the whole system; everything else serves it. All-pairs is
10^18comparisons (63,000 core-years); multi-pass blocking + LSH + size capping cuts it to~200 * N(a few hundred cores). We accept the complexity of several imperfect, redundant keys because their union is the only thing that buys both recall and tractability. - Recall is bought with redundant keys; precision with a scored, three-band decision. A true pair only needs to agree on one blocking key (recall), and a feature-vector match model with conservative
T_highplus a human-reviewed unsure band keeps false merges rare (precision tuned to the asymmetric cost). - Match is not transitive, so clustering must fight chaining. Correlation clustering honoring negative edges plus a cohesion requirement stops one bad edge or a hub from fusing thousands of records; human overrides are hard constraints that always win.
- The graph is a rebuildable projection of the raw records. Raw records (and human overrides) are the source of truth; the canonical graph is derived, so a model or blocking upgrade is a reprocessing job, not a migration - and resolution is deterministic so it is reproducible.
- Serving is a sharded, cached adjacency-list graph. Shard by
entity_idwith co-located adjacency (single-shard 1-hop), batch the frontier per shard per hop, cache the hot set, and slice supernodes - keeping traversal local over billions of edges.
One-line summary: ingest heterogeneous records into a durable raw store, generate candidate pairs with multi-pass LSH blocking that defeats the 10^18 quadratic without losing true matches, score each pair with a probabilistic/ML match model into a conservative three-band decision, cluster the matches with correlation clustering and human-override constraints so transitivity cannot chain-merge, collapse each cluster into one canonical node with provenance and survivorship, and serve it as a sharded, cached adjacency-list graph with bounded multi-hop traversal - so the same real-world entity becomes one node no matter how many sources named it differently, and queries over billions of edges stay local and fast.
Comments