
Postgres JSONB: When It Helps and When It Hurts
Everybody has some opinion about jsonb and we also had one, but without numbers, so on the laptop with Postgres 18 we generated one million of fake webhook events and stuffed each into a jsonb column, there is id, status, amount, and country which sits three levels down.
CREATE TABLE webhook_events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
provider text NOT NULL,
event_type text NOT NULL,
received_at timestamptz NOT NULL DEFAULT now(),
payload jsonb NOT NULL
);
Table became 159 MB, then GIN with jsonb_path_ops took 59 MB and the normal GIN 81 MB, ok the path one is smaller, but ask it does this key exist and it can't help you, it knows containment and paths only.
After that we were looking for one event by its id, with @> it is 0.061 ms, nothing to say, but we would normally write payload ->> 'id' equals something, and this one gives 28 ms with the whole table scanned by two workers, so the GIN what we built is useless for this question, ok, we gave it own index on exactly this expression and it dropped to 0.019, and then the part where we did not believe our eyes, we changed ->> to #>> '{id}', the answer is the same text, and 25 ms is back, because for Postgres it is another expression and it does not care that for us it is same.
CREATE INDEX CONCURRENTLY webhook_payload_gin
ON webhook_events USING gin (payload jsonb_path_ops);
CREATE INDEX CONCURRENTLY webhook_external_id
ON webhook_events ((payload ->> 'id'));
Funny thing is in the rows estimate, it was expecting 5000 rows, and came one, in other query came 2000, so what is inside of your document the planner is just guessing, we would be careful when you join something on it.
And then we broke it with one row, we changed one amount to text N/A, it saved it with no complain at all, and the sum of amounts after this is dying with invalid input syntax for type numeric, one bad row from million and the whole report is dead, a normal numeric column would refuse this at insert.
Next one hurts more. We made a single document around 200 kB with a views field inside, did jsonb_set from 0 to 1, so one digit changed, and looked how much WAL it wrote: 228 kB. For one view! Every time the whole document is written new.
Last thing, the merge with two pipes. In settings we had ui with theme light and font big, we sent only ui theme dark, and our font disappeared, it takes the whole ui object and replaces it, it doesn't go inside, so check your nested settings before some user will tell you that his font is gone.
UPDATE users
SET settings = settings || '{"theme": "dark"}'
WHERE id = 42;
See also: reading query plans and safe migrations in Rails.