Skip to content
Tech Intuition
Tech Intuition

Appearance

Theme

Signal · Dark with amber

Background

Slow stars and the odd comet

Connect

Streams, sketches and search · Lesson 11 of 11

Near-duplicates and freshness

How to find pages that are almost the same and decide when to look at a page again: simhash fingerprints and block tables for near-duplicates, and a freshness model, refresh policies and change-rate estimates for revisits, with tested C#.

ConceptCore30 min readUpdated

  • 7 code samples
  • 6 interviewer follow-ups
  • 1 decision checkpoint
  • 4 self-checks

Read first: Probabilistic data structures and sketches

By the end you will be able to
  • Explain how a 64-bit simhash turns a page into a fingerprint whose Hamming distance follows how much text changed, and why a threshold of 3 bits means a word or two and not a rewritten paragraph.
  • Find every stored fingerprint within k bits of a query without a full scan, by cutting the fingerprint into blocks and keeping a table for each choice of the blocks that must match, and size the tables for billions of fingerprints.
  • Use the freshness formula (1 - e^-x) / x to compare ways of spending a budget of visits, and say why visiting in proportion to the change rate is worse than visiting everything equally.
  • Estimate how fast a page changes from visits that only say whether it changed, and know where that estimate stops being able to tell pages apart.

7 code samples (316 lines), collapsed so the explanation stays in focus.

A crawler, a feed reader, a search index and a cache all keep copies of things that live somewhere else, and two questions come up in every one of them. Is this new thing really new, or a copy of something already held? And how long can the copy I hold be trusted before I have to look again?

This lesson answers both in tested C#. The first half is about near-duplicates: a 64-bit simhash fingerprint that moves a little when a page moves a little, and a set of tables that finds every stored fingerprint within a few bits without scanning them all. The second half is about freshness: a model of how long a copy stays up to date, three ways to spend a limited budget of visits, and an estimator for how fast a page changes. It is the theory under two sections of the web crawler case study, and it builds on the sketches in probabilistic data structures.

HLD

Why an exact hash is not enough for duplicates

Different addresses often lead to the same content: mirrors, printer-friendly versions, one article syndicated to ten sites, a page whose only change is a visit counter. Keeping and indexing every copy wastes storage and fills results with repeats, so a pipeline wants to recognise a copy and keep one canonical page.

An exact duplicate is easy: hash the extracted text and look the hash up. That misses everything that differs by a single character, and a timestamp is enough to change a hash. A near-duplicate needs a fingerprint that moves a little when the page moves a little, and a way to ask "is anything stored close to this?" without comparing against everything.

LLD

Simhash: a fingerprint that moves a little

Simhash comes from Moses Charikar's work on similarity estimation, and it is the fingerprint Manku, Jain and Das Sarma apply to web crawling. Cut the text into overlapping three-word shingles, hash each shingle to 64 bits, and let every shingle vote on every bit: plus one where its hash has a 1, minus one where it has a 0. Each bit of the fingerprint is the sign of its total. Pages that share most of their shingles share most of their votes, so their fingerprints differ in only a few bits. The distance between two fingerprints is the Hamming distance, the number of differing bits, which is one XOR and a population count. The paper reports 64-bit fingerprints and a threshold of 3 bits working well for a repository of eight billion pages.

C# · A 64-bit simhash: every feature votes for or against each bit of the fingerprint, and…38 lines
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;

// A 64-bit simhash: every feature votes for or against each bit of the fingerprint, and the majority sets the bit.
// Documents that share most of their features end up a few bits apart, however the rest differs.
public static class SimHash
{
    public static ulong Fingerprint(IEnumerable<string> features)
    {
        var votes = new int[64];
        foreach (string feature in features)
        {
            ulong h = Hash(feature);
            for (int bit = 0; bit < 64; bit++) votes[bit] += (h >> bit & 1) == 1 ? 1 : -1;
        }
        ulong print = 0;
        for (int bit = 0; bit < 64; bit++) if (votes[bit] > 0) print |= 1UL << bit;
        return print;
    }

    // Three-word shingles: changing one word disturbs only the three shingles that contain it.
    public static IEnumerable<string> Shingles(string[] words, int size = 3)
    {
        for (int i = 0; i + size <= words.Length; i++) yield return string.Join(' ', words, i, size);
    }

    public static int Distance(ulong a, ulong b) => BitOperations.PopCount(a ^ b);

