DEV Community

rinat kozin
rinat kozin

Posted on Originally published at redbase.app

JSON(B) for business objects: an index for every query, or foreign keys without forty tables

redb.Core

Disclosure: I am the author of redb, one of the storage options measured here. Its packages are free to use, Pro included, and this post contains no affiliate links.

How do you store composite business objects in PostgreSQL: a JSONB column, tables with Include, or something else? And which query made it start to hurt?

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 a store for business objects is usually expected to do two things. First, answer queries nobody planned when the schema was designed: tomorrow the business will want a page filtered on a field nobody thinks about today. Second, keep integrity: a reference to another object leads to an object that exists, a status comes from a reference list, a field name does not drift between documents.

JSONB answers fast the queries it was given an index for in advance, and keeps no integrity. Plain tables keep integrity, but a business object of ordinary size spreads over forty tables, and every new field needs a migration and a change to the mapping. redb keeps integrity with foreign keys in a few system tables and answers new queries without new indexes or migrations. This article checks what that costs each side.

We took one class from the redb examples, EmployeeProps, with 100,309 employees, and stored the same data 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 two ways, with Dapper and with EF Core. Then we asked every side the same questions. For every query each side builds the same 100 whole objects in the same order, and every object matches redb's field by field.

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). The document is about 2 kB and none goes to TOAST. It is a business object of ordinary size.

JSONB: fast when the query is known in advance

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)
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

That is 25,210 pages, the whole table, for 100 rows. 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: 5,042 pages.

Then comes the next query: employees on the 7th floor of their home building, ordered by hire date. The index of the first query does nothing for it, and the whole table is read again. A new compound expression index on the floor, the hire date and the id gives the best figure of the whole measurement: 1.8 ms for 100 finished objects. But it holds only for that exact query.

That is how JSONB works: every new query either reads the whole table or gets an index of its own, which means a schema change in the database and a deployment. On top of that come the fields a btree expression index cannot cover at all. Counting the fields of the nested classes, EmployeeProps has 75, and 48 of them sit inside arrays and 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". Every query has to reproduce that format, and an index for 2024-Q1 does not serve 2024-Q2.

JSONB: 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, and homeAddress instead of HomeAddress is just another key to the database.

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.

Integrity comes from normalization with foreign keys. There are two ways to get it for a class like this.

Two normalized forms

Classic tables. EmployeeProps laid out in normal form takes 41 tables, every relation a foreign key. With Dapper that is 41 tables in migrations, SQL for every child table and an object put together by hand. With EF Core it is 41 entities, a DbContext and an Include chain for every address, array and dictionary.

redb. redb is not a separate database engine but a .NET library. It keeps objects in a few ordinary tables of your PostgreSQL database (or SQL Server, or SQLite): _objects for the objects themselves, _values for the field values, and the tables of schemes, fields and reference lists. It is ordinary SQL, ordinary indexes and the ordinary PostgreSQL planner, all of it visible in psql. The same guarantees as the 41 tables, in the same tables for every class:

  • 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;
  • 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;
  • the parent of an object in a tree is a foreign key;
  • 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 sits in a column of its own type;
  • 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;
  • every field of every class except binary ones, array elements and dictionary keys included, is reachable through redb's system indexes, so a new query needs no new index.

The class is described once in C#, and redb syncs it with its schema at InitializeAsync(). There is no DbContext as a unit of work and no Include: an object is loaded whole by its class. redb Pro can 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.

The same E015 in redb

redb Pro turns the LINQ query E015 into one SQL statement over its tables. Its core (the full text adds an estimate of the page boundary and a fallback path for when the boundary does not hold; the field and class ids are shown as numbers):

SELECT d._id_object
FROM (SELECT v._id_object, v._numeric AS val
      FROM _values v
      WHERE v._id_structure = 1000020                -- field Salary
        AND v._array_index IS NULL AND v._numeric > 70000
      ORDER BY v._numeric DESC LIMIT 10000) d
JOIN LATERAL (SELECT o._id FROM _objects o
              WHERE o._id = d._id_object
                AND o._id_scheme = 1000014) o ON true -- class EmployeeProps
LEFT JOIN LATERAL (SELECT f._string AS v FROM _values f
              WHERE f._id_object = d._id_object
                AND f._id_structure = 1000019) pos ON true -- Position
LEFT JOIN LATERAL (SELECT f._long AS v FROM _values f
              WHERE f._id_object = d._id_object
                AND f._id_structure = 1000017) age ON true -- Age
WHERE pos.v <> '' AND age.v >= 30
ORDER BY d.val DESC, d._id_object
LIMIT 100;
Enter fullscreen mode Exit fullscreen mode

And its plan (shortened):

Limit  (actual rows=100)
  ->  Incremental Sort  (Presorted Key: d.val)
        ->  Nested Loop  (actual rows=5015)
              ->  Index Only Scan Backward using "IX__values__structure_numeric_object" on _values v
                    Index Cond: ((_id_structure = 1000020) AND (_numeric > '70000'::numeric))
              ->  Index Only Scan using "IX__objects__scheme_id" on _objects  (loops=5015)
              ->  Index Scan using "IX__values__structure_object_scalar" on _values f  (loops=5015)
                    Index Cond: ((_id_structure = 1000019) AND (_id_object = d._id_object))
              ->  Index Only Scan using "IX__values__structure_object_scalar" on _values f_1  (loops=5015)
                    Index Cond: ((_id_structure = 1000017) AND (_id_object = d._id_object))
Enter fullscreen mode Exit fullscreen mode

