JSON(B) for business objects: an index for every query, or foreign keys without forty tables
Storing a business object as one JSON document is often called an antipattern. PostgreSQL makes the best of it: jsonb, operators, GIN and expression indexes.
But there's a catch.
We took one class from the redb examples, EmployeeProps, with 100,309 employees, and stored the same rows three ways in one PostgreSQL 18.6 database: as a JSONB document per employee, as 41 plain tables, and in redb Pro. The plain tables were read twice, with Dapper and with EF Core. Then we asked every side the same questions and timed the answers, from the SQL to 100 whole objects in a .NET process.
The document
The class has eight scalar fields, three addresses with a building inside each, four arrays, a list of contacts, two references to project objects and six dictionaries, one of them keyed by a tuple (int Year, string Quarter). In our data the document is about 2 kB and none goes to TOAST; the emergency address, two of the dictionaries and the project references are empty in the examples' data (the references are filled for one page below), so four dictionaries carry data. So it is a business object of ordinary size.
Every side returns the same 100 ids in the same order for every query, and every object matches redb's field by field.
The catch: every new query needs its own index
The first query is example E015 from the redb repository:
redb.Query<EmployeeProps>()
.Where(e => e.Position != "" && e.Age >= 30 && e.Salary > 70000m)
.OrderByDescending(e => e.Salary).ThenByRedb(o => o.Id)
.Take(100)
On JSONB a careful developer writes:
SELECT id, doc FROM employees
WHERE doc->>'Position' <> '' AND (doc->>'Age')::int >= 30
AND (doc->>'Salary')::numeric > 70000
ORDER BY (doc->>'Salary')::numeric DESC, id
LIMIT 100;
Without an index for this query, LIMIT 100 does not save the work. To find the hundred highest salaries the database has to look at every document:
Limit (actual rows=100)
Buffers: shared hit=25210
-> Gather Merge (Workers Launched: 3)
-> Sort (Sort Method: top-N heapsort Memory: 31kB)
-> Parallel Seq Scan on employees (actual rows=17552.50 loops=4)
Filter: ((doc ->> 'Position') <> '') AND ((doc ->> 'Age')::integer >= 30)
AND ((doc ->> 'Salary')::numeric > 70000)
That is 25,210 pages, the whole table, for 100 rows: 52 ms. A GIN index on the whole document does not change the plan, since GIN answers containment and key existence and has nothing for a range or a sort. An expression index on (doc->>'Salary')::numeric, (doc->>'Age')::int does: 13 ms, 5,042 pages.
Then comes the next query: employees on the 7th floor of their home building, ordered by hire date. The Q1 indexes do nothing for it, and it is back to the full scan, 31 ms. A new compound expression index on the floor, the hire date and the id brings it down to 0.3 ms. That is the best figure in the whole measurement. It holds only for that exact query.
Two more things a btree expression index cannot do. Counting the fields of the nested classes, EmployeeProps has 75: 20 scalars outside any collection (the eight of the employee and four in each address), 7 classes or references, and 48 inside arrays or dictionaries; an expression index covers one array position or one dictionary key and cannot express "any element". And the tuple key of the reviews dictionary is not JSON at all: System.Text.Json refuses it by default, so our JSONB twin stores it as a string, "2024-Q1", in a format we chose. Every query has to reproduce that format, and the index we built for 2024-Q1 does not serve 2024-Q2.
The other catch: nothing ties the documents together
A JSON document has no foreign keys. A reference to another object is an id inside the document, a value from a reference list is a string. The database will accept an id of an object that no longer exists and a misspelt status. The schema lives in the application code.
MongoDB and RavenDB do not change that. Both are mature databases with ACID transactions, but references and schema are still the application's job (MongoDB's validation checks the shape of a document and does not look up the documents it references). They are also a second database next to PostgreSQL: a separate stack, and a write there is not part of your PostgreSQL transaction. We did not measure them, so there are no figures for them here.
Integrity comes from normalization with foreign keys. There are two ways to get it for a class like this.
Two normalized forms
Classic tables for EF Core. EmployeeProps laid out in normal form takes 41 tables, every relation a foreign key. Loading an employee whole means a DbContext and an Include chain for every address, array and dictionary, with split queries.
redb. The same guarantees, in the same few tables for every class:
- each value row has a foreign key to its object and to the description of its field;
- a field that references another object is a foreign key to that object: deleting an object that a field, an array element or a dictionary value still points to is refused by the database, through the redb API and through plain SQL alike (we checked it on PostgreSQL, SQL Server and SQLite). The soft delete into redb's trash is accepted, the references then read as empty, and the object is purged only once nothing points to it;
- the parent of an object in a tree is a foreign key;
- a value from a reference list (
ListItem) is a foreign key to the list item: a misspelt status cannot be stored, an item in use cannot be deleted, and renaming an item changes one row; - field names and types live in the database: a field is described once per class, every value points to that description by a foreign key, and each value sits in a column of its own type, with an index on field, value and object for every type except binary. In JSONB a field name is a string repeated in every document, and
homeAddressinstead ofHomeAddressis just another key; - uniqueness is declared on the class with
[RedbUnique]: a scalar, a whole nested class or array, or each element of an array across all objects. JSONB makes a whole subobject or array unique with an expression index too; a single element unique across documents needs a side table or a trigger; - a new field in the class needs no migration.
There is no DbContext as a unit of work and no Include: an object is loaded whole by its class. redb Pro can still save only the values that changed (PropsSaveStrategy.ChangeTracking). And since redb is tables in your own database, one transaction can cover a redb save and your own SQL run on redb's connection.
Between these two normalized forms the difference is the number of round trips. On the results page of the redb examples (redbase.app/results), loading one employee by id takes 62 SQL statements in EF Core and 7 in redb on PostgreSQL. Over the 105 examples that every platform completed in the first run, redb Pro on PostgreSQL took 152 ms on average (median 92), EF Core 545 ms (median 702). That run is a different bench from the rest of this article: the client on a laptop over Wi-Fi, the database server in the local network, two runs per example with the better one kept. It shows the order of magnitude and guarantees nothing for another workload.
Same data, same questions
Now the measurement of this article. For every page, five sides build the same 100 whole EmployeeProps objects:
- JSONB: the document of each row through System.Text.Json, on the expression index made for that page. It is the best case for JSONB: by default such an index does not exist;
- the 41 plain tables with Dapper: the page, then one batch of 40 statements, one per child table, and the object put together by hand;
- EF Core on the same 41 tables, the way the redb examples read an employee: every
Include,AsSplitQuery, a new context per call; and the same query withAsNoTracking; - redb Pro:
ToListAsync()on its system indexes only.
Every object of every side was compared with redb's, field by field, and matched.
Q4 is a page with references. No employee in the examples had any, so for this page we added 1,000 project objects and gave 5,010 analysts aged 55 and over a current project, two or three past projects and two project metrics, the same on every side. Q4 is read twice: with the references as ids, and with the referenced objects loaded.
Time from the start of the query to 100 objects in a .NET 10 process on the database host, warm process, median of 21 runs, ms:
| Side | Q1 (E015) | Q2 (floor 7) | Q2b (city) | Q2b desc | Q3 (review 2024-Q1) | Q4, ids | Q4, loaded |
|---|---|---|---|---|---|---|---|
| JSONB + System.Text.Json, index made for the page | 17.1 | 1.8 | 1.5 | 2.3 | 1.6 | 6.8 | 9.0 |
| 41 tables + Dapper | 18.3 | 37.1 | 20.7 | 22.6 | 11.6 | 20.0 | 25.3 |
| EF Core, the examples' query | 322.2 | 696.9 | 250.7 | 319.2 | 174.2 | 245.3 | 284.7 |
| EF Core, the same with AsNoTracking | 299.3 | 673.7 | 229.2 | 296.0 | 151.8 | 219.5 | 244.8 |
| redb Pro, system indexes only (later window) | 52.2 | 27.6 | 74.6 | 28.5 | 16.2 | 73.2 | 90.6 |
A second pass in the same window gave nearly the same figures: within a millisecond for JSONB and Dapper, within about 4 ms for EF Core.
We measured the redb row later, in a separate quiet window, on the same database and under the same protocol. Between the two windows redb gained a change that halved its memory use, so redb was measured again and the other sides were left as they were.
As for memory: for a page of 100 objects JSONB allocates about 0.9 MB in .NET, Dapper 1.8 MB, redb 5.5-5.8 MB and EF Core 9-11 MB. With the references loaded on Q4, redb comes to 11.7 MB and EF Core to about 19 MB.
The EF Core rows show the examples' own query and say nothing about EF Core in general: its split query sends about 30 statements per call, and each of them repeats the page query as a subquery. We did not measure a hand-tuned EF Core query.
The SQL alone, without loading the objects:
| Side | Q1 | Q2 | Q2b | Q3 |
|---|---|---|---|---|
| JSONB, no index | 51.7 | 30.7 | 31.9 | 0.4 |
| JSONB, GIN on the document | 52.3 | 31.2 | 33.8 | 54.0 (containment) |
| JSONB, the Q1 indexes | 13.2 | 30.8 | 32.1 | n/a |
| JSONB, the index made for the query | 13.2 | 0.3 | 0.5 | 0.3 |
| 41 tables, the page statement, the EF model's indexes | 5.2 | 18.2 | 2.3 | 0.6 |
| redb Pro, system indexes only | 35.7 | 14.8 | 76.2 | 1.6 |
The 41-table row is a single call from the plan log, and it is the page statement only: that side then reads the 40 child tables in a batch that takes 4-12 ms more server time.
In short, JSONB with an index made for the page is the fastest on every page. Dapper builds the whole object from 41 tables in 12-37 ms. redb beats it on Q2 (28 ms against 37) and is 1.3 to 3.7 times slower on the other pages. EF Core, used the way the examples use it, is behind redb everywhere, 2.7 to 25 times.
SQL time alone tells a different story. redb is faster than JSONB without the page's index on Q1 and Q2, and on Q2 it also beats the 41-table page statement (14.8 ms against 18.2). On Q3 it is a millisecond behind that statement (1.6 against 0.6), and on Q2b it loses to every side. JSONB without any index is still faster on Q3: a third of the employees match, so the database stops at about the 300th document in id order.
Q3 was a weak spot in our first measurement: redb read all 100,300 entries of the key 2024-Q1 and sorted them, 81.1 ms of SQL. We changed the planner. A condition on a dictionary entry is now read off the system index of values (field, value, object, with the key alongside), in object order, and stops at the page: 1.6 ms of SQL and 16.2 ms end to end.
Q2b stays the weak spot: about 75 ms end to end, 65 ms of it SQL. The SQL table above shows 76 ms because it was taken before the statistics were refreshed.
The cause is the storage layout. All fields of all classes share one table of values, so the statistics for "city is Berlin" do not know that the value belongs to the city field. The planner expects 121 rows instead of 20,060 and picks nested loops. The new planner path, a walk of the hire-date index, does not help here. Q2b sorts by hire date ascending, so objects without a hire date come first, and the index does not hold them: an absent value has no index entry. The same query sorted descending does take the walk and runs in 12-17 ms of SQL and 28.5 ms end to end (JSONB with its index 2.3 ms, Dapper 22.6).
The Q2b figure also depends on the statistics themselves. On a fresh copy of the same data, ANALYZE can pick the other of two equivalent indexes for the hire-date join, and the page then takes about 89 ms, whatever the redb build.
References cost every side something. Loading the referenced projects on Q4 adds 2-3 ms on JSONB, 5-7 ms on Dapper, 17 ms on redb and 24-45 ms on EF Core. Q4 is also where redb is furthest behind Dapper, 3.7 times: of its 73 ms about 50 ms is the page statement itself (a filter on position and age, sorted by hire date).
What redb gives for that time: no query above got an index of its own on the redb side. Q2, Q2b and Q3 were new queries, and they ran on the same system indexes as Q1. A condition on any key of any dictionary of any class is served by those indexes too; on JSONB it takes a GIN index per dictionary or a btree index per key.
redb also has a props cache in application memory (EnablePropsCache, off by default). It was measured in an earlier window, before the change that halved redb's memory use, so its figures are only comparable with each other. In that window Q1, Q2, Q2b and Q3 took 44.2 / 23.0 / 81.7 / 10.1 ms with a warm cache and 53.9 / 34.4 / 92.0 / 19.7 without it. The cache saves 9-11 ms a query.
On a cache hit only the page statement runs and no values are read from the database: the hash to compare comes with the object's row. What remains is a check in memory, about 5 ms per hundred objects. The cache recomputes each object's hash and walks its loaded references, to notice if someone changed a shared instance in place. The saving holds while the working set fits the cache's size limit. JSONB could have a cache in front of it too, so these figures are not compared with JSONB.
The price on disk
| Side | What is stored | Size |
|---|---|---|
| JSONB | the whole document, primary key only | 208 MB |
| JSONB + the four indexes the queries used | the whole document, indexes for Q1, Q2, Q2b, Q3 | about 227 MB |
| 41 tables | the whole object, with the EF model's indexes (heap 230 MB, indexes 246 MB, the Q4 reference rows included) | 478 MB |
| redb | every field of every object, all reachable through redb's own indexes (EmployeeProps is 99% of it) |
about 3.8 GB |
An expression index on each of the 20 scalar fields of the JSONB document would add an estimated 46-76 MB (we did not build them; nobody runs JSONB with an index on every field). The 48 fields inside arrays and dictionaries would still have no btree index. In redb every value is reachable through its own indexes whatever the field, dictionary keys included, and that is what the 3.8 GB pays for.
These 3.8 GB are the full set of redb indexes that comes out of the box, made for any query. We split it using the database catalog and the plan logs. The pages of this article read about a quarter of the index volume. Another quarter is needed whatever the queries: the primary and unique keys keep every save correct, and the foreign keys need their indexes on delete.
The rest is there for queries this article does not run. A senior developer tunes it with a script of their own, as in any database. On this data, dropping the indexes for groupings over array elements and for substring search, together with one index that duplicates another, frees about a fifth of the space by our estimate, and redb does not bring those back. Narrowing the value indexes as well would save more; redb restores those at an upgrade of its SQL module, so the script is run again after each upgrade. The three indexes of the planner come back at every start, so they stay. We dropped nothing and timed nothing afterwards; how to tune the set for an application is a topic for a separate article.
What to choose
- One hot query on known fields, no relations to keep: JSONB with an expression index for that query. Nothing here beats it.
- A settled model and the time to write the mapping: plain tables with Dapper. Over 41 tables they built the whole object in 12-37 ms.
- Foreign keys, types and reference lists held by the database, while fields and queries change with the code: redb, at the price in space and time shown above. Against the classic normalized form for EF Core it loads a whole object with far fewer statements, and on these pages it was 2.7 to 25 times faster than the examples' EF Core query.
How we measured
The bench: PostgreSQL 18.6 in Docker on a Ryzen 5 5500U with 38 GB of RAM and NVMe; shared_buffers 5 GB, work_mem 64 MB, jit = off; nothing else ran on the host during the measurement.
All data fitted in memory, and every page in every plan was a buffer hit. We did not measure a cold cache or data larger than memory. There the JSONB full scans would suffer more than the index walks.
End-to-end time is the median of 21 runs. Before them the same call ran for 10 seconds in the same process, so that .NET had compiled it fully. SQL time is the median of warm runs, and the plans come from EXPLAIN (ANALYZE, TIMING OFF, BUFFERS). Every fill was followed by VACUUM (ANALYZE), every index by ANALYZE. No sort spilled to disk.
The JSONB, Dapper and EF Core rows come from one quiet window, in two passes. The redb row was taken later with our development build in its default configuration. In the same window the released redb ran next to it on two equal copies of the data and matched it within about 3% on every page, with the same memory.
The first request of a freshly started process is slower on every side: 0.13-0.21 s for JSONB and Dapper, 0.35-0.45 s for redb (plus 0.6 s of InitializeAsync before it), 2.2-2.8 s for EF Core while it builds its model and compiles the split query. These are single measurements, one fresh process per page.
redb, its examples and the EF Core comparison: github.com/redbase-app/redb. Every example with its time and statement count: redbase.app/results.
If this was useful, a ⭐ on GitHub helps others find it.
More of my writing: redbase.app/articles, and on dev.to.