'Just Use Postgres' in Numbers: Benchmarking PostgreSQL as a Cache, Job Queue, Search Engine, and Pub/SubLongread · digest for December 2
Editorial risograph poster on a graphite background: a single modular PostgreSQL 17 unit combining four compartments—Cache, Queue, Search, and Pub/Sub.
Longread6 sections≈ 17 min

'Just Use Postgres' in Numbers: Benchmarking PostgreSQL as a Cache, Job Queue, Search Engine, and Pub/Sub

When you spin up a new backend, you almost automatically draw the standard Docker Compose diagram: PostgreSQL for core tables, Redis for caching and sessions, RabbitMQ for background jobs, and Elasticsearch for catalog search. It looks solid until a broker crashes at 3 a.m. or your search cluster runs out of memory. At the opposite end sits the popular "just use Postgres" advice: put everything in one database and skip the extra containers. It sounds tempting, yet in practice that advice usually rests on personal anecdotes rather than measurements.

Engineer Aaron Yong decided to test the idea head-on and published the open-source pg-stack-benchmark suite under the MIT license. He spun up two identical PostgreSQL 17 containers, pointed Grafana k6 at them, and ran four common workloads: caching, a background job queue, full-text search, and pub/sub event delivery. At the end, he turned on all four roles at the same time on one database to measure the real cost of that consolidation.

Let's state the scope clearly upfront. The benchmark doesn't pit PostgreSQL against Redis or Elasticsearch; it compares naive PostgreSQL against tuned PostgreSQL on identical hardware. That framing is more honest for daily engineering: it shows how much performance is already sitting inside your database without adding a single new service, and where that magic starts to fade.

Test Setup and Tuning postgresql.conf for SSDs

To keep numbers free from laptop throttling or backend differences, the test harness is strictly symmetrical. Docker Compose runs two identical PostgreSQL 17 containers, each capped at 2 CPUs and 2 GB of RAM. In front of them sits one Express and TypeScript service on Node.js 20+: port 3001 talks to the baseline instance (baseline), and port 3002 talks to the tuned one (modded), toggled by a single PG_MODE environment variable.

Load comes from grafana/k6:0.57.0 in two modes. First comes a moderate run of 100 to 500 virtual users (VU) with normal pauses to mimic real traffic. Then a stress test fires 500 to 1,000 virtual users with zero pauses between requests (no sleep) to push the database to its limit. Search tables start pre-populated with 10,000 articles.

Before running a single test, both containers received the same postgresql.conf tuning. That is a crucial step many teams skip when booting a default Postgres image.

# Memory allocation for a 2 GB RAM container
shared_buffers = 512MB        # 25% of available RAM
effective_cache_size = 1536MB # 75% of RAM — hint for the query planner
work_mem = 16MB               # memory per sort or hash table operation

# Planner settings for modern SSDs
random_page_cost = 1.1        # default 4.0 assumes spinning HDDs
effective_io_concurrency = 200 # allow concurrent reads from SSD

PostgreSQL defaults still assume mechanical hard drives from the early 2000s. When random_page_cost is 4.0, the planner thinks jumping through an index is four times costlier than scanning a table end-to-end. As a result, it often ignores a perfectly good index and triggers a full sequential scan.

Setting it to 1.1 tells the planner a simple truth about modern SSDs: random reads are nearly as fast as sequential ones. Meanwhile, shared_buffers gives a quarter of RAM to Postgres's internal page cache, and effective_cache_size estimates how much data sits in the OS page cache. Without those five lines, any talk of a fast PostgreSQL starts with the handbrake on.

Throughout the benchmarks below, you'll see two latency metrics: P50 and P95. The first is the median—half of all requests finish faster than this number. The second is the 95th percentile, which 95% of requests meet while the slowest 5% exceed it. Averages easily hide spikes, whereas P95 immediately exposes tail-latency choking.

Benchmark 1: Caching with UNLOGGED Tables Instead of Redis

Every write to a standard PostgreSQL table goes through the WAL (Write-Ahead Log). The database flushes the change to this log on disk before marking the operation complete. That WAL is what saves your orders and payments if someone pulls the power cord.

For a cache, that armor is overkill. If the server crashes and the cache empties out, your app can simply recompute values from the main tables. In the PostgreSQL 17 CREATE TABLE documentation, the UNLOGGED modifier disables WAL writes and removes the main bottleneck on writes.

-- Tuned option: cache table without WAL writes
CREATE UNLOGGED TABLE cache_entries (
  key TEXT PRIMARY KEY,
  value JSONB NOT NULL,
  expires_at TIMESTAMPTZ
);

