Back to Blog

Before You Reach for Redis, Kafka, and Elasticsearch: How Much Can PostgreSQL Handle Alone?

PostgreSQL can consolidate more of an application stack than many teams expect. Learn where JSONB, SQL queues, search, vectors, PostGIS, partitioning, and row-level security fit, and where specialist tools still win.

Sebastian Tekieli

Chief AI Agents Officer and software engineer

LinkedIn
Developerarchitecture26 min read

Modern backend architecture can become a subscription-management simulator. A product starts with one transactional database. Then comes a cache, a broker, a search cluster, an analytics store, a vector database. Every one of them solved a real problem on the day it arrived. Every one also brought a bill, an access model, a backup policy, an on-call rotation, and another copy of your data.

The expensive part is rarely the first integration. It is keeping all of those systems telling the same story. A customer record changes in PostgreSQL, then has to reach the search index, the queue, the analytics store, and the embedding pipeline. Six months later a bug report asks why five views of the same customer disagree, and answering it takes a week.

There is a cheaper question to ask first. PostgreSQL is already the transactional source of truth. Can it carry this requirement well enough that the second copy never gets built? Not forever, and not for everything. But in an ordinary product it reaches considerably further than the label “the SQL database” suggests.

So the decision is not “can PostgreSQL technically do this?” It can usually do something. The real decision has two parts: is one transactionally consistent system simpler and fast enough today, and has the team named the signal that will make specializing worth it tomorrow?

QuestionPostgreSQL-first answerSignal to add a specialist
Durable background workKeep product jobs with their transactional data first.Ordered replay, long retention, fan-out, independently scaled consumers, or very high sustained ingestion.
SearchStart with built-in full-text search and typo matching for product search.Complex relevance operations, large-scale log analytics, or a separate search availability target.
Semantic retrievalKeep vectors with documents when relational filters define relevance.Dataset, latency, isolation, or index-management requirements exceed the database operating envelope.
Event history and dashboardsUse partitions, BRIN, and precomputed summaries for bounded product analytics.A warehouse-style workload competes with transactions or needs a separate governance and compute model.
CachingPrefer indexes, query design, and a measured read path before another dependency.Sub-millisecond in-memory access or cache-specific coordination is the actual requirement.

Redis, Kafka, RabbitMQ, Elasticsearch and a warehouse are not bad choices. Adding one before anyone can say what it is supposed to fix is the bad choice.

Documents without a second database: JSONB and GIN

The trigger is usually a partner integration. A payload arrives with fifteen fields nobody on the team designed, and its shape will change next quarter. Two proposals follow.

The first: add those fifteen columns to the core table. By the third partner it carries forty of them, each populated for exactly one customer and empty for everyone else. Nobody can say any more which ones are required, and every new business rule needs checking against columns that belong to somebody else.

The second: run MongoDB alongside PostgreSQL. That one costs more than it looks. From then on the team keeps two databases consistent, backs up both, and answers “which one is right?” every time two numbers disagree.

PostgreSQL has an answer for data that still belongs to a relational entity: JSONB.

JSONB stores the document in a decomposed binary format. Writes cost slightly more than plain JSON text, but reads stop reparsing the document every time, and the contents can be indexed. Two behaviours surprise people: JSONB does not preserve key order, and for a duplicate key it keeps only the last value. Both are set out in the JSON type documentation.

The model that works is a split, not a migration. Ordinary columns hold anything the business reasons about: identity, money, dates, permissions. JSONB holds what is still settling, such as partner payloads and variable metadata. Foreign keys and transactions stay, and the schema still has room to move.

Indexes follow the same logic. A GIN index makes “does this document contain X” queries practical, and it is not free, because a broad JSONB index stores a great deal. When one nested path carries most of the queries, an index on just that expression is smaller and closer to how the data is actually read. PostgreSQL sets out both trade-offs in its JSONB indexing guidance.

The line to hold is this: JSONB is for documents that take part in a transaction and get filtered next to ordinary tables. It is not a place to hide the domain model. Large JSONB updates lock the whole row, and an attribute the product queries every day has earned a real column with a real constraint.

A transactional work queue: FOR UPDATE SKIP LOCKED

Emails, invoices, webhooks, exports, retries. None of them belong inside an HTTP request, so a broker joins the stack. Usually before anyone checks whether a table would do.

