top of page

Push, never pull: publishing from a LAN to the edge

4 minutes ago
13 min read

Every byte the app shows was pushed from a home network to Cloudflare through one door.

Here is the contract at that door, how we choose between KV, D1 and PlanetScale, and the

four ways publishing goes quietly wrong.


Between the local pipeline that computes everything and the Worker that serves everything,

there is a seam. Data has to cross from a private network, where the databases live, to

Cloudflare's edge, where the app reads it. How that crossing works decides most of what can go wrong in production, because the app never sees the local pipeline. It only sees what

made it across.


AIIM's rule for the seam is short:


Nothing local writes to Cloudflare storage directly. Every publish is an HTTPS POST to

a Worker internal route, and the Worker does the KV, D1 or PlanetScale write.


There is one exception, and it's a bootstrap: a few D1 producers can emit a SQL file

(`--sql-out`) for `wrangler d1 execute`, for loading an empty table the first time. Every

scheduled publish goes through the Worker.


This article covers why we chose that shape, what the contract at the door looks like, and

the lessons, most of them about data that was perfectly correct locally and wrong on the

phone.


Why push, and why publish through the Worker


There were three ways to get data from the LAN to the edge:


1. Let the edge pull. The Worker, or a scheduled Worker, calls into the LAN for fresh

data. That needs an inbound path into a home network: a tunnel, a VPN or an open port.

It also couples the app's availability to the home lab's uptime at request time.


2. Push straight into storage. Local scripts use Cloudflare's REST API to write KV and

D1 directly. That works, but it puts an account-scoped API token on every machine that

publishes, and each script has to know the storage layout.


3. Push through the Worker. Local scripts POST JSON to internal routes, authenticated

with a shared bearer token, and the Worker writes storage through its bindings.


We chose the third, and it pays off in several ways:


  • No inbound path to the LAN. Cloudflare never initiates a connection to the home

    network. If the home lab disappears, the edge carries on serving the last good data until

    the TTLs run out.


  • One credential with a narrow scope. The bearer token can call a handful of write

    routes. It can't delete a namespace, read billing or deploy code.


  • The Worker owns the storage layout. A publish says "this value, this key, this

    namespace". When we decided price history should also land in D1, we changed the Worker, not the scripts.


  • Some stores have no other door. PlanetScale is reached through Hyperdrive, which holds the database credentials. Nobody has the password, so there's no way for a Python script to connect directly even if we wanted it to. Every PlanetScale load goes through the Worker.


The cost is that the Worker becomes a write path as well as a read path, and every internal

route has to be authenticated correctly. [Article 10](draw-it-to-find-the-bugs) covers

how a full trace of the system checks that.


The Transport


Activity diagram for how the data moves

A flow either imports the publish script and calls its `main()`, or runs it as a subprocess.

The script reads whatever it needs locally, shapes a JSON payload, and POSTs it. Most publishes go to one generic route; anything relational has its own route, with its own validation and batching.


The Generic Sync Contract


The workhorse is `/api/internal/sync`. Its body has four fields:

Field

Meaning

key

The KV key, which is the read path itself, e.g. `/api/analytics/scanner-results`

value

Any JSON; stored as a string

binding

Which of the seven KV namespaces to write; (required)

ttl

Seconds until expiry. Default 604,800 (7 days). 0 means never expire


A few details in the handler matter more than they look:


  • The key is the URL. A publish to `/api/analytics/world-map` is read back by

    `GET /api/analytics/world-map`. There's no mapping table to keep in sync. The cost is that renaming a route means re-publishing under the new key.

  • `binding` has no default.** Leaving it out is a 400, not a write to some default

    namespace. Every producer has to say where its key lives, which matters because the read path checks one namespace first (more in [Article 7](one-worker-in-front)).


  • Values over 25 MB are refused with a 413, which matches KV's value limit. The error

    is explicit, so the script logs a size, not a vague failure.


  • The 7-day default TTL is a deliberate choice. A week covers a full week of job

    failures, so a broken producer shows up as stale data long before it shows up as a blank

    screen. Producers that know their own cadence set something shorter; a few long-lived

    reference payloads set `0`.


`ttl: 0` deserves caution. A key that never expires never tells you its producer has died.

It also never washes out a bad write: one incident (below) came from a failed payload

published at `ttl: 0`.


Price history: one write, two stores


Chart data is the one place where a single publish lands in two stores. When the binding is

`DEV_PRICES` and the key starts with `/api/analytics/price-history/`, the Worker:


1. Writes the whole payload to KV, as for any other key;

2. Upserts the company name into D1 `symbol_names` (its own try/catch, so a name failure

can't lose the bars);

3. Upserts every bar into D1 `price_history`, in batches of 50 statements;

4. Deletes that symbol's rows older than 730 days, which keeps the table at about two years

per symbol.


KV is what the app reads first. D1 is the durable copy: it backs the fallback when a KV key

has expired, it serves the portfolio valuation endpoint (which needs closes for many symbols

in one query), and it holds company names for the screens that need them.


The scheduled producer pushes 260 bars per symbol, roughly one trading year. That's the

minimum the app needs to compute a 200-day moving average and a MACD signal line on the device. A comment in the script warns against lowering it: KV holds exactly what's pushed, so a shallower push silently blanks those indicators.


The mirror has a cost we keep an eye on. The upsert has no "unchanged row" guard, so every push rewrites every bar, at about two D1 row writes per bar once the index is counted. The script notes that a top-up of 100 symbols per run costs about 52,000 writes. D1 writes are

the budgeted resource on our plan (50 million rows a month included, then $1 per million),

so the number of symbols per run, and how often they're re-pushed, is a cost decision.

Sending only bars newer than the last sync, or guarding the upsert so unchanged rows aren't

rewritten, would cut that sharply.


The same producer also shows how the two stores protect each other. It writes KV with a

48-hour TTL, chosen to "survive gaps between twice-daily runs Mon–Fri". But from Friday's

17:00 run to Monday's 10:00 run is 65 hours, so every weekend those KV keys expire on Sunday afternoon. Nobody notices, because the read path falls back to D1 `price_history` on a KV miss, which still has every bar. The mirror turns a TTL mistake into a non-event. It's still

a mistake, and it's another case of the rule from [Article 2](43 cron-jobs-one-process):

a TTL has to outlast the longest gap in the schedule, weekends included.


Choosing a Store

Every new dataset gets the same question: KV, D1 or PlanetScale?


flow diagram of choosing a destination to write

KV is the default for anything the app reads as a whole: the scanner results, the world map, the economics payload for a country, the ML dashboard. Reads cost almost nothing, writes don't count against the D1 budget, and replacing the whole value is atomic from the reader's point of view. The limits are size (25 MB per value) and shape: KV can't filter, so anything

the app needs a slice of has to be pre-sliced into separate keys `etf/holdings/{SYMBOL}`,

`sector-companies?sector=...`).


D1 is for data that's genuinely relational or accumulates over time: seven nights of

scanner history, model performance history, company profiles and their links to signals, price history, the P/E history. The budget numbers drive the design. On Workers Paid, reads are about a thousand times cheaper than writes ($0.001 versus $1.00 per million beyond the included amounts). So D1 producers upsert deltas, never truncate and reload, and batch their writes. A D1 database is also single-threaded: a flood of concurrent writes queues and then returns "overloaded", so bulk deletes are chunked to about a thousand rows.


PlanetScale is for wide relational tables that would burn the D1 write budget on every

refresh: quarterly fundamentals for the whole universe, a trailing-twelve-month view over

them, and fund constituents. Hyperdrive pools the connections and caches queries for 120

seconds, so the Worker can query Postgres per request without a connection storm.


Who Writes What

Each row below is a Prefect flow, and each column a Cloudflare destination. ● means the flow writes there on every run.

Flow

DEV_PRICES

DEV_MACRO

DEV_ECON

DEV_FUND_HOLDINGS

ML_MODEL_MEASURES

D1

PlanetScale


economics sync (hourly 08–18)

●

●

●

●


company profiles

listings


market data sync (10:00, 17:00)

●





pe_history

company links


nightly app sync (01:00)

●

●


●

●

History

model history


analytics KV sync (21:30)


●



●

model history



market scan (21:00)

●





scanner history



ML insights (19:00)





●




ETF fund holdings (11:30, 18:30)




●





portfolio performance / rebalance


●







portfolio universe + closes (18:40)



●



price history

tracled symbols


muni risk full publish (4-hourly)





●




market pulse (every 30 min)



●






Two things stand out. The economics sync, which sounds like one job, writes to five

destinations, because it's become the hourly "refresh everything cheap" flow. And several

flows write to the same namespace, which is fine, until two of them write the same key.


Trap 1: many writers, one key