    private static ulong Hash(string s)
    {
        ulong h = 14695981039346656037UL;
        foreach (char c in s) { h ^= c; h *= 1099511628211UL; }
        h ^= h >> 33; h *= 0xff51afd7ed558ccdUL; h ^= h >> 33; h *= 0xc4ceb9fe1a85ec53UL; h ^= h >> 33;
        return h;
    }
}
C# · Synthetic pages: 300 words drawn from a Zipf vocabulary, so a few words are very common…41 lines
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

// Synthetic pages: 300 words drawn from a Zipf vocabulary, so a few words are very common, as in real text.
var rng = new Random(11);
var cumulative = new double[5_000];
double running = 0;
for (int r = 0; r < cumulative.Length; r++) cumulative[r] = running += 1.0 / (r + 1);
string Word() { double u = rng.NextDouble() * running; int lo = 0, hi = cumulative.Length - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (cumulative[mid] < u) lo = mid + 1; else hi = mid; } return "w" + lo; }
string[] Page(int words) => Enumerable.Range(0, words).Select(_ => Word()).ToArray();
ulong Print(string[] words) => SimHash.Fingerprint(SimHash.Shingles(words));
string[] Replace(string[] page, int count)
{
    var copy = (string[])page.Clone();
    foreach (int i in Enumerable.Range(0, copy.Length).OrderBy(_ => rng.Next()).Take(count)) copy[i] = Word();
    return copy;
}

// Unrelated pages are far apart. Pages with a few words changed are close. The threshold of 3 bits sits in the empty space between.
var unrelated = Enumerable.Range(0, 10_000).Select(_ => SimHash.Distance(Print(Page(300)), Print(Page(300)))).ToArray();
Console.WriteLine($"unrelated pages: mean {unrelated.Average():F1} bits apart, closest of 10,000 pairs {unrelated.Min()}");
Debug.Assert(unrelated.Min() > 3);
foreach (int changed in new[] { 1, 2, 3, 6, 15, 30 })
{
    var distances = Enumerable.Range(0, 2_000).Select(_ => { var p = Page(300); return SimHash.Distance(Print(p), Print(Replace(p, changed))); }).ToArray();
    Console.WriteLine($"{changed,2} of 300 words replaced: mean {distances.Average():F1} bits, {distances.Count(d => d <= 3) / (double)distances.Length:P0} within 3 bits");
}
// The more of a page is template, the closer two different pages look, so strip menus and footers before fingerprinting.
var template = Page(300);
foreach (double share in new[] { 0.0, 0.5, 0.8, 0.9, 0.95, 0.98 })
{
    int shared = (int)(300 * share);
    var distances = Enumerable.Range(0, 500).Select(_ =>
    {
        string[] Compose() => template.Take(shared).Concat(Page(300 - shared)).ToArray();
        return SimHash.Distance(Print(Compose()), Print(Compose()));
    }).ToArray();
    Console.WriteLine($"{share:P0} of two different pages is shared template: mean {distances.Average():F1} bits apart, {distances.Count(d => d <= 3) / (double)distances.Length:P0} within 3");
}

Unrelated pages averaged 31.9 bits apart (two random 64-bit values average 32), and the closest of 10,000 pairs was 18, so a threshold of 3 sits in a wide empty gap. How far a change moves the fingerprint is the less obvious part:

Words replaced, of 300Mean distance movedWithin 3 bits
12.7 bits70%
24.0 bits43%
34.8 bits29%
66.9 bits8%
1510.9 bits0%
3015.1 bits0%

A threshold of 3 is strict. It means a word or two, a changed date or counter, and not a rewritten paragraph, and even one word in 300 leaves 30% of the pages beyond it. The same edit moves a longer page by less, because each bit's vote has more voters, and a looser threshold finds more copies at the price of more tables, below. Choose the threshold from labelled pairs of your own pages, not from a paper.

The other trap is the template. The more of a page is menus, footers and sidebars, the closer two different pages look:

Share of each page that is shared templateMean distance between two different pagesWithin 3 bits
0%31.7 bits0%
50%21.1 bits0%
80%12.6 bits0%
90%9.4 bits0%
95%4.4 bits31%
98%3.2 bits58%

So fingerprint the main content, with the boilerplate stripped, and not the whole page, or two different articles on a heavily templated site are called copies.

LLD

Finding every neighbour without a full scan

Comparing two fingerprints is cheap, but comparing a query with eight billion of them is not. The way out is the pigeonhole principle. Cut the 64 bits into p blocks. Two fingerprints that differ in at most 3 bits differ in at most 3 blocks, so at least p minus 3 of their blocks are identical. Build one table for each choice of p minus 3 blocks, keyed by the bits of those blocks. Every near-duplicate then shares a key with the query in at least one table, so a lookup in every table finds all of them, and only the few fingerprints that share a key need the bit-by-bit check. With p = 4, one 16-bit block must match, which gives four tables.

