Optimizing JSON and JSONB in PostgreSQL: GIN Indexes, Advanced Queries, and Real-World Benchmarks

Database tutorial - IT technology blog
Database tutorial - IT technology blog

Context & Why You Need to Optimize JSONB in PostgreSQL

Receiving webhooks from payment providers, storing feature flags, or managing diverse product attributes all share the same pain point: constantly changing schemas. Every time a third party adds a new field and you have to run ALTER TABLE on a 50-million-row table, it’s a nightmare.

Many developers facing this problem immediately think about spinning up a separate MongoDB cluster. Having operated MySQL, PostgreSQL, and MongoDB in production, I know that trade-off well. Adding a new database means extra backups, monitoring, replication, and the headache of syncing transactions across two systems. In reality, if you need both ACID guarantees and flexible data storage, PostgreSQL can handle it effortlessly—as long as you pick the right data type and index it properly.

PostgreSQL offers two JSON data types: JSON and JSONB:

  • JSON: Stores an exact copy of the input string, preserving whitespace, key order, and duplicate keys. Writes are very fast since minimal processing is needed. The downside is that PostgreSQL must re-parse the entire string from scratch on every query, and it doesn’t support direct GIN indexing on the column.
  • JSONB (JSON Binary): Parses the input into a decomposed binary format on write, stripping extra whitespace and keeping only the last value for duplicate keys (without preserving key order). It costs a bit more CPU on insert, but its read speed, filtering performance, and native GIN Index support leave the JSON type far behind.

Unless your system has a strict legal or compliance requirement to preserve every raw character of a payload (such as verifying raw webhook digital signatures), default to JSONB.

Environment Setup and Benchmark Data Preparation

Don’t test directly on staging. You can spin up a PostgreSQL 16 container locally in seconds to verify the numbers yourself:

docker run -d \
  --name pg-jsonb-lab \
  -e POSTGRES_PASSWORD=secret \
  -e POSTGRES_DB=labdb \
  -p 5432:5432 \
  postgres:16-alpine

Next, open psql in the newly created database:

docker exec -it pg-jsonb-lab psql -U postgres -d labdb

Creating the Table and Generating 500,000 Sample Rows

Let’s create an app_events table with two columns, payload_json and payload_jsonb, holding identical data for a fair comparison:

CREATE TABLE app_events (
    id BIGSERIAL PRIMARY KEY,
    created_at TIMESTAMPTZ DEFAULT now(),
    payload_json JSON NOT NULL,
    payload_jsonb JSONB NOT NULL
);

INSERT INTO app_events (payload_json, payload_jsonb)
SELECT
    data::json,
    data::jsonb
FROM (
    SELECT json_build_object(
        'event_type', (ARRAY['login', 'checkout', 'payment_failed', 'refund'])[1 + (i % 4)],
        'env', (ARRAY['prod', 'staging'])[1 + (i % 2)],
        'user', json_build_object(
            'id', i % 50000,
            'tier', (ARRAY['free', 'pro', 'enterprise'])[1 + (i % 3)]
        ),
        'latency_ms', (random() * 500)::int,
        'tags', ARRAY['api', 'v2']
    )::text AS data
    FROM generate_series(1, 500000) AS s(i)
) t;

ANALYZE app_events;

Deep Dive: GIN Indexing and Advanced Queries

Choosing JSONB is only the first step. Without an index, PostgreSQL still has to perform a full table Sequential Scan every time you filter.

Choosing the Right Operator Class: jsonb_ops vs jsonb_path_ops

GIN (Generalized Inverted Index) is built for nested data like JSONB. However, few developers notice that GIN has two different operator classes:

  • jsonb_ops (default): Indexes every key and every value separately. It supports all operators (@>, ?, ?|, ?&), but produces a noticeably larger index and slower writes.
  • jsonb_path_ops: Only hashes the path from the root down to the leaf value. As a result, the index size is typically 2 to 3 times smaller and filtering is significantly faster. The trade-off is that it only works with the containment operator @> and JSONPath (@?, @@).

Roughly 90% of real-world application queries filter by patterns like “find payment_failed events for enterprise-tier users.” For this scenario, jsonb_path_ops wins by a landslide:

-- Default GIN index (jsonb_ops)
CREATE INDEX idx_events_gin_default ON app_events USING GIN (payload_jsonb);

-- GIN index optimized for size and @> filtering speed (jsonb_path_ops)
CREATE INDEX idx_events_gin_path ON app_events USING GIN (payload_jsonb jsonb_path_ops);

Combining B-tree Expression Indexes for Range Queries and Sorting

Many people mistakenly think a GIN index speeds up ORDER BY or > / < comparisons. It doesn’t—GIN does not store sort order. If you frequently filter slow requests with latency_ms > 400, you need a dedicated B-tree expression index:

CREATE INDEX idx_events_latency
ON app_events (((payload_jsonb->>'latency_ms')::int));

Advanced Queries and Avoiding Index-Breaking Traps

The operators you choose in your query determine whether PostgreSQL can use a GIN index:

  • ->: Returns JSONB (used to traverse into child nodes).
  • ->>: Returns TEXT (used for display or type casting).
  • #>>: Extracts a value directly via an array path and returns TEXT, e.g., payload_jsonb#>>'{user,tier}'.
  • @>: Checks whether the left JSON value contains the right JSON value—the operator that pairs best with GIN.

For the exact same filtering logic, the two queries below deliver vastly different performance:

-- WRONG WAY: Extracting as TEXT with ->>, forcing a full table scan
SELECT id, created_at
FROM app_events
WHERE payload_jsonb->>'event_type' = 'payment_failed'
  AND payload_jsonb->'user'->>'tier' = 'enterprise';

-- RIGHT WAY: Using @> to trigger the GIN index
SELECT id, created_at
FROM app_events
WHERE payload_jsonb @> '{"event_type": "payment_failed", "user": {"tier": "enterprise"}}'::jsonb;

Starting with PostgreSQL 12, you also get standard JSONPath support. This syntax lets you write concise nested conditions while still leveraging the GIN index for equality checks:

-- Find prod events with latency > 450ms using JSONPath
SELECT id, payload_jsonb->'user'->>'id' AS user_id
FROM app_events
WHERE payload_jsonb @@ '$.env == "prod" && $.latency_ms > 450';

Tuning Memory When Building GIN Indexes in Production

Building an index on a large production table requires CONCURRENTLY so you don’t block writes. You should also temporarily bump maintenance_work_mem in your session so PostgreSQL can build the GIN tree in RAM instead of spilling to disk:

SET maintenance_work_mem = '512MB';
CREATE INDEX CONCURRENTLY idx_events_gin_path_prod
ON app_events USING GIN (payload_jsonb jsonb_path_ops);

Testing & Monitoring Real-World Performance

Once configured, measure with real numbers instead of guessing by gut feeling.

Comparing Performance with EXPLAIN (ANALYZE, BUFFERS)

On our 500,000-row sample dataset, the condition payment_failed (1/4) and enterprise (1/3) matches roughly 41,667 rows (~8.3% of the table). Let’s see how the unindexed JSON column handles it:

-- 1. Query on the standard JSON column
EXPLAIN (ANALYZE, BUFFERS)
SELECT count(*) FROM app_events
WHERE payload_json->>'event_type' = 'payment_failed'
  AND payload_json->'user'->>'tier' = 'enterprise';

This query typically takes between 280ms and 450ms. That’s because PostgreSQL has to run a Parallel Seq Scan, reading every page of the table and re-parsing the JSON string for each row.

Now let’s switch to the @> operator on the JSONB column with idx_events_gin_path:

-- 2. Query on the JSONB column using GIN jsonb_path_ops
EXPLAIN (ANALYZE, BUFFERS)
SELECT count(*) FROM app_events
WHERE payload_jsonb @> '{"event_type": "payment_failed", "user": {"tier": "enterprise"}}'::jsonb;

The Execution Plan immediately switches to a Bitmap Index Scan paired with a Bitmap Heap Scan. Execution time drops to around 15ms – 35ms (and for narrower filters matching a few hundred rows, it drops to 1ms – 3ms). Buffer reads drop dramatically as well.

Monitoring Index Size and Usage in Production

Creating redundant GIN indexes slows down INSERT/UPDATE operations and wastes disk space. Periodically check both index sizes and how often they are actually used:

SELECT
    indexrelname AS index_name,
    pg_size_pretty(pg_relation_size(indexrelid)) AS index_size,
    idx_scan AS total_scans,
    idx_tup_read AS tuples_read
FROM pg_stat_user_indexes
WHERE relname = 'app_events'
ORDER BY pg_relation_size(indexrelid) DESC;

Looking at the output, pay attention to two key things:

  • The index_size column: On 500,000 sample rows, idx_events_gin_path only takes about 15 – 20 MB, whereas idx_events_gin_default can bloat to 40 – 50 MB. If your app only uses @>, drop the default index to free up RAM for shared_buffers.
  • The idx_scan column: Any GIN index showing idx_scan = 0 after a few weeks in production is dead weight. Dropping it immediately reduces write overhead.

One final tip for write-heavy tables: GIN enables fastupdate = on by default. It batches new entries into a pending list up to 4MB (gin_pending_list_limit) before merging them into the main GIN tree. Once that list fills up, whichever write request triggers the cleanup will stall momentarily. If your system has strict tail-latency (p99) requirements, set fastupdate = off or tune autovacuum to run more aggressively so the pending list never piles up.

Share: