DEV Community

Cover image for 10 PostgreSQL Features That Replace a Service in Your Stack
Polliog
Polliog

Posted on

10 PostgreSQL Features That Replace a Service in Your Stack

In January, I Replaced Redis with PostgreSQL (And It's Faster) ended with a P.S.: "Want a follow-up on 'PostgreSQL Hidden Features' or 'When Redis is Actually Better'?" You wanted both. The Redis one came out last Friday. This is the other one.

I'm not going to call them hidden. Most of them are in the manual, and some have been there for ten years. The useful question is a different one: which of the services in your architecture diagram could be a feature of the database you already run?

Here are ten. For each one you get:

  • the service it replaces,
  • the few lines of SQL that do it,
  • one number I measured (eight of the ten; more on the other two below),
  • the limit, and when to keep the dedicated service.

Ten cards mapping a PostgreSQL feature to the service it replaces, from SKIP LOCKED for job queues to row-level security for tenant filtering

Three of them (queues, pub/sub, cache) were the core of the January post, and last week I measured where they break. I'll keep those short and link to the numbers. The other seven are new.

How I measured

Same approach as last week: one script, all of it at the end of the post.

  • Machine: 4 vCPU (Intel Xeon @ 2.3 GHz), 15 GB RAM, client and server on the same box.
  • Version: PostgreSQL 16.15, shared_buffers = 2GB, everything else default.
  • Load: pgbench with custom scripts, 16 clients unless I say otherwise, plus a small Python script for LISTEN/NOTIFY.

Absolute numbers will be different on your hardware. Look at the ratios and the shapes.

Two features have no number: pg_cron and pgvector are extensions, and they weren't available on the box I used for this run. For those I link the docs and say exactly what I'm relying on.

1. FOR UPDATE SKIP LOCKED replaces your job queue

Replaces: RabbitMQ, SQS, or BullMQ, for background jobs at app scale.

A queue is a table. A worker takes the first job nobody else has locked and deletes it, in the same transaction that does the work. If the worker dies, the transaction rolls back and the job is back in the table:

WITH job AS (
  SELECT id FROM jobs
  ORDER BY id
  LIMIT 1
  FOR UPDATE SKIP LOCKED
)
DELETE FROM jobs USING job
WHERE jobs.id = job.id
RETURNING jobs.*;
Enter fullscreen mode Exit fullscreen mode

SKIP LOCKED is the whole trick. Without it, every worker waits for the same first row. With it, each worker skips the rows that are already taken and grabs the next one.

Measured: 16 workers draining 2M jobs for 20 seconds.

16 workers Jobs/s Jobs processed twice
FOR UPDATE SKIP LOCKED 7,800 0 of 156,080
plain FOR UPDATE 4,000 0 of 80,433

Both are correct. Without SKIP LOCKED the workers line up behind one row and you lose about half the throughput.

The real reason to do it is the transaction. You can insert a job in the same transaction as the order that caused it. If the order rolls back, the job never existed. With an external broker you need an outbox table to get the same guarantee, and an outbox table is... a queue in Postgres.

In LogTide the simple deployment runs its jobs on graphile-worker, which is built on exactly this pattern (I wrote about why I chose it).

Limit: every finished job is a dead row for autovacuum. Last week I measured a queue dropping 13x because an unrelated session kept a transaction open. Set idle_in_transaction_session_timeout and watch pg_stat_activity.

Keep the broker if you run thousands of jobs per second, need fan-out to several consumers, or share the database with long analytical queries.

2. LISTEN / NOTIFY replaces pub/sub

Replaces: Redis Pub/Sub for "something changed" signals between your backend processes.

-- in the worker
LISTEN orders;

-- anywhere, usually in the same transaction as the write
SELECT pg_notify('orders', json_build_object('id', 42)::text);
Enter fullscreen mode Exit fullscreen mode

The detail people miss: a notification is sent when the transaction commits, not when you call NOTIFY. That gives you two properties for free, and I checked both:

  • a transaction that rolls back sends nothing. I sent one and rolled back: 0 delivered.
  • identical notifications in one transaction are folded into one. I sent the same payload 100 times in a transaction: 1 delivered.

Measured: 10,000 notifications, one per committed transaction, one listener on the same machine. Uncontended delivery latency, one message at a time, was 0.12 ms at p50 and 0.22 ms at p99. That's a baseline, not a number under load; the load story is in the limit below.

LogTide's live tail works this way: the ingestion path calls pg_notify('logs_new', ...) and the streaming module holds a LISTEN logs_new connection (notification-publisher.ts and notification-manager.ts, commit 4c1e310). I wrote the long version here.

Limit: committing a transaction that notified takes a global lock, so notifying writers commit one at a time. Last week 32 writers lost 76% of their throughput when each one added a pg_notify. Payloads must be under 8,000 bytes, and a listener that is disconnected misses the message.

Keep Redis if you push to thousands of clients, notify on every row of a busy table, or need replay (Redis Streams, Kafka).

3. UNLOGGED tables replace your cache

Replaces: Redis or Memcached as a cache next to one application.

CREATE UNLOGGED TABLE cache (
  key        text PRIMARY KEY,
  value      jsonb NOT NULL,
  expires_at timestamptz NOT NULL
);
Enter fullscreen mode Exit fullscreen mode

An unlogged table skips the write-ahead log. That's what makes it fast, and that's what makes it a cache.

Measured: 16 clients inserting 200-byte values into an empty table for 20 seconds.

16 clients Inserts/s
regular table 23,100
UNLOGGED table 74,600

3.2x faster writes. The regular table wrote 208 MB of WAL for 463k rows; the unlogged table writes none for its rows.

Last week I also measured reads: Postgres served 128k to 150k cache GETs per second on a similar 4-vCPU box, more than Redis without pipelining, but using three cores to do it.

Limit: an unlogged table is emptied after a crash, is not replicated to standbys, and has no TTL: you delete expired rows yourself (see pg_cron below). Don't keep sessions there unless logging everybody out after a crash is acceptable.

Keep Redis if cache traffic is big enough that you'd rather spend one core on it than three of your primary's.

4. Advisory locks replace your distributed lock

Replaces: Redlock, etcd or ZooKeeper, for "only one of these at a time".

An advisory lock is a lock on a number. Postgres doesn't care what the number means; your application decides.

BEGIN;
SELECT pg_advisory_xact_lock(42);   -- waits until nobody else holds 42
-- check, then act
COMMIT;                              -- released automatically
Enter fullscreen mode Exit fullscreen mode

Use it for "check, then insert" logic that a constraint can't express. My test: a show with 100 seats, and a booking query that sells a seat only if fewer than 100 are sold.

INSERT INTO seats (taken_by)
SELECT $1 WHERE (SELECT count(*) FROM seats) < 100;
Enter fullscreen mode Exit fullscreen mode

Measured: 16 clients, 50 booking attempts each, 800 attempts for 100 seats.

Seats sold
no lock 110
pg_advisory_xact_lock(42) first 100

Without the lock, concurrent transactions all saw "99 sold" and all said yes. Ten people have a ticket for a seat that doesn't exist. With the lock, exactly 100. Taking and releasing a lock on a random key ran at about 97,600 cycles per second.

LogTide does this in two places (commit 4c1e310). User registration takes pg_advisory_xact_lock so that two people signing up at the same moment on a fresh install can't both become the first admin. Extension migrations take one keyed on hashtext('ext-migrate:' || schema), so the API server and the worker booting together don't run the same migration twice.

Limit: prefer the _xact_ versions. Session-level locks (pg_advisory_lock) stay held until you unlock or disconnect, and behind PgBouncer in transaction mode, "your session" is whatever connection the pooler gave you this time. Also, a lock only coordinates clients of the same Postgres server.

Keep etcd or ZooKeeper if you coordinate things that don't touch this database, or need leader election across regions.

5. pg_cron replaces your scheduler

Replaces: the cron box, the "scheduler" container, or the scheduled Lambda that runs one SQL statement.

CREATE EXTENSION pg_cron;

SELECT cron.schedule('purge-cache', '*/5 * * * *',
  $$DELETE FROM cache WHERE expires_at < now()$$);

SELECT cron.schedule('refresh-stats', '30 seconds',
  $$REFRESH MATERIALIZED VIEW CONCURRENTLY daily_stats$$);
Enter fullscreen mode Exit fullscreen mode

No number for this one: the extension wasn't available on my test box. Everything below is from the pg_cron README (version 1.6.7):

  • it uses normal cron syntax, plus '[1-59] seconds' intervals;
  • it runs at most one instance of a job at a time. If a run is still going when the next one is due, the next one waits. That's the overlap protection people usually hand-roll with a lock;
  • every run is recorded in cron.job_run_details, with status and error message.

It's available on the big managed services (RDS, Aurora, Cloud SQL, Azure), so it's usually one CREATE EXTENSION away.

Limit: it needs shared_preload_libraries (a restart), it doesn't run jobs while the server is a hot standby, and the schedule is in GMT unless you set cron.timezone. cron.job_run_details is never cleaned up automatically; schedule a job for that too. Jobs run SQL, so anything that needs to call an API still needs a worker.

Keep a real scheduler if your jobs are mostly HTTP calls, need retries with backoff, or depend on each other. That's a workflow engine, not cron.

6. Full-text search replaces your search engine

Replaces: Elasticsearch or Algolia, for search inside your own app's data.

ALTER TABLE messages ADD COLUMN tsv tsvector
  GENERATED ALWAYS AS (to_tsvector('english', body)) STORED;

CREATE INDEX ON messages USING gin (tsv);

SELECT id, ts_rank(tsv, q) AS rank
FROM messages, websearch_to_tsquery('english', 'disk failure -test') q
WHERE tsv @@ q
ORDER BY rank DESC
LIMIT 10;
Enter fullscreen mode Exit fullscreen mode

A generated column keeps the tsvector in sync on every write, so there's no indexing pipeline to run. websearch_to_tsquery understands the syntax people type into search boxes: quotes, or, and - to exclude.

Measured: 1M messages of 12 words each, drawn from a 5,000-word vocabulary where a few words are very common and most are rare, like real text. (I used the simple config in the test because the words are synthetic; use a language config like english for real text.)

1M messages Time (median of 3)
ILIKE on the text, no index 610 ms
tsv @@ query, no index 66 ms
tsv @@ query, GIN index, rare word (894 hits) 1.8 ms
same, two words AND 0.6 ms
top 10 by ts_rank, rare word 3.0 ms
top 10 by ts_rank, common word (97,545 hits) 92 ms

Even without an index, the stored tsvector beats ILIKE by about 9x, because matching words in a prepared vector is cheaper than scanning strings (to be fair, my ILIKE needed three patterns to match a whole word). The GIN index takes it from 66 ms to under 2 ms, and it was 52 MB next to a 251 MB table.

Look at the last two rows. The index finds matching rows fast, but ts_rank has to be computed for every match before Postgres can pick the top 10. A rare word ranks in milliseconds. A word that matches 10% of your table takes about 30 times longer, and that grows as the table grows.

LogTide uses both halves of Postgres search on its log table (commit 4c1e310): a GIN index on to_tsvector('english', message) for word search, and pg_trgm for substring search, like half a hostname or part of an error code.

Limit: ts_rank is not BM25. There's no typo tolerance without pg_trgm, no synonyms or per-field boosting without work, and ranking cost grows with the number of matches, as measured above.

Keep Elasticsearch, OpenSearch, or a search service if search relevance is your product, you need facets and typo tolerance on millions of documents, or ranking queries start eating your primary's CPU.

7. pgvector replaces your vector database

Replaces: Pinecone, Weaviate, or Qdrant, for embeddings that live next to the rows they describe.

CREATE EXTENSION vector;

CREATE TABLE chunks (
  id        bigserial PRIMARY KEY,
  tenant_id int NOT NULL,
  body      text NOT NULL,
  embedding vector(1536) NOT NULL
);
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops);