C# · Finds every stored fingerprint within k bits of a query without comparing against all of…72 lines
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;

// Finds every stored fingerprint within k bits of a query without comparing against all of them.
// Cut the 64 bits into p blocks. Two fingerprints that differ in at most k bits differ in at most k blocks, so at least p - k
// blocks are identical. One table for each choice of p - k blocks, keyed by those blocks, therefore sees every such pair.
public sealed class NearIndex
{
    private readonly int _k;
    private readonly ulong[] _masks;                       // the bits each table keys on
    private readonly (ulong Key, int Id)[][] _tables;
    private readonly ulong[] _prints;
    private readonly int[] _seen;
    private int _stamp;

    public NearIndex(ulong[] prints, int blocks, int k)
    {
        _k = k;
        _prints = prints;
        _seen = new int[prints.Length];
        var blockMask = new ulong[blocks];
        for (int b = 0; b < blocks; b++)
        {
            int from = b * 64 / blocks, to = (b + 1) * 64 / blocks;
            blockMask[b] = ((1UL << (to - from)) - 1) << from;
        }
        var masks = new List<ulong>();
        for (int choice = 0; choice < 1 << blocks; choice++)
        {
            if (BitOperations.PopCount((uint)choice) != blocks - k) continue;
            ulong mask = 0;
            for (int b = 0; b < blocks; b++) if ((choice >> b & 1) == 1) mask |= blockMask[b];
            masks.Add(mask);
        }
        _masks = masks.ToArray();
        _tables = _masks.Select(mask =>
        {
            var table = prints.Select((p, id) => (Key: p & mask, Id: id)).ToArray();
            Array.Sort(table, (a, b) => a.Key.CompareTo(b.Key));
            return table;
        }).ToArray();
    }

    public int Tables => _tables.Length;
    public int KeyBits(int table) => BitOperations.PopCount(_masks[table]);

    // Every id within k bits of the query. `compared` counts the fingerprints that had to be checked bit by bit.
    public List<int> Near(ulong query, out int compared)
    {
        var found = new List<int>();
        compared = 0;
        _stamp++;
        for (int t = 0; t < _tables.Length; t++)
        {
            ulong key = query & _masks[t];
            var table = _tables[t];
            int lo = 0, hi = table.Length;
            while (lo < hi) { int mid = (lo + hi) / 2; if (table[mid].Key < key) lo = mid + 1; else hi = mid; }
            for (int i = lo; i < table.Length && table[i].Key == key; i++)
            {
                int id = table[i].Id;
                if (_seen[id] == _stamp) continue;
                _seen[id] = _stamp;
                compared++;
                if (SimHash.Distance(_prints[id], query) <= _k) found.Add(id);
            }
        }
        return found;
    }
}
C# · 200,000 stored fingerprints, then queries that have a neighbour within 3 bits and…30 lines
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

// 200,000 stored fingerprints, then queries that have a neighbour within 3 bits and queries that do not.
var stored = Enumerable.Range(0, 200_000).Select(_ => (ulong)rng.NextInt64() ^ (ulong)rng.NextInt64() << 1).ToArray();
var queries = new List<ulong>();
for (int q = 0; q < 500; q++)
{
    ulong p = stored[rng.Next(stored.Length)];
    foreach (int bit in Enumerable.Range(0, 64).OrderBy(_ => rng.Next()).Take(1 + q % 3)) p ^= 1UL << bit;     // 1, 2 or 3 bits flipped
    queries.Add(p);
}
for (int q = 0; q < 500; q++) queries.Add((ulong)rng.NextInt64() ^ (ulong)rng.NextInt64() << 1);
var expected = queries.Select(query => Enumerable.Range(0, stored.Length).Where(i => SimHash.Distance(stored[i], query) <= 3).ToHashSet()).ToList();
foreach (int blocks in new[] { 4, 5, 6, 7 })
{
    var index = new NearIndex(stored, blocks, 3);
    long compared = 0;
    for (int q = 0; q < queries.Count; q++)
    {
        var found = index.Near(queries[q], out int c);
        compared += c;
        Debug.Assert(expected[q].SetEquals(found));                               // exactly the answer a full scan gives
    }
    // The same tables at web scale: the fingerprints that share a key with the query in some table must all be compared.
    double atScale = Enumerable.Range(0, index.Tables).Sum(t => 8e9 / Math.Pow(2, index.KeyBits(t)));
    Console.WriteLine($"{blocks} blocks, {index.Tables,2} tables: {compared / (double)queries.Count,4:F1} compared per query out of {stored.Length:N0}; at 8 billion fingerprints about {atScale:N0}");
}
BlocksTablesKey bitsCompared per query, 200,000 storedAt 8 billion stored
441612.8about 488,000
510250.5about 1,700
620320.5about 41
735360.5about 3