One question settles it. Must the job and the business change it belongs to either both happen or both not happen? If a signup must always produce a welcome email, and a refund must always produce a ledger entry, then the job wants to sit in the same transaction as the change. A broker cannot offer that, because it lives outside the database.

A jobs table can. A worker picks a ready row, locks it, marks it running, and gets to work. Another worker steps over the locked row and takes the next one. PostgreSQL is precise about the mechanism in the SKIP LOCKED documentation: rows that cannot be locked immediately are skipped, which produces an inconsistent view of the table. That makes it wrong for ordinary reads and right for exactly this case, a queue-like table with several consumers.

The caveat matters more than the SQL. The database hands over atomic claiming and nothing else. The application still owns idempotency, retries, and a visibility timeout so that a crashed worker’s job returns to the queue. And when a committed transaction has to produce an effect outside the database, write it to an outbox table and publish from there. A successful commit is not proof that the email left the building.

A SQL queue fits moderate product work that is coupled to the data it changes. A broker or streaming platform wins when the product needs ordering within partitions, event history it can replay, wide fan-out to many consumers, or ingestion that must not compete with the database serving customers.

Search before a search cluster: full-text search and pg_trgm

A search box in a product is not a search problem yet. It becomes one later, and the mistake is buying for that later state on day one.

PostgreSQL ships full-text search. It breaks text into normalized lexemes, the dictionary form of each word, and matches structured queries against them. The full-text search introduction covers the parser, the dictionaries, and the tsvector and tsquery types the team will actually write against.

For an article library, a catalogue, a knowledge base, or content scoped to one account, this deletes an entire moving part: the pipeline that copies documents into a separate index, and the bugs that arrive with it. Document, permission check, query, and ranking all stay in one consistent system. Filters get easy too, because they are just SQL: matching documents, for this organization, in this status, from last quarter.

What it does not provide is typo tolerance. For that PostgreSQL supplies pg_trgm, which compares text as overlapping groups of three characters and adds GiST and GIN operator classes for fast similar-string lookup. It handles a misspelled surname and a half-typed identifier well.

This is not a claim that PostgreSQL search equals a search cluster. A specialized engine earns its place when ranking becomes a product feature in its own right: synonym pipelines, faceting at scale, real autocomplete, indexing across several systems, or log exploration. Until that day, having no index to keep in sync is often the better performance story.

Keep semantic filters close to the data: pgvector

Vector search revived an old integration problem in new clothes. The embedding lives in a vector database. Ownership, publication status, tenant, time range, and permissions live in PostgreSQL. Every useful query needs both, so the application asks each one separately and tries to stitch the answers together.

pgvector is a third-party extension rather than part of PostgreSQL core, and it keeps the vector beside the row it describes. It supports exact nearest-neighbor search plus approximate HNSW and IVFFlat indexes. That placement pays off on the query products actually run: find related documents, but only for this customer, only published ones, only from last week. One query, one permission model, one answer.

The word approximate is doing real work in that sentence. Approximate indexes buy speed with recall, the share of true matches that actually come back. HNSW uses more memory and builds more slowly than IVFFlat, and usually gives a better speed-to-recall deal. Filtered queries need deliberate tuning, because the filter can be applied after the index scan and leave fewer rows than expected. The project documents filtering and iterative scans in detail.

Choose pgvector when vector retrieval is one clause in a relational query, and when the team will benchmark its own corpus, filters, recall target, and build time instead of trusting a blog post. Choose a dedicated vector service when that workload has scaling, isolation, or multi-region requirements of its own. An extension should spare a team premature architecture, not capacity planning.

Spatial data belongs somewhere: PostGIS

Location data tends to get its own system before the product has a geography problem. PostGIS adds spatial types, functions, and spatial indexes to PostgreSQL. Coordinates can then live on the business records that own them: a store, a service area, a delivery route.

That collapses a query most products eventually need. Find available providers inside this service area, respecting availability, tenant, and business rules. A spatial index narrows the candidates, then the exact geometric test and ordinary SQL filters finish the job. No export, no second copy, no reconciliation.

PostGIS will not choose a coordinate system, validate geometry, or explain what distance means on a sphere. Those stay with the team. A dedicated geospatial pipeline still makes sense for map tiles, global routing, raster processing, or when geographic analysis is the product itself. For the geography inside a normal product, PostGIS is usually the capability the team was about to buy elsewhere.

