Workers KV as a tiny (pet) db
I found a way to replace my (very small) postgres db with Cloudflare's Workers KV
September 18, 2022 | 2 min. read
Since Heroku announced deprecating their free tier - I knew I had to get off their managed Postgres, which sucks. Itās worked well for me. Especially because I was using it with Hasura - almost zero-effort. I just type into a few fields and itād (Hasura) creates schema, index etc. and I can query without writing SQL. Nothing against sql. But why pass up auto-generated queries!
I had the goal of moving the entire site to Cloudflare pages. I went down this path and had to give it up when I found out (well, was reminded of) the fact that cloudflare workers (the equivalent of Netlify functions, which are like AWS lambdas, on Cloudflare) āruntimeā doesnāt implement all nodejs
apis. And I happen to be using web-push
package which wouldnāt run in a worker runtime. Oh well.
I decided to just remove the hasura/heroku-postgres part of the site instead.
So. I wrote up a ākv serviceā as a worker and use Workers KV (a key-value store) as the database.
I wouldnāt even have to do this if I could access Cloudflare KV from the (Netlify) functions I currently use. Regardless, this service (I called it kvstore
) was borderline trivial to write.
And then I just had to update the netlify functions to write/read from the KV store instead of hasura. It wasā¦ painless.
This is a sample call to set/create a key with:test
with value simple
POST / HTTP/1.1
Host: localhost:8787
Content-Type: application/json
Content-Length: 69
{
"op": "WRITE",
"key": "with:test",
"value": "simple"
}
One nice trick with using a key-value database is, with prefixes, you can essentially build different ātablesā from a single store. So the structure of the key can embed information about the schema.
For example,
A production table for number of words on a page (homepage
here) could look like:
prod:pages:wordcount:homepage
The namespacing helps with avoiding key-collision. And with prefix support when listing in workers KV.
Itās easy to sayā¦ list all keys for word count count in dev environment with something like
list(prefix='dev:pages:wordcount:')
Easy! Iāve migrated the logic for the push notification and ā¦ everything works as it always has.
And now I can rest easy again. Until cloudflare removes their free tier and I have to relocate again.
Until then.