One source broke and I did not notice until the next afternoon.
Not broken loudly. Broken emptily. The Bilibili job threw HTTP 412 on every call from the Apify cloud IP while the identical URL returned 200 from my laptop. Four runs, exit code 91 each time. Because every source sits in its own try/except — a decision I still defend — the sweep it belonged to finished, wrote everything else, and reported success.
Nothing in the ledger said "Bilibili is gone", because a source that dies and a source that returns nothing look identical from the outside.
That is the whole design problem, and it is not about HTTP.
What one sweep produced
One pass across six Chinese sources: 898 records, 783,094 bytes of JSON, 45 seconds wall clock. From the first Eastmoney row at 03:19:53 UTC to the last Amap POI at 03:20:38 UTC.
| Source | Records | Bytes | Finished at (UTC) |
|---|---|---|---|
| Eastmoney quotes | 800 | 703,468 | 03:19:57 |
| Xueqiu quotes | 5 | 5,770 | 03:20:00 |
| Bilibili search | 18 | 26,282 | 03:20:32 |
| Weibo hot board | 30 | 15,348 | 03:20:34 |
| Douyin hot board | 30 | 20,174 | 03:20:36 |
| Amap POIs | 15 | 12,052 | 03:20:38 |
Eastmoney is 90% of the bytes and under 4 seconds of work: 800 rows off one paginated endpoint. Bilibili's 18 records did not land until 03:20:32, about 32 seconds after the Xueqiu batch finished, because every record is a separate throttled request.
Your pipeline is not one job. It is six jobs with wildly different shapes, and squeezing them into one loop makes the slow one hold the fast one hostage.
The six jobs, isolated
import json import sqlite3 from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime, timezone DB = "china_market.db" def run_sweep(jobs, workers=6): """jobs = {"source_name": callable_returning_list_of_dicts}""" run_id = datetime.now(tz=timezone.utc).strftime("%Y%m%dT%H%M%SZ") results = {} with ThreadPoolExecutor(max_workers=workers) as pool: futures = {pool.submit(job): name for name, job in jobs.items()} for fut in as_completed(futures): name = futures[fut] try: rows = fut.result() or [] results[name] = {"ok": True, "n": len(rows), "rows": rows} except Exception as exc: # One dead source must not kill the sweep results[name] = {"ok": False, "n": 0, "error": f"{type(exc).__name__}: {exc}"} con = sqlite3.connect(DB) con.execute("""CREATE TABLE IF NOT EXISTS records ( run_id TEXT, source TEXT, key TEXT, payload TEXT, scraped_at TEXT, PRIMARY KEY (run_id, source, key))""") for name, res in results.items(): for row in res.get("rows", []): con.execute( "INSERT OR REPLACE INTO records VALUES (?,?,?,?,?)", (run_id, name, dedupe_key(name, row), json.dumps(row, ensure_ascii=False), row.get("scraped_at") or run_id), ) con.commit() con.close() return run_id, {k: (v["ok"], v["n"]) for k, v in results.items()} INSERT OR REPLACE on (run_id, source, key) gives idempotent reruns. Rerun the same second and you get the same rows, not duplicates. Run again an hour later and you get a new run_id, so history accumulates — which is what you want for anything time series.
The ok: False branch is the one that matters. It kept the sweep alive, and it also hid the outage, because I was returning status and never looking at it.
Every source needs its own dedupe key
This is the part that quietly ruins joins:
| Source | Key | Why |
|---|---|---|
| Eastmoney | code | unique per listed security |
| Xueqiu | symbol | SZ000001 ≠ SH000001 |
| Bilibili | bvid | aid also works, bvid is the stable one |
rank:word | rank gaps make rank alone unstable | |
| Douyin | rank:word | same |
| Amap | poi_id | 15/15 unique in my run |
def dedupe_key(source, row): if source == "eastmoney": return row["code"] if source == "xueqiu": return row["symbol"] if source == "bilibili": return row["bvid"] if source in ("weibo", "douyin"): return f"{row['rank']}:{row['word']}" if source == "amap": return row["poi_id"] return str(row) Two of those are defensive rather than obvious. Weibo skips paid slots, so rank 7 was missing in my run and rank alone is not a stable identity. And Amap returns two POIs with the same name in the same mall often enough that name-plus-coordinate is a worse key than the platform's own poi_id.
Null-rate alarms, with real thresholds
The most useful thing I added after the first week was a per-column null check that fails loudly, because these platforms never tell you when a field stops being populated.
Measured null rates from that sweep:
- Eastmoney
pe_dynamic: 239 of 800 negative, 0 null. Fine — those are loss-making companies. - Bilibili
cid: 18 of 18 null in search mode, populated in detail mode. Expected. - Weibo
category: 30 of 30 null. I deleted the column. - Amap
tel: 8 of 15 null. Expected — not every shop publishes a phone. - Amap
rating,cost: 15 of 15 null, and 5 of 5 null on a second city. Deleted both.
def null_report(rows, fields): n = len(rows) return {f: round(sum(1 for r in rows if r.get(f) is None) / n, 3) for f in fields if n} # a column that is null on everything is not a column, it is a bug report report = null_report(amap_rows, ["tel", "rating", "cost", "address"]) # {'tel': 0.533, 'rating': 1.0, 'cost': 1.0, 'address': 0.0} Run it every sweep and alert on change, not on absolute value. tel: 0.533 is normal. tel: 1.0 means the detail pass broke. That difference is invisible in a row count, and it is exactly the difference I missed for a day.
Schedule by cost, not by convenience
Three cadences fall out of the measurements:
- Eastmoney, every 5 minutes during market hours. 3.83 s, one endpoint. Cheap enough to poll hard while the market is open, pointless at 3am.
- Weibo and Douyin, every 5–10 minutes. 30 rows each, a few hundred KB a day. These boards move in both directions, so sampling is the only way to see velocity.
- Bilibili and Amap, daily or on demand. Slow per row, and the underlying objects change slowly. Bilibili is also the source that answers 412 when it thinks you are in a hurry — from a cloud IP, assume it will.
Do not put the daily job on the same timer as the 5-minute job and then wonder why your scheduler drifts. Six sources, three cadences, one ledger table.
What the ledger buys you
With run_id and per-source status stored, "did the pipeline run?" becomes a query instead of a guess:
SELECT run_id, source, COUNT(*) AS rows FROM records GROUP BY run_id, source ORDER BY run_id DESC LIMIT 12; If a source is missing from the latest run_id, it failed and the sweep continued — which is the behaviour you want. A pipeline that dies entirely because Amap returned an HTML shell instead of JSON is a pipeline that pages you at the worst possible moment.
One more deployment lesson that cost me a batch: six builds in parallel is 6 × 4,096 MB against a 16 GB free-plan ceiling, and the fifth and sixth came back 402 actor-memory-limit-exceeded. Serial fixed it. Parallelism is not free at the account level, only at the request level.
The six sources are packaged individually so you can subscribe to just the ones you need — Eastmoney, Xueqiu, Bilibili, Weibo, Douyin, Amap. Same record shapes as the tables above, so dedupe_key works unchanged.
Next step: run the sweep once with all six jobs stubbed to return a single fake row, and check that the ledger gets six rows under one run_id. Then swap in the real jobs one at a time. Debugging six live sources at once is how you end up not knowing which one lied to you.