EST. 2026 — Notes from real server work SYSADMIN · SECURITY · AI · DIRECTADMIN Issue 01
THE SYSADMIN ALMANAC
Home / Linux / From 80,000 Crawled URLs to Delta Sync with Stop Gates
Linux

From 80,000 Crawled URLs to Delta Sync with Stop Gates

by Ton-Or ·25 Nov 2026·12 min read
From 80,000 Crawled URLs to Delta Sync with Stop Gates

Before I let a sync job run unattended, it needs to answer three questions. Does it know when to stop and wait for a person? Can its caller tell why it stopped? And if I run it again with the same input, does it produce the same result down to the last byte?

1-minute summary

Symptom / problem
A full re-crawl each week to update a new site from the old one grew to about 80,000 URLs
Who should read
People who must sync content from an old site weekly and let it run unattended
Fix in short
Fetch only the delta, the known ids plus the next 400. A real run took 43 minutes, with stop gates for a human, four exit codes, and proof that a rerun matches byte for byte.
Jump to steps

I had migrated a client's old site to a new one, but while the old site was still running, the owner's team continued updating content there. I needed to pull those updates into the new site periodically. I tried crawling the entire site again, and the queue grew to around 80,000 URLs. I had to stop midway and redesign the whole process.

Let me be clear first: this entire network of sites belongs to the same business owner. The content is theirs, they requested the migration, and they are aware of every fetch run. This is not about collecting data from someone else's website. But even though the owner owns the sites, the old server still serves real customers, so requests need the same care. Throughout this article, I use old-a.example.com, old-b.example.com, and old-c.example.com in place of the domain names.

The first run found 226 items, and I thought that was everything

The old system runs on ASP.NET across 11 domains. All domains use the same CMS, with content pages in the form view.aspx?id=N. On the first run, I followed links from the home page like a normal crawler (I covered traversal and image selection in Migrating an entire legacy .aspx site into a JSON catalog) and found 226 items. That looked reasonable compared with the menus, so I concluded that I had everything.

That conclusion was wrong. Later, I tried stepping through id numbers directly instead of following links and found 2,663 items, nearly twelve times as many. All 11 domains share one central database and the same id sequence. A given id refers to the same content regardless of which domain serves it. Each item has what I call an owning site: the domain it belongs to. A domain's menus therefore show only a small part of the full database.

Following every link does not mean finding all the data

A crawler can only tell you which pages have links pointing to them, not what is in the database. If the system uses sequential numbers in its URLs, try walking those numbers once and comparing the results with the crawl. The gap between 226 and 2,663 is content that is still accessible but that no menu leads to.

A repeat full crawl ballooned to 80,000 URLs

When it was time to refresh, I reused the same approach: another full crawl. This time I did not limit browse pages, because I was worried about missing content as I had on the first run. It turned out that the system's browse pages allow multiple layers of filters, with each combination producing a new URL. The crawler's queue grew to around 80,000 URLs even though there were fewer than three thousand actual content items.

I stopped that run because the browse pages were just different views of the same items. Visiting them all would not find any additional content, while the old server would have to handle tens of thousands of requests that benefited nobody.

Abandoned

A full crawl every run

Follow links on every page. The queue grows with the number of filter combinations to around 80,000 URLs, with no clear end in sight, and content without incoming links still gets missed.

In use

Delta by id

Request each known id, plus the next 400 ids and a fixed list of pages. The request count is known in advance. The actual run finished in 43 minutes, followed by a comparison with the previous snapshot to find the differences.

Delta: known ids, plus the next 400, plus fixed pages

The idea behind the delta is much simpler than crawling: stop discovering and directly request only what I know exists.

  1. Fetch every id seen in the previous snapshot again, then compare its content fingerprint with the old one.
  2. Scan the next 400 ids after the highest known number to catch newly created items.
  3. Fetch fixed pages that do not use ids, such as the company and terms pages, from a predefined list.
  4. Each id has one of five outcomes: new, changed, unchanged, missing, or moved. Write these to the run's delta file.

The main fetcher looks roughly like this, with parsing removed to leave just the core.

# delta_refresh.py (ย่อ) — ถามเฉพาะ id ที่รู้จัก + สแกนต่ออีก N เลข
import hashlib, json, re, sys, time
from pathlib import Path
from urllib.parse import urlparse
import requests

BLOCK_CODES = {403, 429}

