Anyone else regret going all in on JSONB?

patrick_jones88

New Member
Messages
60
Reaction score
0
Location
Glasgow, UK

So about two years ago we started stuffing all our event payloads into a single jsonb column on Postgres. Felt amazing at the time. No migrations, no schema fights, ship whatever the client sends. I was the one pushing for it too, so this is on me.

Fast forward to now and the table is around 40M rows. Queries that used to be instant are taking 4 to 8 seconds because people keep filtering on nested keys and the GIN index has ballooned to something absurd. Half our analytics dashboards hit that column with ->> and @> operators and the planner just kind of shrugs at all of it.

The part that's really biting us is constraints. We have three different services writing into this thing and nobody agrees on whether a field is called userId, user_id or uid. So now we have application-level validation in four places and it drifts constantly. Found out last week that one service has been writing timestamps as strings for six months. Six months. Nobody noticed because nothing enforces anything.

I've started pulling the hot fields out into real columns with generated columns and a partial index, which works but it's tedious. And the backfill on 40M rows is not something I want to do during business hours, so it's been sitting in a ticket for three weeks.

I'm not saying JSONB is bad, it saved us a ton of time early on. But there's a point where the flexibility turns into a liability and I think we blew past it a year ago.

How do you all decide when a field graduates out of JSONB into a proper column? Do you set a rule up front or just wait until something breaks?

rk_designs

New Member
Messages
68
Reaction score
0
Location
Vancouver, BC

the string timestamp thing made me physically wince. we had a crypto processor send epoch millis as a quoted string for like 8 months and the only reason anyone caught it was a reconciliation report showing every deposit landing in 1970. that was a fun week of explaining to finance.

to your actual question, i don't think there's a rule you can set up front that survives contact with a product team. what i do now is dumb and mechanical. if a key shows up in a WHERE clause or a JOIN more than twice in a sprint, it graduates. no meeting, no design doc, it just gets a column. if it only ever gets pulled out as part of the whole blob for display, it stays in jsonb forever and i don't feel bad about it. the deciding factor isn't schema purity, it's whether the planner ever needs to look inside the thing.

but honestly the jsonb isn't your real problem. three services writing the same column with three different names for the same field is going to bite you exactly the same way once those fields are real columns, you'll just be doing it with migrations and a deploy window instead of a text search. you need a contract at the boundary. one writer service, or a validation schema both writers have to pass, or you're just relocating the drift.

for the backfill, don't do it in one shot. add the generated column, dual write from the app, backfill in batches by id range with a small sleep, and keep a trigger or a partial index covering both shapes until you cut over. and check the fastupdate setting on that GIN before you spend a weekend on REINDEX CONCURRENTLY, sometimes it's just the pending list being fat.

how many of those dashboards actually filter on the nested keys? i'd bet it's two, and the other six just select the whole thing and render it.

danielp77

New Member
Messages
51
Reaction score
0
Location
Melbourne, AU

the "twice in a sprint" rule is clean in theory but I've watched it go wrong. we ended up with like 30 columns on a table that only ever got filtered by 6 of them, because someone had a one-off report and the key showed up in a WHERE twice that week. now every write touches 30 columns whether it needs to or not and the row size is stupid. so I'd add one qualifier: twice in a sprint AND it's still being filtered six weeks later. the report keys rot, the real hot ones never go away.

but yeah, the contract thing. that's the actual wound. we tried the "one writer service" thing and it fell apart the second a second team needed to write the same aggregate, so what we landed on instead was a versioned schema doc that both writers validate against in CI. not perfect. it's basically JSON Schema checked at build time plus a canary row written on every deploy that gets asserted on the read side. if a service starts sending uid the canary fails and the deploy dies before it reaches prod. ugly but it caught a string timestamp in staging last month instead of six months later.

curious what rk_designs means by "a validation schema both writer." the sentence cut off. if you've got a specific shape for that I want to steal it.

rk_designs

New Member
Messages
68
Reaction score
0
Location
Vancouver, BC

yeah the 30 column thing is fair, i've eaten that too. my version was a table where like half the columns were only ever non-null for one enterprise client and everyone else wrote NULL into them, so the row header was fat for no reason and every write paid for it. your six week qualifier is basically the missing half of my rule, i'm stealing it.

and yeah the sentence cut off, i was typing on a phone with one hand while waiting on a deploy, my bad. what i meant was a validation schema that both writers import as a shared dependency instead of each team hand rolling their own checks. one repo, one schema file, both services pull it in and validate on the way out the door. the contract lives in code, not in a confluence page nobody opens. we did the wiki thing first and it rotted in about three weeks because nobody updates docs when they're shipping.

the canary row idea is genuinely good though. ugly, but good ugly. how do you handle the read side assertions when the aggregate is only written once a day by a batch job? we've got one of those and i can't tell if the canary would just sit there stale for 23 hours or if you seed a fake row on deploy anyway.

tommy2k

New Member
Messages
69
Reaction score
0
Location
Mexico City, MX

the six week qualifier is nice in theory but in my experience the "hot" keys aren't hot for six weeks. they're hot for two weeks around a launch, someone builds a dashboard off them, then it goes cold forever and you're left holding a column. we had a campaign_id that got filtered on constantly for a month, I promoted it to a real column with an index, and I'd bet it's been read like four times since.

what actually worked for us was giving up on the graduation rule entirely and flipping the whole thing. the jsonb table stopped being a queryable table. it's an append-only log now, nothing filters on it, nobody joins it. everything that needs querying gets projected into a narrow read table with real types and real constraints, and that projection is the only thing dashboards touch. writers dump whatever garbage they want into the log, we own the shape on the way out.

side effect is the contract problem shrinks a lot. you don't have to get three teams to agree on userId vs user_id vs uid at write time, you only have to agree at projection time, and there's exactly one place doing the projection. the projector maps all three names down to one column. you still maintain a projector and there's lag on the read side, so it's not free, but it stopped the bleeding for us.

the epoch millis as a quoted string thing made me laugh though. we had a service send booleans as "true"/"false" strings for close to a year and the only reason it surfaced was a BI tool choking on a filter. nobody downstream ever caught it because everything was just doing truthy checks on a string.

ahmed_khan92

New Member
Messages
63
Reaction score
0
Location
Toronto, ON

tommy2k the campaign_id thing is painfully real. we promoted a promo_code column off a two week spike and I checked last quarter, it's been read like 11 times since. the index maintenance on it costs more than the queries ever saved.

where I'd push back on the log plus projection setup is that the projector isn't free, it's a second system you now own and it drifts in the exact same way the jsonb did, just one layer down. ours started as a clean mapping and within a year had case-when ladders for 9 legacy field names and a comment that said "ask priya about the 2019 format". priya left.

and now every new field needs a projector change plus a backfill, so the thing that made jsonb nice in the first place (ship a field without asking anyone) is gone. might be the right trade, I just don't think it's as clean as it sounds on a slide.

what latency are you eating on the projection? ours was a batch job so the dashboards were 15 min stale and product complained until we basically rebuilt the thing.

@rk_designs the shared schema repo thing, does it live in the same monorepo as the writers or is it published as a package? we tried a shared validation lib and got into version pinning hell where one service was on v2 and the other on v5 and the schemas disagreed

You must log in or register to reply here.