Events and dashboards: partitioning, BRIN, and materialized views

An append-only table with a timestamp column starts the warehouse conversation early. Sometimes correctly. More often the need is smaller: predictable retention, fast queries over recent ranges, and three dashboards nobody wants to maintain.

Declarative partitioning splits one logical table into physical pieces. When a query’s predicates line up with the partition key, the planner can skip whole partitions during planning and again during execution; the partitioning documentation sets out the rules. Removing last year’s data becomes dropping a partition instead of a DELETE that runs all weekend.

BRIN suits very large tables where a column correlates with where rows physically sit, which is exactly what an append-only timestamp does. Instead of one index entry per row it summarizes ranges of pages, so it stays small. The whole benefit rests on that correlation: timestamps inserted in random order break the assumption and the index stops helping.

Materialized views solve a different cost, the same expensive aggregate recomputed all day. They store the result of a query and refresh on command. Given a qualifying unique index, REFRESH MATERIALIZED VIEW CONCURRENTLY lets people keep reading the view while it rebuilds. Three limits are worth knowing first: it never schedules itself, refreshing costs real resources, and only one refresh of a given view can run at a time.

Together these cover product dashboards, operational reporting, and event data with a clear retention policy. A warehouse, lakehouse, or time-series platform becomes the right answer once one of three things happens. Analytical scans start threatening transaction latency. Several teams need compute that does not fight over one server. Or analytics grows a lifecycle and governance model of its own.

APIs and authorization: RLS is a boundary, not an entire backend

Some controllers exist only to turn an HTTP request into one database operation. Written by hand, forty of them are forty chances to forget a permission check.

Tools remove that work. PostgREST is a standalone web server that exposes a PostgreSQL database as a REST API, driven by the constraints and permissions already in the schema. pg_graphql mirrors the SQL schema in GraphQL and derives what each caller can see from PostgreSQL permissions; the Supabase documentation explains that model.

Neither means the backend disappears. They fit where the database shape is deliberately the API shape. Someone still has to own the policy model, the migrations, and the error contract, because generating endpoints does not generate that ownership. Generate the boring half, and keep the half that carries risk.

Row-level security is the primitive underneath. Turn it on and ordinary access requires a policy: with no policy, PostgreSQL denies by default, which is the right direction for a mistake to fail in. The RLS documentation also lists exceptions that deserve deliberate handling, including table owners and roles with BYPASSRLS. It is worth being clear about what RLS is not. It is authorization at the data boundary, not encryption, not identity verification, not input validation, and not a reason to stop reviewing who holds privileged connections.

Its real value concerns the query nobody has written yet. When a new endpoint appears in a hurry, the policy is already standing between it and another tenant’s rows.

Fewer services do not eliminate vendor lock-in

Consolidating on PostgreSQL cuts the number of vendors and the number of places where data can drift apart. It does not make the choices portable.

A managed PostgreSQL service brings its own availability model, its own restore procedure, and its own price list. It also decides which extensions exist and when the major version changes. Some of its best features are not PostgreSQL at all: Neon offers database branching, which is a platform capability rather than something a team can take with it. Generated APIs and extensions become architectural dependencies just as surely as a vendor SDK does. The question is the one from the vendor lock-in audit: what would replacing this layer actually take, and has anyone rehearsed it?

“Keep it” is a perfectly good answer. A managed service is often the right trade, and running PostgreSQL in-house has a price of its own. What matters is holding on to the parts that keep the decision reversible: schema, migrations, backups, roles, and the operational knowledge to use them.

Start compactly, specialize deliberately

None of this argues for a database-shaped monolith that swallows every concern. It argues for making distributed systems earn their way in.

Start from the relational source of truth. Use the capabilities above where they delete a copy of the data or keep a transaction intact. Measure what the workload actually does. Then write the threshold down before it is needed, as a number: queue lag in seconds, query time at p95, a recall figure the product can live with, months of retention. When the number is crossed, add the specialist, and add it because it solves a constraint the team can name.

For a CTO that means a smaller surface to operate and a smaller bill to explain. For the engineers it means fewer systems to keep in agreement, and fewer incidents that begin with two systems disagreeing about a fact. For the business it means an architecture that grows into the scale the product actually reaches, rather than the scale someone imagined on a whiteboard in year one.

Want to discuss this topic?

Let us turn the idea into a practical architecture and implementation plan.

Book a Consultation