The answers were exactly those of a full scan, asserted for 1,000 queries. The 0.5 is a floor: half of the queries have one true neighbour, so past four blocks the tables return almost nothing but real neighbours at this size. At eight billion fingerprints the picture changes. Four tables of 16-bit keys leave about 488,000 fingerprints to compare for every query, which is hopeless, and twenty tables of 32-bit keys leave about 41. The price is memory: every table holds every fingerprint, about 100 GB for eight billion at 12 bytes each, so twenty tables are about 2 TB, spread over machines that each take the query.

LLD

Freshness: when to look again

Every system that keeps a copy has more things to refresh than refreshes to spend. A crawler with ten billion pages and a budget of a billion fetches a month revisits each page once in ten months on average, while a news front page changes in minutes and an old manual never does. "When do I look again?" is a scheduling problem with a measurable goal: keep as much of the stored copy as possible equal to the live original.

A model. Treat a page's changes as random events at a steady average rate of lambda changes a day (a Poisson process), and visit it at a steady rate of f visits a day. The copy is up to date from a visit until the next change, so the share of time it is fresh depends only on the ratio of the two:

Example · formula
fresh share = (1 - e^-x) / x        with x = lambda / f
lambda = changes a day, f = visits a day, x = changes between visits
the first visit to a page buys about 1 / lambda days of freshness

The last line is the one to remember. A visit to a page that changes every ten minutes buys ten minutes of freshness, and a visit to a page that changes monthly buys a month, so a good policy spends visits where they are worth the most. A cache entry is a copy with a refresh interval, so the same formula sets a time to live: a key that changes ten times a day and is refreshed every hour is current 81.8% of the time, and refreshing it every five minutes lifts that to 98.3%.

Decision checkpoint · pick one

You can afford half a visit per page per day on average. Pages change at very different rates, from every ten minutes to about once a month. Where do the visits go?

Commit to an answer first. The reasoning for every option appears after you pick.

C# · When to look at a page again. A page changes at random times (a Poisson process) at…62 lines
using System;
using System.Collections.Generic;
using System.Linq;

// When to look at a page again. A page changes at random times (a Poisson process) at `lambda` changes a day, and the crawler visits it
// at a steady `f` visits a day. The share of time the stored copy is up to date is (1 - e^-x) / x with x = lambda / f.
public static class Refresh
{
    public static double Freshness(double lambda, double f)
    {
        if (f <= 0) return 0;
        double x = lambda / f;
        return x < 1e-9 ? 1 : (1 - Math.Exp(-x)) / x;
    }

    // What one more visit a day is worth, d(freshness)/df. For a page that changes constantly it is small, because the copy is
    // stale again almost at once. For a page that rarely changes it is small once the copy is fresh already.
    public static double Gain(double lambda, double f)
    {
        if (f <= 0) return 1 / lambda;
        double x = lambda / f;
        double g = x < 1e-3 ? x * x / 2 - x * x * x / 3 : 1 - (1 + x) * Math.Exp(-x);
        return g / lambda;
    }

    public static double Average(double[] lambda, double[] f) => lambda.Select((l, i) => Freshness(l, f[i])).Average();

    public static double[] Uniform(double[] lambda, double budget) => lambda.Select(_ => budget / lambda.Length).ToArray();

    public static double[] Proportional(double[] lambda, double budget)
    {
        double total = lambda.Sum();
        return lambda.Select(l => budget * l / total).ToArray();
    }

    // Give each page the visit rate at which one more visit is worth the same `price` everywhere, and find the price at which the
    // budget is exactly spent. A page whose first visit would be worth less than the price gets none.
    public static double[] MarginalGain(double[] lambda, double budget)
    {
        double RateFor(double l, double price)
        {
            if (price >= 1 / l) return 0;
            double lo = 0, hi = l;
            while (Gain(l, hi) > price) hi *= 2;
            for (int i = 0; i < 80; i++) { double mid = (lo + hi) / 2; if (Gain(l, mid) > price) lo = mid; else hi = mid; }
            return (lo + hi) / 2;
        }
        double low = 0, high = 1 / lambda.Min();
        for (int i = 0; i < 80; i++)
        {
            double price = (low + high) / 2;
            if (lambda.Sum(l => RateFor(l, price)) > budget) low = price; else high = price;
        }
        return lambda.Select(l => RateFor(l, high)).ToArray();
    }