There is no full scan. PostgreSQL takes only the top of the system index of salaries, 5,015 entries out of 100 thousand, checks their class, position and age through indexes, and keeps the first hundred. The indexes are system ones, the same for every class and every field; nothing was built for E015. The next query, by floor, walks the same indexes on another field. redb reads the values of the hundred objects it found with a second statement and builds the objects from them.

Dapper and EF Core have no single statement like this: the object from 41 tables is built from the page and separate statements to the child tables, 40 for Dapper and about 30 per call for EF Core.

The cost of a change

What each side has to do when the class changes or a new question is asked of the data:

New scalar field New array or dictionary New query Foreign keys and reference lists
JSONB a new key in the document, unknown to the database a new key in the document, unknown to the database an expression index for that query, or a read of the whole table; on array elements and dictionary keys only GIN, for containment none, checks in the application code
41 tables + Dapper a migration, changes to the SQL and to the hand-written mapping a new table, one more statement in the batch, a change to the mapping SQL by hand, an index if needed yes
EF Core a migration a new entity, a migration, one more Include LINQ, an index if needed yes
redb a property in the C# class; at start-up redb adds the field to its schema, its values are stored in a column of their type and covered by the system indexes at once a property in the C# class; elements and keys are stored and indexed the same way, with no new tables LINQ; the system indexes already cover every field yes, foreign keys in the database

Normalization has one more cost, the number of round trips. Loading one employee by id takes 62 SQL statements in EF Core and 7 in redb on PostgreSQL (the results page of the redb examples, redbase.app/results).

Same data, same questions: 100 whole objects

For every page, five sides build the same 100 whole EmployeeProps objects in a .NET 10 process:

  • 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 with AsNoTracking;
  • redb Pro: ToListAsync() on its system indexes only. No query got an index of its own on the redb side.

The pages: Q1 is E015 above, Q2 employees on the 7th floor by hire date, Q2b employees of one city by hire date (ascending and descending), Q3 by the 2024-Q1 review from the tuple-keyed dictionary. Q4 is a page with references: 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 finished objects, 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, an index made for each 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
redb Pro, system indexes only 52.2 27.6 74.6 28.5 16.2 73.2 90.6
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

What the table shows:

  • JSONB with its own index is the ceiling, but only for a known query. Every figure in its row rests on an index built for that page. A new query without such an index reads the whole table, 25,210 pages, before the first object is built.
  • redb is in the same range as hand-written Dapper over 41 tables: 16-91 ms against 12-37, and faster on Q2 (27.6 ms against 37.1). Yet redb got no line of SQL, no migration and no index of its own, and all five pages, the tuple-keyed dictionary and the references included, run on the same system indexes.
  • Against EF Core, redb is 2.7 to 25 times faster on every page. 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. We did not measure a hand-tuned EF Core query.

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.

redb's tables are ordinary PostgreSQL tables, and every PostgreSQL tool works on them. For the field of each page we built a partial index on value and object, as we would for a table of our own, and changed nothing on redb's side. The planner took it by itself in three queries of four. It made nothing faster: with and without it the queries stayed within 1.5% of each other, because redb's system indexes already do the same work. So such queries need no indexes of your own to be fast, and if some query ever does, it is an ordinary CREATE INDEX.

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 478 MB
redb every field of every object, all reachable through the system indexes (EmployeeProps is 99% of it) about 3.8 GB

For those 3.8 GB redb gives what the other two sides do not have out of the box: indexes on every field of every class, array elements and dictionary keys included, and foreign keys on every reference and every reference-list value. It is a set made for any query. The queries of this article read about a quarter of the index volume, and another quarter keeps integrity: the primary and unique keys and the indexes of the foreign keys. The rest is there for queries this article does not run, such as groupings over array elements and substring search. If an application does not need them, the set can be narrowed with a script of its own, by our estimate by about a fifth of the space.

One can go further and replace the system value indexes themselves with partial ones. A system index holds the entries of every field of every class, a partial index only those of its own field, so if an application queries a known set of fields, partial indexes on those fields take many times less space. There are two prices. A query on a field without a partial index is left without an index, so what redb keeps the full set for is gone. And redb restores its value indexes at an upgrade of its SQL module, so such a script is run again after each upgrade. We did not build or measure this variant; how to tune the index 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 that rarely changes, and the time to write the mapping and migrations: plain tables with Dapper.
  • A model that lives with the code, with new fields and new queries all the time, and references, types and reference lists that the database must keep: redb. Integrity as in normalized tables, a new query or field without migrations or new indexes, speed in the same range as hand-written Dapper and 2.7 to 25 times above the examples' EF Core. The price is disk space.

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. The .NET 10 client ran on the same host.

All data fitted in memory. We did not measure a cold cache or data larger than memory; there the JSONB full scans would suffer more than the index walks.

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. Every fill was followed by VACUUM (ANALYZE), every index by ANALYZE. The JSONB, Dapper and EF Core rows come from one window, in two passes; the passes differ by less than a millisecond for JSONB and Dapper and by about 4 ms for EF Core. The redb row was taken later, in a separate window, on the same database and under the same protocol; the released redb next to it matched it within about 3%.

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.

redb, its examples and the EF Core comparison: github.com/redbase-app/redb. Every example with its time and statement count: redbase.app/results.

Where did a JSONB column with a business object first run into a new query or a dangling reference for you? Tell me in the comments, especially if you moved from it to tables, or the other way round.

If this was useful, a ⭐ on GitHub helps others find it.

More of my writing: redbase.app/articles, and on dev.to.

Top comments (0)