-- Baseline option: same schema with standard WAL logging
CREATE TABLE cache_entries (
  key TEXT PRIMARY KEY,
  value JSONB NOT NULL,
  expires_at TIMESTAMPTZ
);

The schema takes five lines and needs zero extensions. The key sits in TEXT PRIMARY KEY, the payload lives in binary JSONB, and TTL is tracked in expires_at (expired rows are periodically cleaned up by pg_cron in the benchmark).

Under a moderate load of 200 virtual users, the regular table hit a 1.87 ms median and 6.00 ms P95 at 1,754 requests per second. Switching to UNLOGGED dropped the median to 1.71 ms and P95 to 5.24 ms at 1,760 requests per second. That 13% gain looks modest, yet you get it for a single keyword in CREATE TABLE.

Things get more interesting when 1,000 virtual users hammer the database with zero pauses.

Cache under 1,000 VU stress load: regular table vs. UNLOGGED

The relative lead stays locked around 12–13% even at the container's ceiling. The reason is straightforward: skipping the WAL saves a fixed amount of disk I/O per write, whether you're sending a hundred writes per second or eight thousand. Over the same stress window, UNLOGGED processed 765,934 requests at 8,062 req/s, compared to 728,021 requests at 7,663 req/s for the logged table—nearly 38,000 extra requests served for free.

Now for the trade-offs. Skipping WAL brings two hard limits. First, after an unclean crash, PostgreSQL automatically truncates the entire UNLOGGED table (data survives normal restarts). Second, UNLOGGED tables never replicate to standby read replicas, because Postgres replication streams the WAL.

And what about Redis? If you have a hot path requiring sub-millisecond responses (real-time ad bidding or gaming leaderboards), an UNLOGGED table won't beat an in-memory store. You also miss Redis data structures like sorted sets, HyperLogLog, and streams. But for a typical web app where a user won't notice the difference between 2 ms and 5 ms, one WAL-free table cleanly crosses Redis off your infrastructure diagram.

Benchmark 2: Job Queues with FOR UPDATE SKIP LOCKED and Partial Indexes

Background jobs tell a similar story. Welcome emails, PDF generation, image thumbnails—you want these off the HTTP request path. It feels like RabbitMQ or Redis is mandatory so multiple workers don't fight over the same rows.

PostgreSQL solves that race with SELECT ... FOR UPDATE SKIP LOCKED, covered in the PostgreSQL 17 SELECT docs. When worker one selects a row with FOR UPDATE, Postgres locks it until the transaction ends. When worker two looks for the next job, it sees the lock and, thanks to SKIP LOCKED, silently steps over it and grabs the second row. No duplicates, no waiting. If worker one crashes mid-job, its transaction rolls back, the lock clears, and the job returns to the pool automatically.

The second key piece is a partial index—an index with a WHERE clause that only tracks a slice of rows. In a job queue, you only care about fresh pending rows; completed jobs don't belong in the index.