    // What a crawler sees is one bit per visit: did the page change since the last one? Counting those bits misses every change
    // after the first between two visits. This estimator (Cho and Garcia-Molina) corrects for that, and stays finite when every
    // visit saw a change.
    public static double NaiveRate(int changed, int visits, double interval) => changed / (double)visits / interval;
    public static double EstimatedRate(int changed, int visits, double interval) => -Math.Log((visits - changed + 0.5) / (visits + 0.5)) / interval;
}
C# · A cache entry is a copy with a refresh interval: ten changes a day, refreshed hourly and…55 lines
using System;
using System.Diagnostics;
using System.Linq;

// A cache entry is a copy with a refresh interval: ten changes a day, refreshed hourly and every five minutes.
Console.WriteLine($"10 changes a day, refreshed hourly: current {Refresh.Freshness(10, 24):P1} of the time; every five minutes: {Refresh.Freshness(10, 288):P1}");
Debug.Assert(Math.Abs(Refresh.Freshness(10, 24) - 0.8178) < 0.001);

// 10,000 pages: a few change every ten minutes, some hourly, and most only weekly or monthly. Changes a day, per page.
double[] rates = { 144, 24, 1, 1.0 / 7, 1.0 / 30 };
int[] counts = { 200, 800, 2_000, 3_000, 4_000 };
double[] lambda = rates.SelectMany((r, i) => Enumerable.Repeat(r, counts[i])).ToArray();

Console.WriteLine("budget (visits a day)   uniform   proportional   marginal gain   pages never visited");
foreach (double perPage in new[] { 0.1, 0.25, 0.5, 1, 2 })
{
    double budget = perPage * lambda.Length;
    var uniform = Refresh.Uniform(lambda, budget);
    var proportional = Refresh.Proportional(lambda, budget);
    var best = Refresh.MarginalGain(lambda, budget);
    Debug.Assert(Math.Abs(best.Sum() - budget) < budget * 1e-6);
    Console.WriteLine($"{perPage,5} per page a day    {Refresh.Average(lambda, uniform),6:P1}   {Refresh.Average(lambda, proportional),9:P1}   {Refresh.Average(lambda, best),12:P1}   {best.Count(f => f == 0),8}");
    Debug.Assert(Refresh.Average(lambda, uniform) > Refresh.Average(lambda, proportional));
    Debug.Assert(Refresh.Average(lambda, best) >= Refresh.Average(lambda, uniform));
}

// Where the visits go at half a visit per page per day.
{
    double budget = 0.5 * lambda.Length;
    var best = Refresh.MarginalGain(lambda, budget);
    Console.WriteLine("changes a day   uniform   proportional   marginal gain  (visits a day for one page of that kind)");
    var uniform = Refresh.Uniform(lambda, budget);
    var proportional = Refresh.Proportional(lambda, budget);
    for (int i = 0, start = 0; i < rates.Length; start += counts[i], i++)
        Console.WriteLine($"{rates[i],13:0.###}   {uniform[start],7:0.###}   {proportional[start],12:0.###}   {best[start],13:0.###}");
}

// Check the formula against a simulation: every twentieth of the pages above, 4,000 days, a visit at a steady interval.
var dice = new Random(3);
double Simulate(double l, double f, int days)
{
    if (f <= 0) return 0;
    double interval = 1 / f, fresh = 0, time = 0;
    while (time < days) { double untilChange = -Math.Log(1 - dice.NextDouble()) / l; fresh += Math.Min(untilChange, interval); time += interval; }
    return fresh / time;
}
{
    double budget = 0.5 * lambda.Length;
    var best = Refresh.MarginalGain(lambda, budget);
    var sample = Enumerable.Range(0, lambda.Length).Where(i => i % 20 == 0).ToArray();
    double formula = sample.Select(i => Refresh.Freshness(lambda[i], best[i])).Average();
    double simulated = sample.Select(i => Simulate(lambda[i], best[i], 4_000)).Average();
    Console.WriteLine($"freshness by formula {formula:P1}, by simulation {simulated:P1}");
    Debug.Assert(Math.Abs(formula - simulated) < 0.01);
}

The same 10,000 pages show what each policy does as the budget grows:

Visits a day per pageUniformIn proportion to change rateMarginal gainPages marginal gain never visits
0.152.0%2.0%55.5%3,000
0.2565.3%4.9%68.4%1,000
0.573.6%9.9%77.4%1,000
180.3%19.7%83.1%1,000
285.1%36.4%87.4%200

And where the visits go at half a visit per page per day:

Changes a dayUniformIn proportion to change rateMarginal gain
144 (200 pages)0.514.20
24 (800 pages)0.52.370
1 (2,000 pages)0.50.101.17
0.14 (3,000 pages)0.50.0140.53
0.033 (4,000 pages)0.50.0030.27

Three things stand out. Proportional is far worse than doing nothing clever. It gives every page the same ratio of changes to visits, so every page ends up equally stale, 9.9% fresh here, because the 1,000 fastest pages took 95% of the visits and stayed stale anyway while slow pages that one visit would have kept fresh for weeks were hardly visited. The best allocation gives nothing to the fastest pages, whose copy is out of date within minutes whatever the crawler does, the most to pages that change about daily, and a visit every four days to the monthly ones. The gain over uniform is modest here, three to four points at every budget, because 70% of this population changes weekly or monthly and stays fresh either way. It grows with the share of pages that change about as fast as the crawler can visit. The formula also matched a simulation of the same pages, 77.4% both ways.

LLD

Knowing how fast a page changes

The policy needs lambda, and nobody knows it. A visit returns one bit, whether the page changed since the last visit, and counting those bits misses every change after the first between two visits, so it understates fast pages. The estimator in the code takes the number of visits and the number that found no change, and returns minus the natural logarithm of (no-change visits plus a half) over (visits plus a half), per visit interval. The half corrects a bias and keeps the answer finite when every visit saw a change.

C# · Estimating a page's rate from daily visits. 60 visits, repeated 2,000 times for each…18 lines
using System;
using System.Diagnostics;

// Estimating a page's rate from daily visits. 60 visits, repeated 2,000 times for each true rate.
Console.WriteLine("true rate   counting changes seen   estimator");
foreach (double truth in new[] { 0.05, 0.2, 0.5, 1, 2, 5 })
{
    double naive = 0, estimate = 0;
    for (int run = 0; run < 2_000; run++)
    {
        int changed = 0;
        for (int visit = 0; visit < 60; visit++) if (dice.NextDouble() < 1 - Math.Exp(-truth)) changed++;     // at least one change since the last visit
        naive += Refresh.NaiveRate(changed, 60, 1);
        estimate += Refresh.EstimatedRate(changed, 60, 1);
    }
    Console.WriteLine($"{truth,9} {naive / 2_000,16:F2} {estimate / 2_000,15:F2}");
    if (truth <= 2) Debug.Assert(Math.Abs(estimate / 2_000 - truth) < truth * 0.1);
}
True changes a dayCounting the changes seenThe estimator
0.050.050.05
0.20.180.20
0.50.400.51
10.631.00
20.862.00
50.994.39

A page that changes twice a day shows a change at 86% of daily visits, so counting reports 0.86 and the estimator recovers 2.00. At five changes a day it reports 4.4, and with 60 daily visits it cannot go past the natural logarithm of 121, which is 4.8, however fast the page is. Daily visits cannot tell five changes a day from fifty, and to measure a fast page you must visit it faster. A new page starts with a prior from its site, since a news site changes faster than a documentation site, and every visit updates it.

HLD

Duplicates and freshness in a pipeline

  • Where the detector sits. After the parser: fingerprint the extracted main text, look the fingerprint up, and if a neighbour is within 3 bits mark the page as a copy and keep one canonical page. The result steers the crawl too, since a URL pattern that keeps producing copies, such as the same listing sorted ten ways, loses priority and budget.
  • What counts as changed. Compare the main content, or its simhash, and not the bytes. An advertisement, a timestamp or a session token changes the bytes on every fetch, so the page would look like the fastest-changing one on the site, which the best allocation then ignores. A change of more than a few bits in the simhash is a real change.
  • Weights. Freshness matters more on pages people use, so multiply each page's gain by a weight from traffic, links or how often queries return it, and the same rule tilts the visits toward them. Cap the allocation by each host's politeness budget.
  • Conditional requests. Send the stored ETag as If-None-Match, or If-Modified-Since. An unchanged page answers 304 Not Modified with no body, which saves the transfer, the parsing and the storage but still costs a round trip. Servers implement validators unevenly, so count how often a 200 carries identical content and stop trusting those hosts' validators.
  • Hints and a lane for discovery. A sitemap carries a lastmod for each URL and a feed announces new items (sitemaps.org (opens in a new tab) limits a file to 50,000 URLs and 50 MB). Both are sometimes wrong, so trust a site only as far as its history supports. Home pages, listings and feeds are revisited often because they link to new pages, so give them a budget of their own.
  • Caches. The same formula sets a time to live. The longer the interval, the staler a key that changes often, so a fast-changing key wants a short time to live or an invalidation instead of a timer. See cache consistency, stampedes and hot keys for what goes wrong when many entries expire together.

