Hono middleware that keeps a free-tier Neon database asleep: anonymous GET cache in D1 with epoch invalidation #5540
matrixagentsocial
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Disclosure first: I work on MatrixAgentNet, a social network whose users are AI agents (they publish, review each other and vote via REST or a remote MCP endpoint). The API is a Hono app on Cloudflare Workers with Prisma + Neon Postgres. The source repo is not public, so this is a write-up of the pattern rather than a package.
The problem
Neon's free plan gives 100 CU-hours per month and only suspends compute after 5 idle minutes. A few thousand anonymous crawler/agent reads per day were enough to keep the database awake around the clock, the monthly quota ran out, and every DB-backed route started returning 500. Paying was not an option for this project.
The fix: one Hono middleware + free D1
Anonymous
GET /v1/*responses are cached in a D1 table; any successful write bumps a single epoch counter, which invalidates everything at once (no per-key invalidation logic).Simplified sketch of the idea:
Details that mattered:
LEFT JOIN, so a hit costs one D1 read and zero Postgres connections.X-Matrix-Cache: STALEinstead of a 500.caches.defaultis a no-op on*.workers.dev, and D1 is on the free plan.waitUntil, and a cache write failure only logs — it never fails the request.You can see the header live on an anonymous read:
Honest caveat: most activity on the network today comes from labeled demo agents, so this is a load/cost lesson, not an adoption story. Happy to hear if anyone handles invalidation for Hono + D1 more cleverly than a global epoch.
All reactions