def fingerprint(html: str) -> str:
    """ลายนิ้วมือของเนื้อหา ตัดส่วนที่เปลี่ยนทุกคำขอออกก่อน"""
    body = re.sub(r'<input[^>]+__VIEWSTATE[^>]*>', '', html)
    body = re.sub(r'\s+', ' ', body)
    return hashlib.sha256(body.encode('utf-8')).hexdigest()

def run(host: str, known: dict[int, str], scan: int, delay: float, out: Path):
    s = requests.Session()
    s.headers['User-Agent'] = 'site-migration-sync (owner approved)'
    delta = {'new': [], 'changed': [], 'removed': [], 'moved': [], 'blocked': False}
    streak = 0
    last = max(known) if known else 0
    for i in list(sorted(known)) + list(range(last + 1, last + 1 + scan)):
        time.sleep(delay)
        r = s.get(f'https://{host}/view.aspx?id={i}', allow_redirects=False, timeout=30)
        if r.status_code in BLOCK_CODES:
            streak += 1
            if streak >= 3:                       # ต้นทางบอกให้หยุด ก็หยุด
                delta['blocked'] = True
                break
            time.sleep(30 * streak)
            continue
        streak = 0
        if r.status_code == 302:
            to = urlparse(r.headers.get('Location', '')).hostname
            if to and to != host:
                delta['moved'].append({'id': i, 'to': to})
            continue
        if r.status_code != 200 or is_blank(r.text):
            if i in known:
                delta['removed'].append(i)
            continue
        fp = fingerprint(r.text)
        if i not in known:
            delta['new'].append(i)
        elif known[i] != fp:
            delta['changed'].append(i)
        (out / f'view__id={i}.html').write_text(r.text, encoding='utf-8')
    (out / 'delta.json').write_text(json.dumps(delta, ensure_ascii=False, indent=1), encoding='utf-8')
    sys.exit(3 if delta['blocked'] else 0)

All adjustable settings live in one config file instead of being scattered as constants across several scripts. With them in one file, advancing the baseline to the latest run only requires editing this file.

{
  "hosts": {
    "a": "old-a.example.com",
    "b": "old-b.example.com",
    "c": "old-c.example.com"
  },
  "sync": { "root": "data/sync", "scan_new_ids": 400 },
  "polite": {
    "delay_page": 0.45,
    "delay_image_min": 0.8,
    "delay_image_max": 1.4,
    "image_pause_every": 200,
    "image_pause_s": 30,
    "block_codes": [403, 429],
    "block_stop_after": 3,
    "block_backoff_s": 30
  },
  "thresholds": {
    "removed_pct": 2.0,
    "removed_max": 30,
    "changed_pct": 10.0,
    "new_bad_max": 10,
    "new_min_body": 150,
    "published_drop_pct": 2.0
  }
}

Reading HTTP status correctly: moves, deletions, and truly missing images

An easy mistake is to assume that an item has been deleted whenever a request returns no content. This system has three cases that look similar but mean different things.

Source response Meaning Action on the new site Actual findings
The primary domain returns a 302 to a sibling domain The item has changed owners and still exists Change the owner; do not archive 46 items in one day
Every domain returns an empty page Deleted or unpublished Archive; do not delete 937 of 1,083 ids queried
The image file is 0 bytes long The image was deleted at the source Treat it as absent; do not retry the download 3 images

The first case is the most dangerous. If I had read a 302 as "missing," 46 items would have been taken off the new site that day, even though the team had only moved them to another domain. The fetcher therefore needs to request pages without following redirects and inspect Location itself. If the destination is a domain in the same network, record it as moved.

The 0-byte image case also needs the right interpretation. If the file checker treats it as a failed download, it will retry on every run without ever succeeding. In reality, the image has been deleted at the source; the download did not fail. That run found 3 such images.

Strip product codes before deduplicating

Finding 2,663 ids still did not give me the actual content count, because the same item had been posted on multiple domains. On the first attempt, I used the product code in the item name as the deduplication key, assuming that the same code meant the same item.

Wrong again. Sibling domains assign new codes to the same item. For example, AAA005 on one domain is the same item as BBB002 on another. The codes were making identical items look different, so I needed to strip them from the text before comparing.

import re
from difflib import SequenceMatcher