-- Job queue table
CREATE TABLE job_queue (
  id SERIAL PRIMARY KEY,
  payload JSONB NOT NULL,
  status TEXT NOT NULL DEFAULT 'pending',
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Partial index: tracks only pending jobs
-- Once status changes, the row leaves the index
CREATE INDEX idx_pending_jobs ON job_queue (created_at)
WHERE status = 'pending';

-- Atomic job claim: select and update status in one query
UPDATE job_queue
SET status = 'processing'
WHERE id = (
  SELECT id
  FROM job_queue
  WHERE status = 'pending'
  ORDER BY created_at
  LIMIT 1
  FOR UPDATE SKIP LOCKED
)
RETURNING *;

In a single statement, the subquery finds the oldest unclaimed job while skipping locked rows, and the outer UPDATE flips it to processing and hands the payload back via RETURNING *.

The benchmark ran 100 producers and 50 consumers for 60 seconds. A regular full index scored 1.90 ms P50, 5.01 ms P95, and 1,053 req/s. The partial index scored 1.81 ms P50, 5.28 ms P95, and 1,052 req/s—basically a tie.

It's easy to misread that tie and think partial indexes don't matter. In reality, a 60-second test wasn't long enough to pile up millions of completed jobs. In production, completed job history bloats a normal index to gigabytes until it falls out of memory. A partial index with WHERE status = 'pending' stays a few kilobytes even with millions of old rows, because it only holds active work.

There's little reason to build retries, scheduling, and dead-letter handling around this pattern from scratch—mature libraries already wrap SKIP LOCKED. For Node.js and TypeScript, pg-boss (MIT license, over 4,000 GitHub stars) gives you delayed retries, rate limiting, debouncing, dead-letter queues (DLQ), cron schedules, and adapters for Prisma, Kysely, Knex, and Drizzle. For Go (with clients for TypeScript, Java, Ruby, and Rust), River (MPL-2.0, nearly 6,000 stars) stands out with InsertTx, which enqueues a job inside the same DB transaction as your business write. Order saved? Job queued. Transaction rolled back? No ghost job left behind.

River — a background job queue built on PostgreSQL and SKIP LOCKED (Source: riverqueue.com)

Where is the ceiling? PostgreSQL handles "run this job once" workflows effortlessly. Once you need complex message routing (broadcasting one event to ten independent services via fan-out or topic exchanges) or consumer groups that replay yesterday's event stream, it's time for RabbitMQ or Kafka.

Benchmark 3: Full-Text Search with tsvector + GIN vs. ILIKE

When you need a quick search bar for articles or products, it's tempting to write WHERE title ILIKE '%query%'. Because of the leading % wildcard, a standard B-tree index can't help—the match might be in the middle of a word. With two hundred rows, everything feels instant. Things fall apart once the table grows and dozens of users search at the same time.

Postgres ships a built-in engine for full-text search in PostgreSQL 17 with zero external plugins. It rests on two pieces. First is the tsvector data type, which stores text pre-split into normalized word lexemes (stripping stop words and stemming endings). Second is a GIN (Generalized Inverted Index). Conceptually, it works like an Elasticsearch index: it maps a dictionary of words to the rows where each word appears.

-- Articles table with a dedicated column for search tokens
CREATE TABLE articles (
  id SERIAL PRIMARY KEY,
  title TEXT NOT NULL,
  body TEXT NOT NULL,
  search_vector tsvector
);

-- Inverted GIN index on the token column
CREATE INDEX idx_search ON articles USING GIN (search_vector);

-- Function and trigger: refresh tokens on every insert or update
CREATE OR REPLACE FUNCTION update_search_vector()
RETURNS trigger AS $$
BEGIN
  NEW.search_vector := to_tsvector(
    'english',
    COALESCE(NEW.title, '') || ' ' || COALESCE(NEW.body, '')
  );
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trg_search
BEFORE INSERT OR UPDATE ON articles
FOR EACH ROW EXECUTE FUNCTION update_search_vector();

The trigger keeps search_vector updated automatically on inserts and edits (this benchmark uses the 'english' dictionary; Postgres also ships 'russian' and many others built in). Now compare two queries: naive ILIKE vs. indexed search ranked by relevance via ts_rank.

-- Baseline: full scan of all 10,000 articles
SELECT *
FROM articles
WHERE title ILIKE '%postgresql%'
   OR body ILIKE '%postgresql%';

-- Tuned: GIN index lookup with relevance ranking
SELECT
  id,
  title,
  ts_rank(
    search_vector,
    plainto_tsquery('english', 'postgresql')
  ) AS rank
FROM articles
WHERE search_vector @@ plainto_tsquery('english', 'postgresql')
ORDER BY rank DESC
LIMIT 20;

The moderate 500-VU test produced the biggest gap in the entire study. Naive ILIKE hit 101.83 ms at P95 (25.22 ms average, 561 req/s), while tsvector + GIN finished in 10.39 ms at P95 (3.76 ms average, 675 req/s). That's a 10x speedup in tail latency without an external service.

One interesting detail: on P50 median latency, naive ILIKE slightly beat the index—1.96 ms vs. 2.76 ms. Buffer caching explains why: when a small table fits entirely inside shared_buffers, a single sequential scan is fast. Once hundreds of concurrent queries scan all 10,000 articles at once, the cache churns and response times avalanche.

In the 500-VU no-sleep stress test, that avalanche buries the database.

Search under 500 VU no-sleep stress: ILIKE vs. tsvector + GIN

Under constant pressure, ILIKE collapses into one-second delays as every query scans the whole table and evicts neighbors from memory. GIN index lookups run in logarithmic time regardless of concurrency. Over the same stress window, tsvector served 129,679 requests (1,441 req/s) vs. 50,212 requests (558 req/s) for ILIKE—2.6x more throughput on the exact same hardware.

For a blog, admin panel, or small store catalog, this covers your needs with room to spare. Once you outgrow a single server and need sharded distributed search, advanced CJK morphological analyzers, or heavy faceted aggregations across dozens of filters, then it's time for Elasticsearch or OpenSearch.

Benchmark 4: Real-Time Events via LISTEN/NOTIFY

The fourth scenario is delivering events to subscribers—chat notifications or order status updates without refreshing the page. The naive database approach is polling: clients ask "anything new?" every second, wasting dozens of empty queries.

Postgres's built-in LISTEN and NOTIFY pair flips that model. Instead of polling, an AFTER INSERT trigger calls pg_notify, pushing the event to all subscribed connections right after the transaction commits.

-- Trigger broadcasts a notification when a new row is inserted
CREATE OR REPLACE FUNCTION notify_message()
RETURNS trigger AS $$
BEGIN
  PERFORM pg_notify(NEW.channel, NEW.payload::text);
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trg_notify
AFTER INSERT ON messages
FOR EACH ROW EXECUTE FUNCTION notify_message();

At first glance, the trigger looks like extra work on every INSERT, since the database now writes a row and emits a signal. Yet a 200-VU test showed the opposite. Polling scored 1.99 ms P50, 6.04 ms P95, and 1,116 req/s. LISTEN/NOTIFY dropped P50 to 1.65 ms and P95 to 4.80 ms, while edging throughput up to 1,131 req/s. Cutting network round-trips and reusing connections cleanly shaved 20% off P95 latency.

Still, LISTEN/NOTIFY has two sharp edges that can bite you in production.

Two hard limits of LISTEN/NOTIFY
  1. Payload limit is strictly under 8,000 bytes. The PostgreSQL 17 NOTIFY documentation spells out this ceiling for standard builds. If you need to pass a large JSON blob, store the record in a table and send only its short row ID through pg_notify.
  2. Incompatible with PgBouncer in transaction mode. Listening on a LISTEN channel requires a dedicated, long-lived TCP connection. In transaction pooling mode, PgBouncer lends a backend session only for a single BEGIN ... COMMIT block and immediately hands it to another client, breaking subscriptions. You must carve out a direct connection or a session mode pool for LISTEN.

As long as events stay small and you have a handful or a few dozen app servers listening, built-in pub/sub easily replaces Redis. If you need to fan out massive streams to hundreds of microservices behind strict connection pooling, a dedicated broker will save you headaches.

Combined Stress Test: What Happens When All Four Roles Run Together

Isolated benchmarks always look flattering because each feature runs alone while the rest sit idle. The real question for production apps is what happens when caching, queues, search, and pub/sub share the same CPU, RAM, and disk at the same time.

Aaron Yong ran a mixed workload combining all four scenarios on the same 2-CPU, 2-GB RAM containers. Here is what came back:

ConfigurationP50P95AverageRequests/sec
Baseline PostgreSQL1.65 ms5.24 ms2.17 ms1,424
PostgreSQL with all 4 features1.86 ms6.05 ms2.47 ms1,417

The picture flipped: under mixed load, the tuned setup ran roughly 15% slower than baseline at P95. There's no mystery here—the background costs added up. The instance was simultaneously updating GIN indexes on article edits, firing triggers on message inserts, and running pg_cron cleanup jobs. When tested in isolation, nobody noticed that background work; together, they elbowed each other for resources.

Even so, both setups stayed comfortably below 10 ms at P95 on a modest two-core container. For the vast majority of standard web apps, that speed leaves plenty of headroom. Just keep the 15% tax in mind: there's no free lunch, and one instance shares its CPU, RAM, and disk I/O pool between live transactions and background chores.

Pulling all measurements into a practical cheat sheet gives clear thresholds for when to stay on Postgres and when to split services out:

System roleWhen PostgreSQL 17 is enoughWhen to extract a dedicated service
Cache (UNLOGGED)Web app with 2–5 ms budget, ephemeral data okay to lose on crashSub-1 ms latency, millions of reads/sec, or Redis structures (sorted sets, HyperLogLog, streams)
Queue (SKIP LOCKED)Simple "process job once" pattern via pg-boss or RiverComplex routing (fan-out, topic exchanges), millions of msgs/sec, or stream replay (Kafka/RabbitMQ)
Search (tsvector + GIN)Catalog, blog, or internal admin up to tens or hundreds of thousands of rowsTerabytes of docs, sharded search, CJK analyzers, or heavy faceted analytics (Elasticsearch)
Pub/Sub (LISTEN/NOTIFY)Short notices under 8,000 bytes with direct DB connections availableHeavy payloads, hundreds of subscribers, or strict PgBouncer transaction mode

One properly tuned PostgreSQL 17 instance genuinely covers up to 80% of a startup or product backend's needs and saves your team from maintaining three to five extra services on day one. You ship faster with fewer failure points. And when traffic actually hits a ceiling, your own metrics will point to the exact role ready to move into Redis, Kafka, or Elasticsearch—instead of guessing upfront.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 9