Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

A team stores most order attributes in a single jsonb column to avoid migrations. A year later, reports are slow, data has inconsistent keys, and a field rename broke billing. How would you review this design and what would you change?

I would keep JSON only for attributes that truly vary or are rarely queried, and promote everything that reports filter on, joins use or billing depends on into real columns with types and constraints. The remaining JSON gets validation and a version number, and the move happens gradually: add and backfill the columns, write both, switch reads, then stop writing the old keys.

Why this question is asked

Putting most attributes in one jsonb column feels productive at the start: no migrations, no schema review, any team can add a field. The costs arrive later and all at once, which is exactly what this team saw. Interviewers ask this design question to see whether we understand what a schema actually does for us, beyond being a list of columns, and whether we can fix a running system without stopping it. In this answer, we will look at what the team gave up, trace each of the three symptoms back to its cause, decide what stays in JSON and what becomes a column, add guard rails to the rest, and plan a migration that keeps billing running.

1What a Schema Was Doing for Us

A relational schema does three jobs that are easy to forget until they are gone. It enforces shape: a column has one name and one type, so every row agrees on what customer_id means. It enforces rules: NOT NULL, CHECK and foreign key constraints refuse bad data at the door. And it feeds the query planner, the part of the database that chooses how to run each query. After ANALYZE, PostgreSQL keeps statistics for every column, such as the most common values and a histogram of the rest, and it uses them to estimate how many rows each filter will return.

A single jsonb column gives up all three. The database sees one opaque value per row, so it cannot stop a writer from sending customerId in one service and customer_id in another, it cannot check that total is a number, and it has no per-key statistics. That is the trade the team made, often without knowing it: flexibility now in exchange for enforcement and good plans later.

2Tracing Each Symptom to Its Cause

Slow reports come mostly from bad estimates. When a report filters on attrs->>'channel' = 'web', the planner has no statistics for that expression and falls back to a fixed default guess. If the guess says 0.5 percent of rows but the truth is 60 percent, it may choose a nested loop join that runs millions of times instead of a hash join. Every report also has to extract and cast values from each document, which costs CPU on every row.

Inconsistent keys are the absence of shape. Without one owner of the format, each producer writes its own spelling, and every reader has to guess. The broken billing is the absence of a contract: a rename in one service was a silent breaking change for another, and nothing in the database or the build could notice it. We can measure the second problem directly before deciding anything.

Java
-- How many spellings of the same attribute exist?
SELECT k, count(*)
FROM orders, jsonb_object_keys(attrs) AS k
WHERE k ILIKE '%customer%'
GROUP BY k;
-- customer_id | 4100233
-- customerId | 312876
-- customer | 1904
-- How far off are the planner's estimates?
EXPLAIN ANALYZE SELECT count(*) FROM orders WHERE attrs->>'channel' = 'web';
-- rows=21450 (estimated) actual rows=2604118

Notice how this turns opinions into numbers. Three spellings of customer_id and an estimate that is off by a factor of over a hundred tell us which keys hurt most and give us a list to work through.

3Deciding What Becomes a Column

The rule I would use is simple. An attribute becomes a real column if reports filter or group on it, if a join uses it, if a constraint or another team depends on it, or if money is computed from it. customer_id, status, currency, total and created_at clearly qualify. An attribute stays in JSON if it truly varies between orders or is rarely queried, such as gift wrap options, marketplace specific fields, or the raw payload a payment provider sent us, which we keep for audit exactly as it arrived.

A stored generated column is a good first step, because it gives us a typed, indexable column without changing any writer. The database computes it from the JSON on every insert and update.

Java
ALTER TABLE orders
ADD COLUMN channel text
GENERATED ALWAYS AS (attrs->>'channel') STORED; -- typed copy, kept in sync by the database
CREATE INDEX CONCURRENTLY orders_channel_idx ON orders (channel);
ANALYZE orders; -- now the planner has real statistics
Where each attribute belongs
AttributeUsed forDecision
customer_idjoins, reportsreal column, foreign key
total, currencybillingreal columns, NOT NULL, CHECK
statusfilters, workflowreal column with allowed values
gift_optionsshown on one pagestays in JSON
provider_payloadaudit onlystays in JSON, never queried

But there is a catch: adding a stored generated column rewrites the whole table under an exclusive lock, which on a big orders table can mean minutes of blocked writes. For large tables, the gradual path in the last section is safer. A lighter option for estimates alone is an expression index or CREATE STATISTICS on the expression (PostgreSQL 14 and later), since ANALYZE then gathers statistics for it.

4Guard Rails for the JSON That Stays

The attributes that stay in JSON still need some rules. In the database we can add CHECK constraints for the few things that must always hold, such as the type of a value. In the application we validate the payload against a JSON schema before writing it, which can check much more than SQL can express comfortably. And we add a version number to the document, so a reader knows which shape it is reading and a change of shape becomes a new version instead of a silent rename.

SQL
ALTER TABLE orders ADD CONSTRAINT attrs_is_object
CHECK (jsonb_typeof(attrs) = 'object') NOT VALID; -- checks new rows right away
ALTER TABLE orders VALIDATE CONSTRAINT attrs_is_object; -- checks old rows without blocking writes
INSERT INTO orders (attrs) VALUES ('{"v": 2, "gift_options": ["wrap"]}'); -- ok
INSERT INTO orders (attrs) VALUES ('"just a string"');
-- ERROR: new row for relation "orders" violates check constraint "attrs_is_object"

Notice the NOT VALID then VALIDATE pattern: adding the constraint is instant and protects new rows, and validating old rows later takes a weaker lock that lets writes continue. The version key is the part that would have saved billing, because the rename would have been version 3, and billing would have kept reading version 2 until it was ready.

5Migrating Without Breaking Billing

Billing already broke once, so the move must be reversible at every step. We use the expand and contract pattern: add the new structure, run old and new side by side, then remove the old one only when nothing reads it.

Step throughMoving an attribute out of JSON
  1. Add nullable columnno lock on existing rows
  2. Backfill in batchesa few thousand rows per transaction
  3. Write both column and keynightly check compares them
  4. Do the values match for weeks?
    YesSwitch readers, billing lastNoFix writers, keep dual write
  5. Stop writing the old keythen add NOT NULL and CHECK

5 steps in order. Play them, or step through them one at a time.

First we add nullable real columns and backfill them from the JSON in batches of a few thousand rows, so locks stay short and replicas keep up. Then the application writes both the column and the JSON key, and a nightly check compares them and reports any row where they differ. Next we switch readers one at a time, billing last and with extra testing, to the new columns. When the comparison has been clean for a few weeks and no query reads the old keys (pg_stat_statements helps here), we stop writing them, add NOT NULL and the other constraints, and finally remove the keys from the documents. Each step can be rolled back by switching reads back to the JSON.

6Follow-up questions

Isn't a migration tool like Flyway or Liquibase enough to avoid this?

Those tools make migrations easy to run and repeat, which removes the original excuse for avoiding columns. They do not decide the design. The real lesson is that adding a column with Flyway is a small, reviewable change, while an uncontrolled JSON key is a hidden one.

When is a mostly-JSON design actually right?

When the data really has no stable shape and is read whole, such as product attributes that differ by category, form answers, or third party payloads. Even then, the keys used for joins, filters and money should be columns from the start.

How do we stop a rename from breaking a consumer again?

Treat the document shape as a versioned contract with an owner, validate it with a schema in the producer, and run consumer contract tests in the build. A rename then appears as a new version that consumers adopt on their own schedule.

7Conclusion

In this answer, we saw that one big jsonb column trades enforcement and planner statistics for flexibility, and that the three symptoms follow from it: poor estimates make reports slow, no shape lets keys drift, and no contract lets a rename break billing. The fix is to promote queried, joined, constrained and money attributes to real columns, perhaps first as generated columns, to keep JSON for truly variable or raw data with CHECK constraints, schema validation and a version key, and to migrate gradually with backfill, dual writes, switched reads and finally removal of the old keys.

What to say in the interviewAbout 90 seconds aloud

Open with

I would start by measuring rather than arguing: which keys reports filter on, how many spellings each attribute has, and how far the planner's estimates are from the actual rows.

Then, if they want more

The root cause is that a single JSON column gives up what a schema does for us. The database cannot enforce names or types, cannot apply constraints, and has no statistics per key, so the planner guesses and picks bad join strategies. Then I would sort attributes.

Anything that is filtered on, joined, constrained or used to compute money becomes a real typed column; customer id, status, currency and total are obvious ones. Truly variable attributes and raw provider payloads stay in JSON.

For the JSON that stays, I add a CHECK constraint that it is an object, validate it against a JSON schema in the application, and put a version number in the document so a shape change becomes a new version instead of a silent rename.

For the move itself I would use expand and contract: add nullable columns, backfill in batches, dual write with a nightly comparison, switch readers with billing last, and only then stop writing the old keys and add NOT NULL.

A generated column is a quick win on a small table, but on a big one it rewrites the table, so I would use the batch backfill there.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 14
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A team stores most order attributes in a single jsonb column to avoid migrations. A year...": https://scrivio-interview-library.netlify.app/databases/advanced-sql/287ab07f52/