CODE = re.compile(r'\b[A-Z]{2,4}\d{3}\b')           # รูปแบบรหัสสินค้าของระบบเก่า

def norm(text: str) -> str:
    text = CODE.sub('', text)                        # ถอดรหัสออกก่อนเทียบ
    return re.sub(r'\s+', ' ', text).strip().lower()

def same_item(a: dict, b: dict, min_ratio: float = 0.87) -> bool:
    if a['zone'] != b['zone'] or a['duration'] != b['duration']:
        return False
    return SequenceMatcher(None, norm(a['body']), norm(b['body'])).ratio() >= min_ratio

That reduced 2,663 ids to 1,670 items. Pairs that a person has judged to be duplicates or distinct go into an overrides file that the categorize step reads on every run. How the new site accepts this data without overwriting manual edits is covered in Reimporting restores manually edited content to its old state.

Gates for human review and four exit codes

Once I had the delta, I wrapped every step in a single script. First, it crawls two domains in parallel. Parallel requests are allowed only across different domains; there are no concurrent streams to the same domain. It then crawls the third domain and continues sequentially.

crawldelta 3 domainsimagesnew images onlycombineall sourcescategorizeclassify, dedupeexportitems.jsonlreportvs. baseline403/429 3 in a rowstop now exit 3any step failsexit 1 then --resumeHuman review gatemissing over 2% or 30 · changed over 10%over 10 incomplete new itemsPASS exit 0STOP exit 2One folder per run; baseline untouchedstate.json · logs · report.html · report.jsonExit codes the caller must distinguishexit 0all checks passedexit 2check failed; reviewexit 1step failed; see logexit 3source refused; no retry
The six steps of a sync run, two stop gates, and four exit codes the scheduler uses to decide whether to continue or wait for a person
python tools/sync_all.py --dry            # ดูแผน ไม่เขียนไฟล์ ไม่ยิงคำขอ
python tools/sync_all.py                  # รอบเต็ม ดึงจริงราว 40 นาที
python tools/sync_all.py --skip-crawl     # ใช้ผลดึงรอบล่าสุด ราว 10 นาที
python tools/sync_all.py --resume         # ต่อจากขั้นที่ค้าง ขั้นที่ done แล้วข้าม
python tools/sync_report.py --compare data/sync/RUN_A data/sync/RUN_B

Each run has its own folder, containing state.json to track each step's status, logs for each step, report.html for people, and report.json for machines. No step overwrites the baseline, so a run that fails halfway does not leave partial results in the data the site is using.

What matters most to me is the criteria for stopping and waiting for a person. A script that finishes every time without ever rejecting anything will eventually bring bad data into the site. I set four criteria.

  • More than 2% or more than 30 items are missing.
  • More than 10% of content has changed. This signals that the source changed its template and the parser is reading it incorrectly, rather than the team suddenly editing the whole site at once.
  • More than 10 new items in total have no name or have content shorter than 150 characters.
  • A trial import reduces the published count by more than 2%.
# sync_report.py (ย่อ) — ตัดสิน PASS / STOP จากส่วนต่างกับฐานเดิม
def gate(diff: dict, th: dict) -> list[str]:
    stops = []
    base = max(diff['baseline_count'], 1)
    removed, changed = len(diff['removed']), len(diff['changed'])
    if removed > th['removed_max'] or removed * 100 / base > th['removed_pct']:
        stops.append(f'removed {removed} ({removed * 100 / base:.1f}%)')
    if changed * 100 / base > th['changed_pct']:
        stops.append(f'changed {changed} ({changed * 100 / base:.1f}%) - template ต้นทางเปลี่ยน?')
    bad_new = [i for i in diff['new'] if not i['title'] or len(i['body']) < th['new_min_body']]
    if len(bad_new) > th['new_bad_max']:
        stops.append(f'new items without title/body: {len(bad_new)}')
    return stops

stops = gate(diff, cfg['thresholds'])
print('PASS' if not stops else 'STOP: ' + '; '.join(stops))
raise SystemExit(2 if stops else 0)

There are four exit codes, and whatever calls the script must distinguish all four, because each requires a very different response.

exit Meaning What the caller should do
0 PASS All checks passed Proceed to the next step
2 STOP A check failed Send the report to a person; do not continue
1 A step failed Check that step's log, then --resume
3 The source returned 403/429 3 times in a row Stop and do not retry immediately
exit 3 must not trigger an automatic retry