KV has no owners. Any authenticated publish can overwrite any key, and the last write wins.

When two producers write the same key, the app shows whichever ran most recently, and

neither producer has any idea.


activity diagram of one key

We've had this happen to at least three keys.


World P/E ratios had three producers writing three different envelopes:

`{"results": [...]}` for 28 countries, `{"ratios": [...]}` for 72, and a raw `{"data": [...]}`

copy. The client only reads `results[]`, so whenever either of the other two had written

last, the panel was empty. The fix was to make one script the sole owner of the key; the

others stopped writing it (one keeps its D1 history append, which has no competitor). That

script also turned out to emit the string `"N/A"` where the client expects a number or null,

and the panel called `.toFixed(2)` on it and crashed. Producers now emit numbers or null,

never placeholder strings, and `ytd_change` is null rather than 0 when there's no index to

measure, because 0 renders as a real "flat" reading.


Scanner results is written by more than one producer: the nightly scan publishes its own

results, and other syncs republish copies they read from Redis. Some of them wrap the payload twice and some don't, which is why the Worker reshapes `scanner-results` on the way out. If the scanner looks stale after a successful 21:00 run, the first question is who wrote the key after the scan did.


Sector analysis was the worst case. The analytics KV sync called a local gateway, got an

`ok: false` error body, logged it, and published it anyway, inside its own `ok: true`

envelope, at `ttl: 0`. That poisoned the key indefinitely, on top of the good data another

script had written. Two fixes: the sync now refuses to publish a failed payload, and

sector analysis was removed from its list entirely, because the key belongs to a different

script whose version is actually correct.


The rule that came out of this: every KV key has exactly one producer, and the producer

is named in the key catalogue. A repo check (`npm run infra:check`) lists keys sitting in a

namespace other than the one the read path looks in first. Duplicate producers are still

found by reading the code, which is one reason the lineage diagrams exist.


Trap 2: TTLs that don't match the schedule

TTL is the only freshness signal KV gives you, so it has to agree with the producer's

schedule, and it often didn't:


  • The economics sync runs hourly on **weekdays**. Its keys were written with a 24-hour TTL, so every weekend the economics screens went blank on Saturday evening and came back on Monday morning. The fix was a TTL longer than the 62-hour weekend gap.


  • The price history TTL described above expires every weekend too, and is rescued by D1.


  • A nightly flow that was silently skipping (see the zombie-run story in

    [Article 2](43-cron-jobs-one-process)) was hidden for three days by a 3-day TTL, then

    revealed as two blank screens.


A TTL shorter than the schedule's longest gap causes outages on a timetable. A TTL much

longer than that, or zero, hides a dead producer behind stale data. The 7-day default sits at

the long end on purpose. The next piece of work queued for the app is a shared "as of" stamp on every panel, so stale data is visible to the user rather than silent.


Trap 3: producers that never run, or run too early

A publish script that isn't scheduled produces nothing, and nothing complains. The app just

shows whatever was written last time someone ran it by hand.


The bond risk screen was the clearest case. Its payload, `bond-risk-full`, was published only

from the **monthly** muni flow, while ratings were written daily. When someone noticed, the app was 217 bonds behind the database (2,089 published, 2,306 local). Moving the publish into a daily flow looked like the obvious fix, and it would have been wrong:


activity diagram of trap 3

The daily flow doesn't write the table. It queues a job for the aggregation agent, which

rewrote the table about two hours later. Publishing at the end of the daily flow would have

shipped yesterday's rows with today's timestamp.


The fix was a separate publish every four hours with a fingerprint skip. The script

computes `"{row count}:{max updated_at}"` over the source rows, reads the fingerprint stored in the live payload's `meta`, and skips the POST if they match (`--force` overrides). A

4-hourly schedule then costs one KV write per actual change, and the publish no longer needs to know when the agent finished.


The trace also turned up scripts that aren't scheduled anywhere. A D1 muni table has a

producer nobody runs, so it's empty; the KV payload serves the same data. A sentiment summary is only read by the PWA. A schema publish writes a namespace no route serves. Each is harmless on its own, but each is a trap for the next person who finds the table and assumes it's live.


Trap 4: the source expires before the publish runs

Sometimes the publish is correct and its input has vanished. The world P/E publish reads a

Redis key written by the aggregation agent with no TTL, deliberately persistent. But a

cache-maintenance job force-expires any key in that prefix with no TTL after 24 hours, and

