Government open-data portals publish a lot of useful business data: contractor licenses, insurance filings, liquor license applications. What they don't publish is what changed since yesterday. A Socrata dataset is a current-state table. If a roofing contractor's general liability policy moves to a new agency, the row just changes. The old value is gone.
CountySignals exists to keep that history and turn the changes into dated events. This post covers how the pipeline works: one Cloudflare Worker, D1 for state, R2 for raw snapshots, Queues and Workflows for the work, and a pure diff function in the middle.
The sources
Seven Socrata (SODA 2.1) datasets, read every day:
| Adapter | Portal | What it gives us |
|---|---|---|
wa-li-general | data.wa.gov | Washington contractor licenses |
wa-li-insurance | data.wa.gov | the general liability policy on file: carrier, agency, expiration |
wa-li-principals | data.wa.gov | owners and officers |
wa-lcb-pending | data.wa.gov | pending liquor license applications |
ny-sla-pending | data.ny.gov | New York pending liquor licenses |
nyc-dcwp-hic | data.cityofnewyork.us | NYC home-improvement contractors |
chi-licenses | data.cityofchicago.org | City of Chicago business license applications |
Each adapter declares a query window (for example "policies expiring in the next 60 days, plus policies created in the run window") rather than pulling the whole table. That keeps a daily run to thousands of rows, not millions.
One Worker, and a cron that does almost nothing
Everything runs in a single Worker: the TanStack Start app, four queue consumers, three Workflows and a five-minute cron. The cron is the part I was most careful with. It reads D1, finds sources that are due, and sends one message per source to the ingest queue. That's all.
To keep it that way, every outbound client (Socrata, the crawler, the AI gateway, email, webhooks) calls a guard first:
export function forbidInScheduled(what: OutboundKind): void { if (!inScheduled()) return; console.error(JSON.stringify({ event: "scheduled.forbidden_call", what })); throw new Error(`scheduled.forbidden_call: ${what}`); } The cron body runs inside an AsyncLocalStorage store, so inScheduled() is true only for that call stack. Concurrent requests in the same isolate are unaffected. If someone later adds a "quick fetch" inside the cron, it fails loudly in the first test run instead of quietly eating the cron's CPU budget.
Ingest: snapshot first, then decide whether to trust it
The IngestWorkflow handles one source per step:
Socrata fetch → sanitize → gzip snapshot to R2 → stale-data guard → normalize → D1 upsert → diff → signal_events A few decisions worth calling out:
Raw snapshots go to R2 before anything else. Each run writes raw/<source>/<day>/<run>.json.gz. If the normalizer has a bug, I can replay any day without asking the portal again. Sanitizing happens before the snapshot: the Washington liquor dataset includes applicants' birth dates, and those are stripped so they are never stored anywhere.
The Socrata client is boring on purpose. $limit/$offset pagination over a stable $order, a 250 ms pause between pages, bounded retries on 429 and 5xx, and an injected fetch so unit tests never touch the network.
A stale-data guard decides whether a run counts. Open-data portals fail in quiet ways: a dataset returns zero rows for a day, or a column gets renamed. Diffing against a broken snapshot would produce a flood of fake "status changed" events. So every run is checked before it's used:
if (previousSchemaHash && fetched > 0 && previousSchemaHash !== schemaHash) { return { status: "anomaly", reason: `schema_changed:${previousSchemaHash}->${schemaHash}`, median: med }; } if (med !== null && med > 0 && fetched === 0) return { status: "anomaly", reason: "zero_rows", median: med }; if (med !== null && recent.length >= 2 && med > 0) { const deviation = Math.abs(fetched - med) / med; if (deviation > DEVIATION_LIMIT) return { status: "anomaly", reason: `count_deviation:${Math.round(deviation * 100)}%`, median: med }; } The schema hash covers the field names the portal declares. The row count is compared with the median of the last four good runs, and a deviation over 35% marks the run as an anomaly. Anomalous runs are stored and flagged, but they don't feed the diff.
The diff is a pure function
Change Radar (src/lib/pipeline/diff.ts) takes one normalized record plus the license state D1 held before this run, and returns a list of events. No I/O. That makes it easy to test with fixtures, including all the awkward cases (a policy renewed on the same day it expired, a carrier name spelled two ways).
Event types:
-
new_license(issued in the last 14 days) -
pre_opening_filing(a liquor or food license application) -
gl_expiring_60d,gl_expiring_30d,gl_expiring_15d -
agency_change,carrier_change -
status_change,license_renewal_60d
Names from government data are inconsistent, so comparisons normalize first: lowercase, strip everything that isn't a letter or digit. "Ohio Cas. Ins. Co" and "OHIO CAS INS CO" are the same carrier.
The X-date buckets are a small function:
export function glBucket(daysLeft: number) { if (daysLeft < 0 || daysLeft > GL_WINDOW_DAYS) return null; if (daysLeft <= 15) return "gl_expiring_15d"; if (daysLeft <= 30) return "gl_expiring_30d"; return "gl_expiring_60d"; } Idempotency through the event key
Workflows retry steps, and I sometimes re-run a day on purpose. Re-running must never emit the same event twice, but a new fact about the same license must emit.
Each event carries keyParts built from the triggering fact: the license, the event type, and the value that changed (the new agency, the new status, the X-date bucket and the policy number). They're joined into event_key, which is UNIQUE in D1, and events are written with INSERT OR IGNORE. A policy moving from the 30-day bucket to the 15-day bucket is a new key, so it emits. The same policy seen again tomorrow in the same bucket is the same key, so it doesn't.
There's one special case on a source's first run, when there is no stored state yet: an agency or carrier switch seen between a contractor's two latest policies counts only if the new policy is at most 45 days old. Otherwise the first backfill would announce years of old switches as news.
Dedupe
The same business shows up in several datasets. Washington L&I and the liquor board both carry the state UBI number, so the key is <hub>:id:<UBI> when one exists, and <hub>:nz:<name without legal suffix>:<zip or city> when it doesn't. Chains and shell entities are flagged and kept for statistics, but left out of feeds.
Delivery
Events land in signal_events, and the rest of the product reads from there: the web feed, CSV export, saved-search alerts, signed webhooks (one lead per POST, because most CRMs create one contact per call), a REST API, and an MCP server at https://countysignals.com/mcp with three tools that need no token. All sending happens in queue consumers. The cron only enqueues a tick.
What I'd tell someone building something similar
- Store the raw snapshot before you parse it. Replays get much cheaper.
- Don't diff against a run you haven't checked. A schema hash and a median row count catch most portal failures.
- Keep the diff pure and make the event key describe the fact that triggered it. Retries stop being scary.
- Treat the cron as a scheduler, not a worker, and enforce it in code.
The full description of sources, windows and event rules is on the methodology page. If you work with Socrata data and handle schema drift differently, I'd like to hear how.
