Storing JSON with PostgreSQL jsonb: what it does and when teams need it
If your team receives payloads whose shape varies from record to record and already runs PostgreSQL, jsonb lets you keep those documents in the same database as the rest of your data, without adding a second storage system. The work we plan and build for this starts with deciding which fields belong in ordinary columns and which can stay as documents, then setting up the schema, indexes and access rules inside infrastructure you control.
PostgreSQL's jsonb type stores JSON in a decomposed binary format. The PostgreSQL documentation describes it as slightly slower to input than the plain json type but significantly faster to process, because the server does not have to reparse the text on every use. The common use cases are event payloads from external systems, product or item attributes that differ by category, application configuration, and partial schemas where a few fields are fixed and the rest vary. jsonb sits alongside relational columns rather than replacing them: keys you filter, join or constrain on heavily should remain typed columns, while the variable remainder goes into a jsonb column on the same row.
Before committing, confirm three things with your data owners: how often the document shape changes, which keys are queried most often, and whether any of those keys must be enforced by a constraint. Those answers decide the split between columns and documents, and they set the work a partner needs to plan, including data loading, validation rules at write time and the migration path if a field later becomes a column. Ask for the design in writing, including which fields are typed, how malformed input is rejected, and who owns the schema changes. The PostgreSQL JSON types documentation is the natural reference for the type behavior described here, and your engineers should read it before the design review.
json or jsonb: how the two types store data
The json type stores an exact copy of the input text, including whitespace, key order and duplicate keys. PostgreSQL checks that the text is valid JSON when it is written, but it does not decompose the document. Every time a query reads a field, the server has to parse the stored text again, which adds work on each read. Because the original text is kept, the value comes back exactly as it was submitted, which can matter when a downstream system depends on byte-level fidelity or key order.
- Storage form: the exact input text is kept, so the stored value is close to the size of the submitted document.
- Input cost: writes are slightly quicker because no decomposition happens at insert time.
- Query cost: each field access reparses the text, so repeated extraction across large volumes is slower.
- Indexing: GIN indexes do not work on
json, so searches over keys or values across many documents need a different approach. - Fidelity: duplicate keys and original ordering are preserved, which can help audit or replay use cases.
Confirm whether your applications need the exact submitted text back, and measure read volume on documents before choosing json for a store that is queried often.
The jsonb type stores the document in a decomposed binary format. Input is slightly slower because PostgreSQL parses and converts the document when it is written, but later processing is significantly faster because the server does not reparse the text on each read. Whitespace is not preserved, key order is not kept, and duplicate keys are resolved so that only the last value remains. That normalization is what makes jsonb suitable for indexing and for containment and existence queries.
- Storage form: the binary decomposed form is used, so values are normalized on write.
- Input cost: writes are somewhat slower than
jsonbecause conversion happens at insert time. - Query cost: field access and operators work on the binary form, which is the reason for the faster processing.
- Indexing: GIN indexes support key and key/value search, and the
jsonb_path_opsoperator class offers a narrower index for containment and jsonpath queries. - Normalization: whitespace, key order and duplicate keys are not preserved, so the text returned may differ from the input.
Confirm that your consumers accept normalized output, and test write throughput with realistic document sizes if inserts are the bottleneck.
The practical difference shows up in which operators and indexes are available. A jsonb column can use containment operators such as @> together with a GIN index, and key-exists operators such as ? are also supported by the default GIN operator class. The jsonb_path_ops operator class is non-default and does not support key-exists operators, so it suits containment and jsonpath workloads where those are the main access patterns. A json column cannot use these GIN indexes, so queries against it generally scan or extract fields at read time.
- Containment queries:
jsonbwith a GIN index handles@>lookups across large document sets. - Key-exists queries: the default GIN operator class supports
?, whilejsonb_path_opsdoes not. - Expression indexes: btree indexes on extracted scalar values can serve equality and range filters on known fields.
- Choosing an operator class: decide between the default GIN class and
jsonb_path_opsbased on which operators the application actually uses. - Plan review: check
EXPLAINoutput to confirm the planner uses the index you built.
Confirm the exact query shapes your application runs, then build indexes against those shapes and verify them with production-like data volumes.
For most new document-style workloads inside PostgreSQL, jsonb is the default choice because it supports indexing, is faster to process and fits typical application queries. The json type is more appropriate when preserving submitted text exactly is a requirement, such as storing a signed payload or an audit record that must be returned byte for byte. Mixing both in one schema is possible, but it complicates queries and should be a deliberate decision rather than a default.
- Choose
jsonb: when documents are queried by content, indexed, or joined with relational tables. - Choose
json: when the original text, key order or duplicate keys must be kept for evidence or replay. - Signed or hashed payloads: store the original text in
jsonortextif a hash must match the submitted bytes. - Migration: converting a
jsoncolumn tojsonbchanges stored values, so confirm downstream consumers first. - Mixed use: keep one type per column where possible to keep query patterns consistent.
Confirm with your application and compliance owners whether byte-level fidelity is required before the column type is set, since changing it later rewrites the data.
The right type depends on measurements taken against your own documents. Document size, nesting depth, write rate, read patterns and how often fields are updated all influence the result. Benchmarks on synthetic data can mislead, so it is worth loading a representative sample of real or anonymized documents into both candidate types and running the actual queries. Record insert latency, query latency, index size and the effect on vacuum activity.
- Document shape: measure typical size, maximum size and how deeply documents are nested.
- Update pattern:
jsonbrewrites the whole document on partial updates, so frequent small changes to large documents deserve a test. - Index size: GIN indexes on large document sets can be substantial, so compare index size against the storage budget.
- Query plans: confirm with
EXPLAIN ANALYZEthat the intended index is used under realistic data volume. - Operational load: check the effect on vacuum and on backup size for each candidate.
Ask your database team to run this comparison on a staging copy before committing to a column type in production.
Which jsonb index and schema option fits which workload
This table compares the default GIN index, a jsonb_path_ops GIN index, expression indexes on specific keys and typed generated or relational columns. Read each row against the queries your application runs most often, because the right choice depends on which operators those queries use and how often the documents change.
| Option | Queries it supports | Write and maintenance cost | When it fits |
|---|---|---|---|
| Default GIN on jsonb | Key-exists operators (?, ?|, ?&) plus containment (@>) and jsonpath operators | Largest GIN index and the highest write overhead of the options listed here | Documents with varied keys where you query by key presence and by containment across many paths |
| GIN with jsonb_path_ops | Containment (@>) and jsonpath operators only, with no key-exists support | Smaller index than the default operator class and typically lighter writes | Containment-heavy filters on nested data where existence checks are not needed |
| Expression index on one key | Equality or range filters on the exact expression, such as (doc->>'status'), that match the index definition | One B-tree per key, so cost grows with each indexed key but stays modest per index | A few known, frequently filtered keys that drive your most important queries |
| Generated column with a B-tree index | Typed equality, range and ordering on a promoted value, with the planner using ordinary column statistics | Value is computed on write and stored, and the index adds write cost per column | Stable fields used in joins, sorting or constraints, where a fixed type helps correctness |
| Relational columns for core fields | Standard SQL types, foreign keys, check constraints and joins without jsonb operators | Schema migrations are needed when fields change, which adds release effort | Fields that every record must have, or that other tables reference |
| Keep the document opaque | Retrieval by primary key or a small number of known keys with no document-level search | Lowest index cost, but any search across the document requires a full scan | Payloads that are stored and returned as a unit and rarely queried internally |
| Confirm the choice with query plans | Run EXPLAIN (ANALYZE, BUFFERS) on production-like data before and after each index | Indexes need disk space and slow writes, so each one must earn its place | Every option above should be validated against the team's own queries and data volumes |
How to design schemas for semi-structured data
Storing documents in jsonb does not remove schema work, it moves it. The decisions below decide which data stays relational, how document shapes change over time, and whether the indexes you need stay usable as the data grows.
Keep queried fields as typed columns
Fields you filter, join, sort or enforce uniqueness on usually belong in ordinary typed columns, with the jsonb column holding the remainder of the document. A typed column gets normal statistics, constraints and index types, and it avoids casting inside every query. Before you move a field into jsonb, list the queries that touch it and check whether a B-tree index on a typed column or an expression index would serve them better.
Version every document shape
Store a schema version in each document, for example as a schema_version key, so the application knows how to read older rows. Without it, a field renamed in release 12 and a field renamed in release 15 look identical to the reader. Ask who owns the version field, how new readers handle unknown versions, and whether old documents are upgraded lazily on write or in a batch job.
Validate with CHECK constraints or code
jsonb accepts any valid JSON, so the database will not reject a missing customer_id unless you ask it to. CHECK constraints on jsonb expressions can enforce required keys and value types close to the data, at the cost of slower writes and a migration every time a rule changes. Application-side validation is easier to evolve but lets bad rows in from scripts, admin tools and other services. Most teams use both, with the database enforcing the small set of rules that must never break.
Limit nesting depth and array growth
Deeply nested objects make paths long, queries hard to read and partial updates expensive, because PostgreSQL rewrites the whole jsonb value on each change. Arrays that grow without bound, such as an event history stored inside one order document, make rows large and hard to vacuum. Set a maximum depth and a maximum element count in your design review, and move unbounded lists into their own table with a foreign key.
Keep key names stable for indexing
A GIN index on a jsonb column matches exact key names and values, so renaming cust_id to customerId in a later release splits your data across two keys and silently breaks queries. Choose a naming convention early, document it, and treat key names as part of the public contract. Dynamic keys, such as user-chosen field names used as object keys, make index usage and statistics harder to reason about, so prefer a fixed set of keys with values that vary.
Plan migration of document shapes
Every shape change needs a rewrite plan: whether old and new formats coexist, how long readers must support both, and how you prove that no rows still use the retired shape. Run the rewrite in batches so it does not hold long locks or generate a large burst of WAL. Confirm with your operations team how the backfill is monitored and how it is rolled back if a transform is wrong.
Deciding between jsonb in PostgreSQL and a separate document database
The decision starts with relational data that has variable attributes, the usual case for a jsonb column next to ordinary tables. The first hand-off asks whether transactions span documents and relational rows: if they do, keeping both in one PostgreSQL database avoids coordinating commits across two systems. The next check is whether query patterns need a JSON index, since a GIN index on jsonb (with jsonb_path_ops when only containment and jsonpath queries are needed) may cover the access paths. The last check asks whether search or scale needs exceed the current cluster. Only when the answer there is yes does a separate document store deserve a formal evaluation.
Decision path for choosing jsonb in PostgreSQL or a separate document database.
Setting up a jsonb document table with indexes and checks
This sequence takes a jsonb document table from version confirmation to a tested schema, a GIN index chosen for the real query patterns, and measured write and read behavior before the design reaches production.
Confirm the PostgreSQL version and support status
Confirm which PostgreSQL major version the environment runs and whether that release is still within its support window. The supported releases are 18, 17, 16, 15 and 14, with 14 ending November 12, 2026, so a table designed on 14 may need an upgrade plan before go-live. Your team or the partner records the version with
SELECT version();and checks the result against the support dates in the versioning policy. Done means the version, its end-of-life date and any planned upgrade are written into the design record. Confirm with your database owner whether the production and staging versions match.Design the table with typed keys and a jsonb payload
Decide which attributes are stable enough to be typed columns, such as a tenant identifier, a document type, a creation timestamp and a status, and which vary between documents and belong in a jsonb payload column. Typed columns carry NOT NULL constraints, foreign keys and ordinary B-tree indexes, so they stay cheap to query and validate. Write the DDL with a
jsonbcolumn, for examplepayload jsonb NOT NULL, and keep the payload limited to attributes that genuinely differ by record. Done means a reviewed DDL file exists and every query the application runs can be mapped to either a typed column or a payload key. Confirm the key list with the application team before creating the table.Add validation with check constraints
Because jsonb accepts any valid JSON, add rules that the database enforces on every write. Use CHECK constraints such as
CHECK (jsonb_typeof(payload) = 'object')and checks for required keys withpayload ? 'key', and keep the payload shape documented alongside the schema. Validation at the database layer protects data written by scripts and migrations, not only by the application. Done means invalid test rows are rejected by an insert in a test database, and a valid row is accepted. Confirm with your security and data governance owners which fields carry regulated data, because those fields need their own access and logging rules.Load representative data
Load a dataset that reflects production in row count, document size, key variety and nesting depth, using anonymized or synthetic records where real data cannot be used in a non-production environment. Uneven data shapes matter because a GIN index's size and the planner's choices depend on how many distinct keys and values appear. Run
ANALYZEafter the load so the planner has current statistics. Done means the table row count, average payload size and number of distinct top-level keys are recorded. Confirm with your data owners how much data is representative and where test data may be stored.Create the GIN index with the chosen operator class
Create a GIN index on the payload column. The default operator class supports key-exists operators and containment, so it fits queries that check whether a key is present. The non-default
jsonb_path_opsclass is smaller and faster for containment and jsonpath queries, but it does not support key-exists operators, so choose it only if the query list confirms that no query needs those operators. Example (illustrative):CREATE INDEX ON documents USING GIN (payload jsonb_path_ops);. Done means the index exists, its size is recorded withpg_relation_size, and the chosen operator class is written next to the query list it serves. Confirm with your DBA whether index build time fits your maintenance window on production-sized data.Run EXPLAIN on the real queries
Run
EXPLAIN (ANALYZE, BUFFERS)on each query the application sends, using the exact operators and parameters it uses. Containment queries with@>should show a bitmap scan on the GIN index for a selective filter. Key-exists queries with?need the default operator class, and a query that does not match the index operator class will fall back to a sequential scan. If the planner ignores the index on a large table, check the statistics and the selectivity of the predicate before changing settings. Done means each query's plan is saved and the index use is confirmed or explained. Confirm the query list against the production application code, not against examples.Test write and read performance
Measure insert and update cost with the GIN index in place, since each write must update the index entries for every key and value in the payload. Compare read latency at the expected concurrency using a load tool run against staging, and record write latency with and without the index on representative data to size the trade-off. Check autovacuum behavior on the table, because frequent payload updates create dead tuples that GIN maintenance must handle. Done means a written result shows write throughput, read latency at target concurrency and index size, and the team agrees whether the design meets its targets. Confirm target latency and concurrency numbers with the product owner before testing, because the test cannot pass without them.
Security and operational considerations for jsonb data
A jsonb column puts several kinds of data behind one column, so access, encryption, backups, maintenance and logging all need decisions that a typed schema would make for you. Each card below is something to design and then verify in your own environment, not a guarantee that PostgreSQL provides by default.
Access control on the jsonb column
PostgreSQL grants privileges per table and per column, not per key inside a document, so a role that can read the jsonb column can read every key in it. Decide whether sensitive keys belong in a separate table with stricter grants, or whether row-level security policies on the table are enough for your access model. Test each role with real queries to confirm what it can read and write.
JSON types docsEncrypting sensitive fields in documents
Transparent disk encryption protects files at rest but not values that an authorized query returns. If a document holds personal or regulated identifiers, decide between application-level encryption of specific fields, which blocks jsonb operators and indexes on those values, and keeping them out of the document entirely. Confirm with your security team which fields need this and how keys are rotated.
Backups and restore testing for documents
A base backup plus archived WAL files supports point-in-time recovery, and incremental backups are reconstructed with pg_combinebackup at restore time. Document data is easy to corrupt silently when an application writes malformed JSON through a bad release, so restore to a separate host and run queries that check the documents a business process depends on. Record how long each restore takes.
Continuous archiving docsVacuum and index upkeep on large jsonb tables
Large jsonb tables with frequent updates create dead tuples, and every update rewrites the whole document, so GIN indexes on those columns generate heavy write traffic. Watch autovacuum activity and table bloat on the jsonb table, and size GIN index maintenance into your change windows. Measure index size and vacuum duration on a copy of production data before you set thresholds.
Logging queries that touch sensitive content
Statement logging can capture document values inside query text, including literal values in containment checks such as @> filters. Decide which roles need audit logging, set log_statement and related parameters with that in mind, and check whether log files holding document content are restricted and retained under your policy. Verify the logs with a test query that contains a known marker value.
Questions teams ask before storing JSON in PostgreSQL
What drives the cost or effort of a jsonb design?
The main driver is how much of the document shape the application needs to query, filter and sort on. Fields that are only stored and returned cost little to design. Fields used in WHERE clauses, joins and ordering need a deliberate path expression, an index and a check that the planner uses it. Other drivers are the number of document types, how often their shapes change, how much validation sits in the database versus the application, and how many existing reports or exports read the JSON. Cost is mostly engineering time for schema decisions, query review and migration of existing rows, and it recurs whenever document shapes change. Ask any partner to list the queried paths and the expected document variants before quoting.
How long does a typical index and schema build take?
Duration depends on data volume, the query mix and how many document shapes exist, so no fixed figure applies here. Index creation time grows with the number of rows and the size of the documents, and a GIN index on a large table can take long enough to plan around a maintenance window. The number of distinct queries matters more than the raw table size, because each access pattern may need a different index or operator class. Schema work on a small set of well-understood document types moves faster than work on many loosely defined ones. Ask for the row counts, the top queries and a test run on a copy of production data before accepting a timeline.
What does the work need from our team?
The work needs people who know the data and the application well enough to say which fields are queried, how often documents change and which reports depend on them. Your application owners should provide representative sample documents, including edge cases and old versions, along with the query patterns that matter. A database administrator should confirm backup, storage and maintenance settings, and an engineer should be available to review query plans and application code. Access to a staging environment with a realistic data copy is important, since index behavior on synthetic data often differs from production. Agree on who approves schema changes before the build starts.
Can an in-house team design and run jsonb storage on its own?
An in-house team with solid PostgreSQL and application experience can usually handle a small, stable set of document types. The harder parts are judging which paths deserve indexes, testing query plans at realistic volume, and planning how document shapes evolve without breaking readers. Teams without recent PostgreSQL tuning experience often find that the first design works in development and slows in production. A partner is most useful for a one-time design review, a performance test on your data, or a migration from an existing document store. Compare the internal cost of those skills with a fixed-scope engagement, and confirm the scope in writing either way.
When is a separate document database worth the extra operations?
A separate document database is worth considering when the workload is dominated by flexible documents with heavy horizontal scaling needs, when your team already runs that platform well, or when the document model is the core product rather than a side feature. PostgreSQL with jsonb covers many cases where documents sit beside relational data, need transactions with other tables and must be queried with SQL. Each extra database adds backups, upgrades, monitoring, access control and a second failure domain to run. Compare the operational work of both options against the query and consistency needs, and document the reasons for the choice so the decision can be revisited.
How do indexes affect write performance?
Every index on a jsonb column must be updated when a row is inserted or changed, so write cost rises with the number of indexes and the size of the documents. A GIN index on a whole document is broader and generally more expensive to maintain than a targeted index on one path. The jsonb_path_ops operator class is smaller and faster for containment queries, but it does not support key-exists operators, so a design that depends on checking whether a key is present needs the default operator class or a different index. Test write throughput with the planned indexes in place, and remove any index that no production query uses.
Should jsonb columns replace all normalized tables?
No. Jsonb works best for attributes that vary between records or change often, while stable fields used in joins, constraints and frequent filters usually belong in ordinary columns. Mixing the two keeps foreign keys, check constraints and types enforced where they matter most. A common pattern is to store core identifiers and status as columns and keep the variable payload in a jsonb column. Treat the JSON portion as a schema you still design, with documented keys and validation in the application or in check constraints.
What is the difference between json and jsonb, and which should we use?
The json type stores an exact copy of the input text and must be parsed each time it is used. The jsonb type stores a decomposed binary form that is slightly slower to input but significantly faster to process, and it supports GIN indexing. For most document storage and querying, jsonb is the right choice. The json type is only worth considering when preserving the exact input text, including key order and duplicate keys, matters for your application. Confirm that choice against your application's needs before the schema is built.
Limits to confirm in your environment
A jsonb design depends on operator class behavior, index cost, version support and the operational path around the data. Confirm each item below against your own data and your own PostgreSQL build before the schema reaches production, and record the answers in the design review.
Key-exists support in jsonb_path_ops
The non-default jsonb_path_ops operator class does not support key-exists operators such as ? , ?| and ?&. It does support containment and jsonpath operators. If your queries test whether a key is present, a jsonb_path_ops index will not serve them. Run EXPLAIN on each production query shape against a staging copy and confirm which index the planner chooses. Ask your application team to list every query form that filters on keys alone.
Index size and write overhead
GIN indexes on large jsonb columns can be significant in size, and every insert or update of an indexed document updates the index. Measure index size and write latency on a copy loaded with realistic document shapes and volumes, using both the default GIN class and jsonb_path_ops. Ask your DBA to project index growth against your storage budget and your write peak, since these numbers depend entirely on your data and cannot be assumed from general guidance.
Version and support end date
Confirm which PostgreSQL major version your cluster runs and when its community support ends. Supported versions in the current policy are 18, 17, 16, 15 and 14, and the end dates differ by version, so a cluster on 14 has a nearer deadline than one on 17. Ask your platform owner for the version in your inventory, then plan any jsonb-related upgrade around that date. Minor release cadence also matters, because storage format is unchanged within a major version.
- Version 18 final release
- 2030
Document size and nesting limits
Test the largest and most deeply nested documents you expect, not the average. Large documents increase write amplification, TOAST handling and index entry counts, and deeply nested paths make queries and index use harder to reason about. Ask your data owners for the 99th percentile document size and maximum nesting depth, then load representative samples and check query plans and vacuum behavior at that volume.
Replication and backup coverage
Confirm that your streaming replicas, logical replication setup and point-in-time recovery process handle the jsonb design without special cases. Check that a restore from base backup plus archived WAL returns documents that query and index correctly, and that any logical replication publication includes the jsonb columns you intend to replicate. Your infrastructure team and your backup owner should sign off on a test restore before go-live.
Continuous archiving docsRunning jsonb inside a PostgreSQL cluster you control
A jsonb document table is still a PostgreSQL table, so its design choices sit inside the same cluster decisions as every other workload. The first one is the major version. Supported versions today are 18, 17, 16, 15 and 14, with 14 reaching end of support on November 12, 2026, so a new document store should start on a version with a clear support window, and the team should confirm the current end-of-life dates against the PostgreSQL versioning policy before the build starts. Choose the version with the upgrade path in mind, because a document store usually outlives the release it was built on. Minor releases do not change the storage format, so routine patching is a restart and executable replacement, while the major upgrade method (pg_upgrade, dump and restore, or logical replication) should be decided at design time, not when the next version is due.
Recovery planning matters more for document tables than teams often expect, because a jsonb column can hold many business fields in one row, and a bad application write can change them silently. Streaming replication to hot standbys protects availability, but it copies mistakes as well as data, so point-in-time recovery is the control that answers the question "what did this document look like before the bad deploy?" It combines a base backup with archived WAL files. Confirm that restores are tested on a schedule, that the archive is stored outside the primary failure domain, and that the team can restore a single document table or a full cluster within the targets it has agreed. Automatic failover is not built into PostgreSQL itself, so the external tool that promotes a standby must also be validated against your recovery goals.
Connection pooling is the third decision. Document applications often open many short requests, and each PostgreSQL connection has a cost. PgBouncer sits between the application and the server as a lightweight pooler, and the team should size pool modes and connection limits against the application's concurrency, then run load tests that include the jsonb queries and index updates they expect in production. Pinning PgBouncer to a current release also matters, since version 1.26.1 was released on October 14, 2026 with security fixes. Ask your team to confirm which pool mode works with the session settings and prepared statements their driver uses, because a mismatch can cause errors that look like database faults.