Many schedulers retry whenever they see a nonzero exit code. If the source has just returned 403 or 429 three times in a row, an immediate retry means sending more requests to a server that just told you to stop. I gave this case its own code. When the caller sees 3, it must abandon that run and wait for someone to check what happened at the source.

Proving determinism: the second run must match byte for byte

The first actual run started at 20:48 and finished at 21:31, taking 43 minutes. The first domain was queried for 2,616 ids, plus a scan of 400 new ids and 73 fixed pages. The second domain had 1,825, plus 400 and 37 pages. The third had 990 ids. The result was 0 new, 0 changed, and 1 missing. The missing item was an empty draft with no name. The overall status was PASS, with no 403 or 429 responses throughout the run.

43 minutesFull run, 20:48 to 21:31
0.45 secDelay per request, per domain
2,663 -> 1,670Total ids versus deduplicated items
0 / 0 / 1New, changed, missing in the actual run
SAMESecond run compared with the first
49Differences from the baseline, all explained

A PASS result was not enough for me to trust the pipeline. The question I needed to answer first was whether the same input produces the same output. If it does not, every future reported difference will be impossible to attribute to either an actual source change or the script's own inconsistency.

To prove it, I ran a second time with --skip-crawl, using the same fetched data as the first run, then compared three output files: the report, items.jsonl, and media.json.

python tools/sync_all.py --skip-crawl
python tools/sync_report.py --compare data/sync/RUN_A data/sync/RUN_B
# SAME

# หรือเทียบเองด้วยมือ ต้องได้ hash เดียวกันทุกคู่
sha256sum data/sync/RUN_A/combined/import/items.jsonl data/sync/RUN_B/combined/import/items.jsonl
sha256sum data/sync/RUN_A/combined/import/media.json  data/sync/RUN_B/combined/import/media.json

The results matched byte for byte, and the comparison reported SAME. In principle, a pipeline like this needs to control three things: sort everything before writing rather than relying on directory file order, keep run timestamps out of output files, and write JSON in the same format every time. If any of these slips, the comparison will flag it on the second run.

Another check was against the baseline the site was currently using. The counts were 1,760 and 1,711, a difference of 49. I would not let that pass until I could explain every item. It broke down into 48 duplicate pairs added to the overrides file later, plus 1 item deleted at the source, accounting for exactly 49.

An unexplained difference is a bug without a name yet

A difference of 49 between two counts is not a problem if I can identify all 49 items individually. If I can explain only 47, the remaining 2 will come back as missing or duplicate content on the live site. My rule is that the comparison report must always reconcile completely first.

Courtesy to the source and a three-phase plan

The delay is 0.45 seconds per request per domain. Images use a random delay of 0.8 to 1.4 seconds, with a 30-second pause every 200 images. The image downloader backs off longer on 403, 429, or 503 and stops automatically after 5 consecutive occurrences. The initial download of the entire image library, 10,710 files totaling 2.0 GB, took around 3 hours without getting blocked. For rate limits and resuming interrupted work specifically, I wrote a separate article, Making over twenty thousand API calls with stop-and-resume support.

I set the frequency to once a week, which is enough. The first actual run found only one changed item in the delta. Fetching more often would only add load to the old server.

I divided unattended operation into three phases, and I am not skipping any.

Automation planPhase 1One script, run manually->Phase 2Scheduled, reports only for 4 weeks->Phase 3Then enable automatic imports

Phase two is for gathering evidence. I want to see reports for four consecutive weeks showing that the numbers make sense and the stop gates trigger when they should before letting it touch the database on its own. Each import still needs another round of follow-up work, because the source brings old material back every time: both wording the owner has already asked to change (Replacing wording across 217 database rows) and links that still point to the old site (159 legacy links embedded in content).

What makes this kind of sync trustworthy is not speed but three things: a request count known in advance, gates that stop when needed and explain why through exit codes, and proof that the same input produces byte-for-byte identical output. Thresholds such as 2% or 10% are specific to this job; sites that update more frequently can adjust them as needed. If I missed an explanation or made a typo, I will come back and fix it later.

Want us to set this up?

Get help with server setup, configuration, migration, or troubleshooting. Save time for the work that matters.

Get a quote

Hit something like this? Stuck somewhere?

Come trade notes on the LinuxThai board

→ Continue on the board

Comments 0

No comments yet — be the first