another service rewrites the same key with a 30-minute TTL. So the source key dies daily, or

half-hourly, and the publish then degrades quietly: one script publishes only its 28

world-map countries, the other logs "Aggregated 0 countries", and both exit successfully.


The general lesson is that "the publish succeeded" says nothing about whether its input was

complete. Producers that can detect a thin input (a row count far below yesterday's) should

refuse to publish rather than overwrite a good payload with a partial one.


PlanetScale through the Worker

planetscale through the worker

Because no one holds the PlanetScale password, every operation goes through internal Worker routes: schema migrations, health checks, and the loads themselves. The weekly fundamentals flow fetches from FMP locally and POSTs batches to the Worker. The fund-constituents refresh works differently: the flow asks the Worker to refresh a list of funds, and the Worker calls FMP itself, using its own key, and writes the result.


The read side refreshes itself too. When the app asks for an index's holdings and the

stored constituents are about a week old, the Worker refetches them from FMP while serving the request. That makes the weekly job a warm-up rather than a dependency.


The trade-off is testing. With no direct connection, the only way to check a migration or a

loader is to deploy the Worker and call it. It's slower to iterate on, but there's exactly one

code path to production data, and it's the one that's tested.


D1 producers that diff before they write

The D1 producers that run often are built around the write budget. The company profile sync

(`scripts/sync_company_profiles_d1.py`) runs inside the hourly economics flow, but profiles

rarely change. Two mechanisms keep it cheap:


  • A content hash per profile. The script hashes everything the app renders for a company and sends it with the row. The Worker's upsert is `ON CONFLICT(company_key) DO UPDATE ... WHERE excluded.content_hash <> company_profile.content_hash`, so an unchanged profile costs a read, not a write. `updated_at` is excluded from the hash by construction: it's set by the database, and including it would make every row look changed every run, which is exactly the write the hash exists to avoid.


  • A manifest diff for listings. Before pushing listing rows, the script fetches a

    manifest from the Worker with a fingerprint per row, and sends only rows whose fingerprint differs. The fingerprint must be byte-identical on both sides: SQLite renders an integer flag as `"0"`/`"1"` where Python would render a bool as `"False"`/`"True"`, and absent values have to be `""` on both sides to mirror `COALESCE`. A one-character mismatch makes every row look changed, and the delta path quietly degrades to a full push.


The first run wrote about 10,300 profiles and 14,000 listing rows. Steady-state runs write a

handful.


The same script is a good example of refusing thin input. Its pool of companies comes from

the KV payload published just before it in the same flow, and if that reads back empty, the

script writes nothing rather than overwrite 10,300 good profiles because the network blipped.


Company profiles are keyed by a normalised company name, not a ticker, so one profile can sit behind several listings. The links between companies, signals and insights are rebuilt from

the KV payloads (scanner, valuation, news) that were just published, which keeps D1

consistent with what the app is already showing.


A sync that's paused on purpose

The network sync, which publishes the fund-holdings graph derived from Neo4j, is paused while the graph is rebuilt from the re-ingested N-PORT data. Pausing a publish is safer than

letting it run against a half-built graph, but it has a visible cost: the graph namespace is

empty and the D1 network tables hold the last good sync. The diagrams mark it as paused so nobody "fixes" it by turning it back on before the rebuild finishes.


Debugging a stale or blank panel

1. Read the key. What's in it, what does `meta` or `updated_at` say, and which namespace

is it in?


2. Find every producer of that key. If there's more than one, assume a race until proven

otherwise.


3. Check the producer's last run and whether it published. "Completed" isn't "published":

look for the POST and its response.


4. Check its inputs. Was the Redis key or table it reads complete at the time it ran?


5. Compare the TTL with the schedule, including weekends and holidays.



Takeaways

  • Push from the private network, through your own edge code, with one narrowly scoped credential. Never let the edge reach in.


  • Make the storage key the read path. Fewer mapping layers means fewer places to drift.


  • Default to KV, reserve D1 for relational and deltas, and move wide bulk tables to

    Postgres before they eat the write budget.


  • One producer per key, written down and checked by a script.


  • TTLs must outlast the longest schedule gap. `ttl: 0` hides dead producers and preserves bad writes.


  • Publish when the data is ready, not when the job that requested it finishes. A fingerprint

    skip makes frequent publishing cheap.


  • A successful publish of incomplete input is worse than a failed publish. Refuse to

    overwrite good data with thin data.

bottom of page