SELECT id, body
FROM chunks
WHERE tenant_id = $1
ORDER BY embedding <=> $2
LIMIT 5;
Enter fullscreen mode Exit fullscreen mode

The selling point isn't speed. It's that the embedding sits in the same row as tenant_id, body, and your permissions, inside the same transaction and backup. No sync job between your database and the vector store, no "deleted in Postgres, still found in Pinecone".

No number for this one either: same reason as pg_cron. I compared it with Pinecone and Weaviate in an earlier post. The limits below are from the pgvector README.

Limit: filters are applied after the approximate index scan. The README's own example: if your WHERE matches 10% of rows, with the default hnsw.ef_search of 40 you get about 4 rows back on average, not 5. Since 0.8.0 you can turn on iterative scans (SET hnsw.iterative_scan = strict_order), which keep scanning until enough rows match. Turn it on if you filter. Also, HNSW builds are much faster when the graph fits in maintenance_work_mem, and the vector type indexes up to 2,000 dimensions (halfvec goes to 4,000). So OpenAI's text-embedding-3-large, 3,072 dimensions by default, needs halfvec or shortened embeddings to get an HNSW index.

Keep a vector database if you have hundreds of millions of vectors, the index no longer fits in RAM, or vector search traffic competes with your transactions.

8. JSONB + GIN replaces your document store

Replaces: MongoDB, for data whose shape changes more often than your migrations.

CREATE TABLE events (
  id  bigint PRIMARY KEY,
  doc jsonb NOT NULL
);
CREATE INDEX ON events USING gin (doc jsonb_path_ops);

SELECT * FROM events
WHERE doc @> '{"user": {"country": "IT", "plan": "pro"}, "type": "refund"}';
Enter fullscreen mode Exit fullscreen mode

@> means "contains". One GIN index answers containment queries on any key, at any depth, including array elements. jsonb_path_ops supports fewer operators than the default jsonb_ops (no "has key" ?), and in exchange its lookups are usually faster.

Measured: 1M documents with a type, a nested user object, two tags and an amount.

1M documents, median of 3 No index GIN jsonb_path_ops
one user ({"user":{"id":12345}}, 20 matches) 86 ms 0.2 ms
three keys, nested (10,012 matches) 75 ms 29 ms
one array element ({"tags":["t7"]}, 10,063 matches) 89 ms 16 ms
(doc->>'amount')::numeric > 499 (1,963 matches) 73 ms 78 ms

The GIN index turns a selective lookup into a fraction of a millisecond. It helps less as matches grow, because Postgres still has to fetch every matching row. And it does nothing for the range query in the last row: GIN can't do >. A plain B-tree expression index on ((doc->>'amount')::numeric) took that query to 3.4 ms.

Both GIN flavors came out at 29 MB on these small documents (the table is 191 MB).

LogTide indexes OpenTelemetry metric attributes exactly like this: USING GIN (attributes jsonb_path_ops) in migration 026_add_metrics.sql (commit 4c1e310). Attributes are whatever key/value pairs the SDKs send, so there's no fixed schema to put in columns. I wrote a whole post on why JSONB GIN queries are slow and how to fix them.

Limit: GIN only helps with "contains" and "has key". Ranges, sorting and ->> comparisons need an expression index per field, like the amount row above. Changing one key writes a new copy of the whole document, so a large document with one hot counter is a bad fit. And there's no schema: a typo in a key name is valid JSON.

Keep MongoDB if documents are your whole data model, you need its sharding, or your team's tooling is built around it. If you mostly have relational data with a few flexible fields, keep it in Postgres.

9. Partitioning replaces your retention job

Replaces: the nightly DELETE FROM events WHERE created_at < now() - interval '30 days', and the archive service that grows around it.

CREATE TABLE events (
  ts      timestamptz NOT NULL,
  payload text NOT NULL
) PARTITION BY RANGE (ts);

CREATE TABLE events_2026_11_01 PARTITION OF events
  FOR VALUES FROM ('2026-11-01') TO ('2026-11-02');
-- ...one per day

-- retention: drop a whole day at once
ALTER TABLE events DETACH PARTITION events_2026_11_01;
DROP TABLE events_2026_11_01;
Enter fullscreen mode Exit fullscreen mode

Queries see one table. Underneath, each day is its own table, so deleting a day means deleting a file.

Measured: 10M rows over 10 days, 1M per day, with an index on ts. Removing the oldest day:

Removing 1M of 10M rows Time WAL written Table size after
DELETE ... WHERE ts < '2026-11-02' 685 ms 188 MB 1,562 MB (unchanged)
DETACH + DROP partition 105 ms 79 kB one day smaller

The time difference is only 6.5x here, because the deleted rows were all together at the start of the table. The other two columns are the real story. The DELETE wrote 188 MB of WAL, which your replicas and backups have to absorb. And it gave no disk space back: after a VACUUM the table was still 1,562 MB. That space gets reused by new rows, but the file doesn't shrink. Dropping a partition wrote 79 kB of WAL and freed the disk space immediately. On a busy table, the DELETE also leaves a million dead rows for autovacuum to clean up while your writes keep coming.

LogTide does this through TimescaleDB, which partitions the log table into chunks automatically. Its retention job calls drop_chunks for the maximum retention ("instant, drops entire files", says the comment in retention/service.ts) and only falls back to row deletes for organizations with a shorter retention than the maximum.

Limit: you have to create partitions ahead of time (pg_partman or a scheduled job, see pg_cron above), a query that doesn't filter on the partition key reads every partition, and primary keys must include the partition key.

Keep a separate archive if you need years of history that nobody queries interactively. Export old partitions to Parquet on object storage before you drop them.

10. Row-level security replaces your tenant filter

Replaces: the WHERE tenant_id = ? you add to every query by hand, and the middleware that's supposed to make sure you never forget it.

ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation ON invoices
  USING (tenant_id = current_setting('app.tenant_id', true)::int);

-- per request, inside the transaction
SELECT set_config('app.tenant_id', '42', true);
SELECT * FROM invoices;   -- only tenant 42's rows
Enter fullscreen mode Exit fullscreen mode

The database adds the filter to every query on that table, for every role the policy applies to. Forget the WHERE and you still get only the current tenant's rows. Forget to set the tenant and you get zero rows, not everybody's invoices.

Measured: 2M invoices, 1,000 tenants, an index on tenant_id. Same transaction shape in both runs (set the tenant, count and sum one tenant's invoices).

16 clients, 20 s Transactions/s
table owner (RLS bypassed), explicit WHERE tenant_id = $1 1,480
app role, policy only, no WHERE 1,466

A 1% difference, within noise. EXPLAIN shows why: the policy's condition becomes an Index Cond on invoices_tenant_id_idx, the same plan as the hand-written WHERE. And when I ran the query without setting app.tenant_id, I got 0 rows, not two million: current_setting(..., true) returns NULL, and NULL matches nothing.

(These transactions are slow in absolute terms because each tenant's 2,000 invoices are spread across the whole table. That's the same for both runs.)

Limit: superusers and roles with BYPASSRLS always skip policies, and so does the table owner unless you ALTER TABLE ... FORCE ROW LEVEL SECURITY. Make sure your app connects as a plain role, not as the owner of its tables. Use set_config(..., true) (or SET LOCAL) so the tenant is scoped to the transaction: with a pooler, a session-level setting leaks into the next request that gets the same connection. And policies with complex subqueries run for every row they check, so keep them to indexed column comparisons.

Keep it in the application if your permission model is richer than "rows belong to a tenant" (sharing, roles per document, field-level rules). That's what dedicated authorization services are for.

All the numbers in one picture

Six bar charts comparing each feature with the same job done without it: queue throughput, insert rate, seats sold, search time, JSONB lookup time and WAL written for retention

The summary table

# Feature Replaces What I measured Bring the service back when
1 SKIP LOCKED job queue 7,800 jobs/s, 0 duplicates (2x plain FOR UPDATE) thousands of jobs/s, long transactions nearby
2 LISTEN/NOTIFY pub/sub 0.12 ms p50 delivery; rollback sends nothing many writers, thousands of listeners, replay
3 UNLOGGED cache 3.2x faster inserts than a regular table cache traffic competes with your queries
4 advisory locks distributed lock 100 of 100 seats sold, vs 110 without coordination outside this database
5 pg_cron scheduler not measured jobs are HTTP calls or workflows
6 tsvector + GIN search engine 1.8 ms vs 610 ms for ILIKE relevance is the product, big result sets
7 pgvector vector database not measured index outgrows RAM, heavy filtered search
8 JSONB + GIN document store 86 ms to 0.2 ms for a selective lookup documents are the whole model
9 partitioning retention job 79 kB of WAL vs 188 MB for one day years of cold history
10 row-level security tenant filter 1% overhead, 0 rows when tenant unset permissions richer than "rows per tenant"

When not to do any of this

"Use the database you already have" is a default, not a rule. Bring in the dedicated service when:

  • one feature starts eating your primary's CPU or I/O. Search, vectors and cache are the usual suspects. A workload that competes with your transactions is a workload that wants its own box, even if that box also runs Postgres.
  • you need the thing the service is actually good at: fan-out to thousands of clients, BM25 relevance tuning, billions of vectors, replayable streams.
  • another team owns it. A shared database is a shared failure domain and a shared schema. Sometimes a boundary is worth a network hop.

The cost of a feature in Postgres is mostly zero until it isn't. The cost of a new service starts on day one: a deployment, a backup, a monitor, an on-call runbook, and a second place where your data can be wrong.

TL;DR

  • Ten services you might be running next to Postgres can start as a Postgres feature: queue, pub/sub, cache, locks, scheduler, search, vectors, documents, retention, tenant isolation.
  • The best reason isn't speed, it's the transaction: the job, the notification, the embedding and the row commit or roll back together.
  • Each one has a measurable edge. Ranking a common word costs 30x a rare one. Notifying writers commit one at a time. GIN can't do ranges. A DELETE keeps its disk space.
  • Start with the feature. Add the service when one of those edges shows up in your numbers, not in your diagram.

All the numbers come from one script. You need a throwaway PostgreSQL 16 or newer (it drops and recreates its own tables), Python 3 with psycopg 3, and about 20 minutes. The script creates a role app_user for the RLS test that logs in without a password, so run it where local connections use trust.

Save the files below in one folder and run ./run.sh.

run.sh (click to expand)
#!/usr/bin/env bash
# Benchmarks for "10 PostgreSQL Features That Replace a Service in Your Stack".
# Needs: a THROWAWAY PostgreSQL 16+ (psql + pgbench), python3 with psycopg 3.
# It drops and recreates its own tables. Do NOT point it at a real database.
#
#   PGHOST=/var/run/postgresql PGUSER=postgres ./run.sh | tee results.txt
set -euo pipefail
cd "$(dirname "$0")"
: "${PGHOST:=/var/run/postgresql}" "${PGPORT:=5432}" "${PGUSER:=postgres}" "${PGDATABASE:=postgres}"
: "${T:=20}"
export PGHOST PGPORT PGUSER PGDATABASE

P="psql -q -X -v ON_ERROR_STOP=1"
A="psql -X -At -v ON_ERROR_STOP=1"
pgb() { pgbench -n "$@" 2>&1 | grep -E "^tps|latency average|number of transactions actually" ; }
walmark() { $A -c "SELECT pg_current_wal_lsn()"; }
waldiff() { $A -c "SELECT pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), '$1'))"; }
timed() { psql -X -c '\timing on' "$@" | grep -E "^Time"; }
# runs a query 3 times, prints the 3 timings
timed3() { psql -X -c '\timing on' -c "$1" -c "$1" -c "$1" | grep -E "^Time" | awk '{printf "%s ms  ", $2} END {print ""}'; }
want() { [ -z "${ONLY:-}" ] || [[ " $ONLY " == *" $1 "* ]]; }   # ONLY="5 7" runs only sections 5 and 7

echo "## Versions"; $A -c "SELECT version()"; $A -c "SHOW shared_buffers"
echo "nproc=$(nproc)"; grep -m1 "model name" /proc/cpuinfo || true

if want 1; then
echo; echo "## 1. Queue: SKIP LOCKED vs plain FOR UPDATE (16 workers)"
for mode in skip noskip; do
  $P -c "DROP TABLE IF EXISTS jobs, done" \
     -c "CREATE TABLE jobs (id bigint PRIMARY KEY, payload jsonb NOT NULL)" \
     -c "CREATE TABLE done (job_id bigint NOT NULL)" \
     -c "INSERT INTO jobs SELECT g, '{\"n\":1}' FROM generate_series(1,2000000) g" \
     -c "VACUUM ANALYZE jobs"
  echo "mode=$mode"; pgb -c 16 -j 4 -T $T -f queue_$mode.sql
  $A -c "SELECT 'jobs done: '||count(*)||'  distinct: '||count(DISTINCT job_id)||'  per second: '||round(count(*)/$T.0) FROM done"
done
fi

if want 2; then
echo; echo "## 2. LISTEN/NOTIFY: latency, rollback, dedup"
python3 notify_latency.py 10000
fi

if want 3; then
echo; echo "## 3. Cache writes: UNLOGGED vs regular table (16 clients, 200-byte values)"
for kind in logged unlogged; do
  U=$([ $kind = unlogged ] && echo UNLOGGED || echo "")
  $P -c "DROP TABLE IF EXISTS kv_$kind" -c "CREATE $U TABLE kv_$kind (k text PRIMARY KEY, v text NOT NULL)"
  $P -c "CHECKPOINT"; m=$(walmark)
  echo "table=$kind"; pgb -c 16 -j 4 -T $T -f cache_ins_$kind.sql
  echo "WAL written: $(waldiff $m)"
done
fi

if want 4; then
echo; echo "## 4. Advisory locks: 'max 100 seats', 16 clients x 50 attempts"
for mode in race lock; do
  $P -c "DROP TABLE IF EXISTS seats" -c "CREATE TABLE seats (id bigserial PRIMARY KEY, taken_by int)"
  pgbench -n -c 16 -j 4 -t 50 -f seats_$mode.sql >/dev/null 2>&1
  echo "mode=$mode seats sold: $($A -c 'SELECT count(*) FROM seats')"
done
echo "lock+unlock on random keys"; pgb -c 16 -j 4 -T $T -f advisory_cycle.sql
fi

if want 5; then
echo; echo "## 5. Full-text search, 1M messages x 12 words (Zipf-like vocabulary of 5000 words)"
$P -c "DROP TABLE IF EXISTS messages" \
   -c "CREATE TABLE messages (id bigint PRIMARY KEY, body text NOT NULL)" \
   -c "SELECT setseed(0.42)" \
   -c "INSERT INTO messages
       SELECT g, (SELECT string_agg('w' || floor(5000 * power(random(), 3))::int, ' ')
                  FROM generate_series(1, 12) WHERE g > 0)
       FROM generate_series(1, 1000000) g" \
   -c "ALTER TABLE messages ADD COLUMN tsv tsvector GENERATED ALWAYS AS (to_tsvector('simple', body)) STORED" \
   -c "VACUUM ANALYZE messages"
$A -c "SELECT 'rows with w4321: '||count(*) FROM messages WHERE tsv @@ 'w4321'::tsquery"
$A -c "SELECT 'rows with w3: '||count(*) FROM messages WHERE tsv @@ 'w3'::tsquery"
echo "ILIKE, no index (rare word)";  timed3 "SELECT count(*) FROM messages WHERE body ILIKE '% w4321 %' OR body ILIKE 'w4321 %' OR body ILIKE '% w4321'"
echo "tsvector, no index";          timed3 "SELECT count(*) FROM messages WHERE tsv @@ 'w4321'::tsquery"
$P -c "CREATE INDEX messages_tsv ON messages USING gin (tsv)"
$A -c "SELECT 'GIN index size: '||pg_size_pretty(pg_relation_size('messages_tsv'))||'  table: '||pg_size_pretty(pg_table_size('messages'))"
echo "tsvector + GIN (rare word)";   timed3 "SELECT count(*) FROM messages WHERE tsv @@ 'w4321'::tsquery"
echo "tsvector + GIN, two words AND"; timed3 "SELECT count(*) FROM messages WHERE tsv @@ 'w4321 & w12'::tsquery"
echo "top 10 by ts_rank, rare word"; timed3 "SELECT id FROM messages WHERE tsv @@ 'w4321'::tsquery ORDER BY ts_rank(tsv, 'w4321'::tsquery) DESC LIMIT 10"
echo "top 10 by ts_rank, common word"; timed3 "SELECT id FROM messages WHERE tsv @@ 'w3'::tsquery ORDER BY ts_rank(tsv, 'w3'::tsquery) DESC LIMIT 10"
fi

if want 6; then
echo; echo "## 6. JSONB documents, 1M rows"
$P -c "DROP TABLE IF EXISTS docs" \
   -c "CREATE TABLE docs (id bigint PRIMARY KEY, doc jsonb NOT NULL)" \
   -c "SELECT setseed(0.42)" \
   -c "INSERT INTO docs SELECT g, jsonb_build_object(
          'type', (ARRAY['order','refund','signup','login'])[1 + floor(random()*4)::int],
          'user', jsonb_build_object('id', g % 50000,
                                     'country', (ARRAY['IT','DE','FR','US','ES'])[1 + floor(random()*5)::int],
                                     'plan', CASE WHEN random() < 0.2 THEN 'pro' ELSE 'free' END),
          'tags', to_jsonb(ARRAY['t' || floor(random()*200)::int, 't' || floor(random()*200)::int]),
          'amount', round((random()*500)::numeric, 2))
       FROM generate_series(1, 1000000) g" \
   -c "VACUUM ANALYZE docs"
Q1="SELECT count(*) FROM docs WHERE doc @> '{\"user\":{\"id\":12345}}'"
Q2="SELECT count(*) FROM docs WHERE doc @> '{\"user\":{\"country\":\"IT\",\"plan\":\"pro\"},\"type\":\"refund\"}'"
Q3="SELECT count(*) FROM docs WHERE doc @> '{\"tags\":[\"t7\"]}'"
Q4="SELECT count(*) FROM docs WHERE (doc->>'amount')::numeric > 499"
for q in "$Q1" "$Q2" "$Q3" "$Q4"; do echo "matches: $($A -c "$q")"; done
echo "no index: user id / 3 keys / tag / amount range"
for q in "$Q1" "$Q2" "$Q3" "$Q4"; do timed3 "$q"; done
$P -c "CREATE INDEX docs_ops ON docs USING gin (doc)"
$P -c "CREATE INDEX docs_path ON docs USING gin (doc jsonb_path_ops)"
$A -c "SELECT 'jsonb_ops: '||pg_size_pretty(pg_relation_size('docs_ops'))||'  jsonb_path_ops: '||pg_size_pretty(pg_relation_size('docs_path'))||'  table: '||pg_size_pretty(pg_table_size('docs'))"
$P -c "DROP INDEX docs_ops" -c "ANALYZE docs"
echo "GIN jsonb_path_ops: user id / 3 keys / tag / amount range"
for q in "$Q1" "$Q2" "$Q3" "$Q4"; do timed3 "$q"; done
echo "amount range with an expression index"
$P -c "CREATE INDEX docs_amount ON docs (((doc->>'amount')::numeric))" -c "ANALYZE docs"
timed3 "$Q4"
fi

if want 7; then
echo; echo "## 7. Retention: DELETE one day vs DROP one partition (10 days x 1M rows)"
$P -c "DROP TABLE IF EXISTS ev_flat, ev_part" \
   -c "CREATE TABLE ev_flat (ts timestamptz NOT NULL, payload text NOT NULL)" \
   -c "CREATE INDEX ON ev_flat (ts)" \
   -c "CREATE TABLE ev_part (ts timestamptz NOT NULL, payload text NOT NULL) PARTITION BY RANGE (ts)"
for d in $(seq 1 10); do
  $P -c "CREATE TABLE ev_part_$d PARTITION OF ev_part FOR VALUES FROM ('2026-11-01'::date + $((d-1))) TO ('2026-11-01'::date + $d)"
done
$P -c "CREATE INDEX ON ev_part (ts)"
$P -c "INSERT INTO ev_flat SELECT '2026-11-01'::timestamptz + (g * interval '86.4 ms'), repeat('x', 100) FROM generate_series(0, 9999999) g" \
   -c "INSERT INTO ev_part SELECT * FROM ev_flat" -c "VACUUM ANALYZE ev_flat" -c "VACUUM ANALYZE ev_part" -c "CHECKPOINT"
$A -c "SELECT 'flat table size before: '||pg_size_pretty(pg_total_relation_size('ev_flat'))"
m=$(walmark); echo "DELETE oldest day from flat table"; timed -c "DELETE FROM ev_flat WHERE ts < '2026-11-02'"; echo "WAL: $(waldiff $m)"
$A -c "SELECT 'flat table size after DELETE: '||pg_size_pretty(pg_total_relation_size('ev_flat'))"
timed -c "VACUUM ev_flat" | sed 's/^/VACUUM /'
$A -c "SELECT 'flat table size after VACUUM: '||pg_size_pretty(pg_total_relation_size('ev_flat'))"
$P -c "CHECKPOINT"; m=$(walmark); echo "DETACH + DROP oldest partition"
timed -c "ALTER TABLE ev_part DETACH PARTITION ev_part_1" -c "DROP TABLE ev_part_1"; echo "WAL: $(waldiff $m)"
fi

if want 8; then
echo; echo "## 8. Row-level security: policy vs hand-written WHERE (2M invoices, 1000 tenants)"
$P -c "DROP TABLE IF EXISTS invoices" -c "DROP ROLE IF EXISTS app_user" \
   -c "CREATE ROLE app_user LOGIN" \
   -c "CREATE TABLE invoices (id bigint PRIMARY KEY, tenant_id int NOT NULL, amount numeric(10,2) NOT NULL)" \
   -c "INSERT INTO invoices SELECT g, 1 + (g % 1000), (random()*1000)::numeric(10,2) FROM generate_series(1,2000000) g" \
   -c "CREATE INDEX ON invoices (tenant_id)" -c "VACUUM ANALYZE invoices" \
   -c "ALTER TABLE invoices ENABLE ROW LEVEL SECURITY" \
   -c "CREATE POLICY tenant_isolation ON invoices USING (tenant_id = current_setting('app.tenant_id', true)::int)" \
   -c "GRANT SELECT ON invoices TO app_user"