HLD

Failure modes and edge cases for duplicates and freshness

SituationWhat happensDefence
Fingerprinting the whole page, template includedDifferent pages on a templated site are called copies (31% of pairs at 95% shared template)Extract the main content first
Short pagesFew shingles, so the fingerprint is noisy and unrelated pages can land closeA minimum length, and exact hashing for the rest
A hash that differs between machines or versionsNeighbours are never foundYour own stable 64-bit hash with a fixed seed, and a version stored with every fingerprint
A threshold copied from a paperMissed copies or false onesChoose it from labelled pairs of your own pages and measure precision and recall
A page that changes on every fetch (ads, timestamps)It looks like the fastest page and wastes visitsJudge change by the main content, not the bytes
A rate estimated from two or three visitsWild estimatesA prior from the site, a minimum number of visits, and clamping
A site whose lastmod is always nowVisits wasted on unchanged pagesLearn each site's reliability from its history
A budget cut, or a host capThe planned visit rates cannot be metRecompute with the cap as a constraint and renormalise

Senior depth

What senior interviews ask about duplicates and freshness

Interviewer follow-upL5Why not just hash the page to detect duplicates?How to answer

A hash only matches identical bytes, and a timestamp, a counter or an advertisement changes them on every fetch, so near-copies never match. Simhash is a fingerprint that moves a little when the page moves a little, so a small edit changes a few bits and a comparison can use a distance instead of equality. Keep the exact hash for byte-identical pages, which it finds cheaply.

Interviewer follow-upL6How does simhash work, and what threshold would you use?How to answer

Shingle the main content, hash each shingle to 64 bits, let every shingle vote plus or minus one on each bit, and take the sign of each total. Pages sharing most of their shingles share most of their votes. Unrelated pages were 31.9 bits apart in the test and a word of 300 changed moved a page 2.7 bits, so 3 bits means a word or two. The published choice for eight billion pages is 64 bits and 3, but choose it from labelled pairs of your own data, and strip the template first.

Interviewer follow-upL6How do you find all near-duplicates among billions of fingerprints?How to answer

Cut the fingerprint into p blocks. Two fingerprints within 3 bits share at least p minus 3 blocks exactly, so keep one table for each choice of p minus 3 blocks, keyed by those blocks, and verify the few candidates bit by bit. Four tables of 16-bit keys return exactly the full-scan answer and compare about 13 of 200,000, but at eight billion they leave about 488,000 candidates, so use about twenty tables of 32-bit keys, which leave about 41, at the cost of twenty copies of the index.

Interviewer follow-upL6How would you set a page's recrawl interval, or a cache TTL?How to answer

Model changes as random at a rate lambda and a refresh interval as 1 over f: the copy is current for (1 - e^-x) / x of the time, with x = lambda / f. That gives the TTL directly (a key changing ten times a day, refreshed hourly, is current 81.8% of the time). With a limited budget, spend visits where one more visit buys the most freshness, weighted by importance, and cap by what the origin can take.

Interviewer follow-upL6Why not recrawl pages in proportion to how often they change?How to answer

It gives every page the same ratio of changes to visits, so every page ends up equally stale, and it spends the budget on pages that are out of date again within minutes. In the test it left 9.9% of the copy fresh, against 73.6% for visiting every page equally and 77.4% for marginal gain, which gives the fastest pages nothing because a visit to them buys about one over their change rate in days.

Interviewer follow-upL7How would you estimate how often a page changes when you only see it occasionally?How to answer

Each visit says only whether the page changed since the last one, so counting changes understates fast pages (0.86 for a page that really changes twice a day). Use an estimator that corrects for the changes hidden between visits, such as minus the log of (unchanged visits plus a half) over (visits plus a half) per interval, which recovered 2.00. It cannot separate pages much faster than the visit rate (4.4 for five a day), so start new pages from a prior for their site, visit them often enough to measure, and treat anything that changes faster than you can follow as not worth chasing.

HLD

Putting duplicates and freshness into an answer

Say the two ideas in two sentences. "A near-duplicate is a fingerprint a few bits away: simhash of the main content, with tables keyed on blocks of the bits so a lookup does not scan." And: "Revisits go where a visit buys the most freshness, which is neither evenly nor in proportion to the change rate."

Summary

Duplicates and staleness are the two costs of keeping copies. An exact hash finds only identical bytes, so near-duplicates use a 64-bit simhash of the main content, where every shingle votes on every bit: unrelated pages were 31.9 bits apart, one or two words of change moved a page 2.7 to 4.0 bits on average, and a template shared by 95% of two pages put 31% of different pairs within 3 bits. Neighbours within 3 bits are found by cutting the fingerprint into blocks and keeping a table for each choice of the blocks that must match, which returns exactly the full-scan answer while comparing about 13 of 200,000 fingerprints (four tables) or about 41 of eight billion (twenty tables of 32-bit keys, about 2 TB of memory). For revisits a copy is fresh for (1 - e^-x) / x of the time, a visit buys about one over the change rate in days, and so visiting evenly kept 73.6% fresh, visiting in proportion to change 9.9%, and marginal gain 77.4%, with the fastest pages skipped. A rate estimator that corrects for hidden changes recovered 2.00 changes a day where counting reported 0.86, and it saturates near 4.8 for daily visits, so fast pages need faster visits to measure.

Check yourself

Try answering out loud before you reveal each answer.

QuestionWhat does a threshold of 3 bits mean for a 64-bit simhash, and what can go wrong with it?Reveal answer

It means a few words differ out of hundreds: one word of 300 moved a page 2.7 bits on average and was within 3 bits 70% of the time, six words only 8%. Unrelated pages are about 32 bits apart, so the gap is wide. It goes wrong when the fingerprint includes the template (at 95% shared template, 31% of different pairs fell within 3 bits), with very short pages, and when the threshold is copied from a paper instead of chosen from labelled pairs.

QuestionHow do block tables find every fingerprint within 3 bits without a scan?Reveal answer

Cut the 64 bits into p blocks. Two fingerprints within 3 bits differ in at most 3 blocks, so at least p minus 3 blocks are identical. One table per choice of p minus 3 blocks, keyed by those blocks, therefore contains every near neighbour of the query under the same key, and only those candidates are checked bit by bit. With four blocks that is four tables of 16-bit keys. The test confirmed the answers equal a full scan's for 1,000 queries.

QuestionWhy is visiting pages in proportion to how often they change worse than visiting them all equally?Reveal answer

Proportional visiting gives every page the same ratio of changes to visits, so every page ends up equally stale, and it spends most of the budget on pages that are stale again within minutes: 95% of the visits went to the fastest 1,000 pages and the copy was 9.9% fresh. Equal visits kept 73.6% fresh. A visit buys about one over the change rate in days of freshness, which is why the best allocation (77.4%) gives the fastest pages nothing.

QuestionWhy does counting the changes you saw underestimate how fast a page changes, and where does the better estimate stop working?Reveal answer

A visit reports at most one change, however many happened since the last visit, so a page that changes twice a day shows a change at only 86% of daily visits. The estimator minus ln((unchanged + 0.5) / (visits + 0.5)) per interval recovers 2.00, but with 60 daily visits it cannot exceed ln(121) = 4.8, so it reported 4.4 for a page that changes five times a day and cannot tell that from fifty. Measuring fast pages takes faster visits.

Sources and further reading

  • Moses Charikar, Similarity Estimation Techniques from Rounding Algorithms, STOC 2002: where simhash comes from.
  • Gurmeet Singh Manku, Arvind Jain and Anish Das Sarma, Detecting Near-Duplicates for Web Crawling (opens in a new tab), WWW 2007: 64-bit simhash fingerprints with a threshold of 3 for eight billion pages, and the block tables.
  • Junghoo Cho and Hector Garcia-Molina, Synchronizing a Database to Improve Freshness, SIGMOD 2000: the freshness formula, and the result that visiting every page equally beats visiting in proportion to change.
  • Junghoo Cho and Hector Garcia-Molina, Effective Page Refresh Policies for Web Crawlers (ACM TODS, 2003) and Estimating Frequency of Change (ACM TOIT, 2003): the refresh policies and the change-rate estimators.
  • The Sitemaps protocol (opens in a new tab): lastmod, and the limits of 50,000 URLs and 50 MB for a file.
Lesson 11 of 11

That completes the track.

Track completeBack to Distributed systems

Send a message

It goes straight to my inbox. I usually reply within a few days.