echo "owner (RLS bypassed), explicit WHERE"; pgb -c 16 -j 4 -T $T -f rls_where_tx.sql
echo "app_user, policy only";                PGUSER=app_user pgb -c 16 -j 4 -T $T -f rls_policy.sql
echo "app_user, tenant not set:"; PGUSER=app_user $A -c "SELECT count(*) FROM invoices"
echo "app_user plan:"; PGUSER=app_user psql -X -c "BEGIN" -c "SELECT set_config('app.tenant_id','7',true)" -c "EXPLAIN SELECT count(*) FROM invoices" -c "COMMIT" | grep -E "Scan|Cond|Filter"
fi
Enter fullscreen mode Exit fullscreen mode

notify_latency.py (click to expand)
# LISTEN/NOTIFY: end-to-end latency, rollback, and same-payload dedup.
# Needs: pip install "psycopg[binary]"
import os, sys, time, threading, statistics, psycopg

DSN = os.environ.get("DSN", "dbname=postgres user=postgres host=/var/run/postgresql")
N = int(sys.argv[1]) if len(sys.argv) > 1 else 10000

got = []
def listen(stop):
    with psycopg.connect(DSN, autocommit=True) as c:
        c.execute("LISTEN bench")
        ready.set()
        for n in c.notifies(timeout=None, stop_after=None):
            if n.payload == "STOP":
                break
            got.append((time.perf_counter(), n.payload))

ready = threading.Event()
t = threading.Thread(target=listen, args=(None,)); t.start(); ready.wait()

with psycopg.connect(DSN, autocommit=True) as s:
    # 1) latency: one NOTIFY per committed transaction
    for i in range(N):
        s.execute("SELECT pg_notify('bench', %s)", (f"{time.perf_counter()}",))
    time.sleep(1)
    lat = sorted((r - float(p)) * 1000 for r, p in got)
    print(f"latency over {len(lat)} notifications: p50={lat[len(lat)//2]:.3f} ms "
          f"p99={lat[int(len(lat)*0.99)]:.3f} ms max={lat[-1]:.3f} ms")
    got.clear()

    # 2) rolled-back transaction: nothing is delivered
    with s.transaction(force_rollback=True):
        s.execute("NOTIFY bench, 'rolled-back'")
    # 3) identical payloads in one transaction are folded into one
    with s.transaction():
        for _ in range(100):
            s.execute("NOTIFY bench, 'same'")
    time.sleep(1)
    print("rolled-back delivered:", sum(1 for _, p in got if p == "rolled-back"))
    print("100 identical NOTIFYs in one tx delivered:", sum(1 for _, p in got if p == "same"))
    s.execute("NOTIFY bench, 'STOP'")
t.join()
Enter fullscreen mode Exit fullscreen mode

the pgbench scripts (click to expand)

queue_skip.sql

WITH j AS (SELECT id FROM jobs ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED),
     d AS (DELETE FROM jobs USING j WHERE jobs.id = j.id RETURNING jobs.id)
INSERT INTO done SELECT id FROM d;
Enter fullscreen mode Exit fullscreen mode

queue_noskip.sql

WITH j AS (SELECT id FROM jobs ORDER BY id LIMIT 1 FOR UPDATE),
     d AS (DELETE FROM jobs USING j WHERE jobs.id = j.id RETURNING jobs.id)
INSERT INTO done SELECT id FROM d;
Enter fullscreen mode Exit fullscreen mode

cache_ins_logged.sql

INSERT INTO kv_logged (k, v) VALUES (md5(random()::text), repeat('x', 200));
Enter fullscreen mode Exit fullscreen mode

cache_ins_unlogged.sql

INSERT INTO kv_unlogged (k, v) VALUES (md5(random()::text), repeat('x', 200));
Enter fullscreen mode Exit fullscreen mode

seats_race.sql

INSERT INTO seats (taken_by) SELECT :client_id WHERE (SELECT count(*) FROM seats) < 100;
Enter fullscreen mode Exit fullscreen mode

seats_lock.sql

BEGIN;
SELECT pg_advisory_xact_lock(42);
INSERT INTO seats (taken_by) SELECT :client_id WHERE (SELECT count(*) FROM seats) < 100;
COMMIT;
Enter fullscreen mode Exit fullscreen mode

advisory_cycle.sql

\set k random(1, 100000)
SELECT pg_advisory_lock(:k);
SELECT pg_advisory_unlock(:k);
Enter fullscreen mode Exit fullscreen mode

rls_where_tx.sql

\set t random(1, 1000)
BEGIN;
SELECT set_config('app.tenant_id', :t::text, true);
SELECT count(*), sum(amount) FROM invoices WHERE tenant_id = :t;
COMMIT;
Enter fullscreen mode Exit fullscreen mode

rls_policy.sql

\set t random(1, 1000)
BEGIN;
SELECT set_config('app.tenant_id', :t::text, true);
SELECT count(*), sum(amount) FROM invoices;
COMMIT;
Enter fullscreen mode Exit fullscreen mode

Which service did Postgres replace in your stack? And which one did you have to bring back?

Top comments (0)