No. 42Database9 min read2,315 words
Why we use PostgreSQL: as our default database
Why PostgreSQL is our default database for new web apps and SaaS: JSONB, full-text search, queues and row-level security in one system, and when to add more.
- Written by
- Lazy Devs
- Published
- Updated
- Sources
- Cited inline

Key takeaways · 05
The short version
- 01PostgreSQL is the best default database for most new web apps because one instance can be your relational store, document store, full-text search, job queue and vector store.
- 02Every extra database adds backups, upgrades, monitoring and failure modes; starting with one Postgres instance defers that operational cost until you have a measured reason to pay it.
- 03JSONB with a GIN index gives you document-style flexibility next to real foreign keys and constraints, so you rarely need a separate document database.
- 04Add a second system when you hit a specific, measured limit: Redis for caching and high-rate counters, a column store for heavy analytics, a dedicated search engine for advanced relevance tuning.
- 05Postgres is open source under a permissive licence, and every major cloud and many specialist providers host it, so you are not locked into one vendor.
On this page · 11
PostgreSQL is our default database because one boring, reliable system covers almost everything a new web app or SaaS product needs: relational data with real constraints, flexible JSON documents, full-text search, a job queue, row-level security and vector search. We add a second data store only when we hit a specific, measured limit. For most products, that day comes much later than people expect, if it comes at all.
Every new project comes with the same fork in the road: which database? The temptation is to match a fashionable tool to each shape of data, one store for documents, another for search, another for the queue. We have learned the lazy answer is usually right: start with Postgres, and only add a second system when Postgres genuinely cannot do the job. Here is the honest case, including when we do not follow it.
Why Postgres is the default that earns its keep
Postgres has roughly three decades of production use behind it, and it shows. It is fully transactional (ACID), its multi-version concurrency control lets readers and writers work without blocking each other, it has a mature query planner, and it is careful with your data when things go wrong. That alone rules out a surprising number of alternatives for anything touching money, accounts, or state you cannot reconstruct.
It is also open source under the permissive PostgreSQL Licence, and every major cloud offers it managed, alongside specialist hosts like Supabase and Neon. If a provider raises prices or disappoints you, you can take a standard dump and move. That matters more in year four than it does in week one.
But the main reason we reach for it first is range. A single Postgres instance can act as your relational store, document store, full-text search, job queue, pub/sub channel and vector index. Each of those is often a separate product in an architecture diagram. Collapsing them into one system means one backup strategy, one connection pool, one set of credentials, one thing to monitor at 3am, and transactions that span all of it.
JSONB: the document store you already have
People reach for a document database when their data is genuinely unstructured, or when they think it is. Postgres has a binary JSON type, jsonb, and it is indexable. You get schema flexibility where you want it and relational integrity where you need it, in the same table.
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id bigint NOT NULL REFERENCES users (id),
type text NOT NULL,
payload jsonb NOT NULL DEFAULT '{}'::jsonb,
created_at timestamptz NOT NULL DEFAULT now()
);
-- GIN index makes containment queries fast
CREATE INDEX events_payload_idx ON events USING gin (payload);
-- Completed checkout events over 100 in any currency
SELECT id, payload->>'currency' AS currency
FROM events
WHERE type = 'checkout'
AND payload @> '{"status": "completed"}'
AND (payload->>'amount')::numeric > 100;The @> containment operator uses the GIN index, so that query stays fast as the table grows. Meanwhile user_id is a real foreign key, so a deleted user cannot leave orphaned events. That blend, strict where it matters and loose where it does not, is hard to get from a pure document database.
A rule of thumb we follow: if you filter, join or sort on a JSON field constantly, promote it to a real column. JSONB is for the long tail of metadata, provider payloads and per-customer settings, not for your core domain. Our Postgres vs MongoDB comparison goes deeper on where each one fits.
Search without a search cluster
The reflex for search is to stand up Elasticsearch or OpenSearch. For most apps, that is a heavy second system to feed, sync and keep alive. Postgres full-text search covers the common cases: weighted ranking, stemming, phrase and prefix matching, all transactional and always consistent with your data.
ALTER TABLE articles
ADD COLUMN search tsvector
GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
setweight(to_tsvector('english', coalesce(body, '')), 'B')
) STORED;
CREATE INDEX articles_search_idx ON articles USING gin (search);
SELECT id, title, ts_rank(search, websearch_to_tsquery('english', $1)) AS rank
FROM articles
WHERE search @@ websearch_to_tsquery('english', $1)
ORDER BY rank DESC
LIMIT 20;The search column is a generated column, so it updates itself on every write. No background sync, no lag, no moment where search returns a row that was already deleted. Add the pg_trgm extension for typo-tolerant matching on names and titles. When you outgrow this (you will know, because you will be fighting relevance tuning, facets and synonyms), reach for a dedicated search engine then. Not on day one. Our guide to database indexing for app developers covers the GIN and trigram indexes that make this fast.
A queue is just a table with locking
This surprises people, so it is worth showing. You do not need a separate broker to process background jobs reliably. FOR UPDATE SKIP LOCKED lets many workers pull from the same table without stepping on each other.
-- One worker claiming the next available job
WITH next AS (
SELECT id
FROM jobs
WHERE status = 'pending'
AND run_at <= now()
ORDER BY run_at
FOR UPDATE SKIP LOCKED
LIMIT 1
)
UPDATE jobs j
SET status = 'running', attempts = attempts + 1, locked_until = now() + interval '5 minutes'
FROM next
WHERE j.id = next.id
RETURNING j.*;Because the claim and the status update happen in one statement, two workers never claim the same job. If a worker crashes mid-job, the row stays running and a sweeper resets it once locked_until passes. The best part is transactional enqueue: you insert the job in the same transaction as the order it belongs to, so a rolled-back order never sends a confirmation email.
For the job volumes most products actually see, this is plenty, and it lives in the same backup as everything else. LISTEN and NOTIFY can wake workers immediately instead of polling, and libraries like pg-boss and Graphile Worker package the whole pattern.
Security and multi-tenancy built in
Row-level security lets the database itself enforce which rows a user or tenant can see. A policy like "rows where tenant_id matches the current session's tenant" becomes a backstop under your application's own checks, so a forgotten WHERE clause does not leak one customer's data to another. It is the foundation of how Supabase exposes Postgres safely, and a pattern we use in multi-tenant architecture. If the term is new, start with what multi-tenancy is.
Add constraints, check constraints, exclusion constraints (no two bookings for the same room may overlap) and proper types like timestamptz, and a lot of bugs become impossible rather than merely unlikely.
Vectors and AI features
AI features usually need embeddings stored next to the data they describe. The pgvector extension adds a vector type and approximate nearest-neighbour indexes (HNSW and IVFFlat) to Postgres. You can filter by tenant, permissions and recency with ordinary SQL in the same query as the similarity search, which is awkward when vectors live in a separate system. For most product-scale retrieval, it is the simplest good option.
The lazy part is what you do not run
The real cost of a database is rarely the licence or the hosting bill. It is the operational surface. Every extra system is another upgrade path, another security advisory to read, another failure mode, another thing a new engineer must learn before they can ship. We treat each new piece of infrastructure as a standing tax on the whole team.
| Need | Typical extra system | The Postgres way |
|---|---|---|
| Core relational data | None | Tables, foreign keys, constraints |
| Flexible documents | Document database | jsonb with GIN indexes |
| In-app search | Search cluster | Full-text search and pg_trgm |
| Job queue | Message broker | SKIP LOCKED table, or pg-boss |
| Notifications between processes | Pub/sub service | LISTEN and NOTIFY |
| Embeddings and semantic search | Vector database | pgvector |
| Tenant isolation | Application code only | Row-level security policies |
That is one system doing seven jobs. The alternative is several systems that all have to be online for your app to work, each with its own "how do we restore this" runbook, and no transactions across them. It is a big part of the stack we reach for, and why.
Setting up Postgres so it stays boring
Choosing Postgres is the easy part. Running it so you never think about it takes a few deliberate decisions on day one, and almost all of them are cheaper to make before launch than after an incident.
- Use a managed service. Unless you have someone whose job is databases, let a provider handle patching, failover and backups. Your time is better spent on schema design than on replication configuration.
- Turn on point-in-time recovery, then test a restore. Nightly dumps lose up to a day of data. Continuous WAL archiving, which Postgres documents under backup and point-in-time recovery and most managed providers expose as a setting, lets you restore to the minute before someone ran the wrong
DELETE. A backup you have never restored is a hope, not a backup, so rehearse it on a scratch instance. - Set timeouts at the role level.
statement_timeout,lock_timeoutandidle_in_transaction_session_timeoutare all client connection settings you can set per database role. A runaway report query or a request that opened a transaction and then crashed should be cut off automatically, not discovered when everything else is waiting behind its locks. Give your web app role tight limits and your migration or reporting role looser ones. - Pool connections from the start if you deploy to serverless functions or many small containers. Each Postgres connection is a separate server process with its own memory, so hundreds of idle ones from short-lived functions waste resources and can exhaust the connection limit.
- Run migrations as code, reviewed like code. Every schema change goes through a migration file in version control, applied by CI, never typed by hand into production. Build indexes concurrently, and split risky changes (adding a
NOT NULLcolumn to a big table, renaming a column the app reads) into backwards-compatible steps you can deploy one at a time. - Plan for major version upgrades. Under its versioning policy, Postgres ships a new major version about once a year and supports each one for five years after release. Upgrading is routine with
pg_upgradeor a managed provider's upgrade button, as the upgrade documentation describes, but it still deserves a calendar slot and a test run against a copy of production rather than a surprise end-of-life notice.
None of this is exotic. It is the difference between a database you trust and a database you are quietly afraid of, and it is the work that lets the "one system" approach hold up for years.
When we do not reach for Postgres alone
Postgres first is a default, not a religion. There are real cases where it is the wrong tool, and pretending otherwise is how you end up with an unhappy database. We add a second system when:
- We need a fast cache or high-rate ephemeral counters. Rate limit counters and hot-key caching create a lot of short-lived writes, and that is exactly what Redis is built for. Postgres stays the source of truth.
- We have heavy analytical workloads scanning huge volumes of events for dashboards and reports. That is a job for a column store or warehouse such as ClickHouse or BigQuery, fed from Postgres, not for your transactional database.
- Search becomes a product feature with facets, synonyms, typo tolerance and relevance tuning at scale. Then a dedicated search engine earns its keep.
- Vector search outgrows a single node, with very large embedding sets and tight latency targets at high query volume.
- We need a durable event stream with many independent consumers, replay and strict per-key ordering at high volume. That is Kafka territory, and a jobs table will not stretch that far.
Notice the pattern: each one is a specific, measured limit, not a vague feeling that Postgres "won't scale". The decision to add infrastructure should come with a number from your own monitoring attached: a queue latency, a query time, a CPU graph. "The other database feels more modern" is not a reason.
What actually limits Postgres in practice
When a Postgres-backed app struggles, the cause is usually not Postgres. In our experience it is one of these, and each has a known fix:
- Missing indexes, especially on foreign keys. Fix with query plans and targeted indexes.
- Too many connections, common with serverless functions that each open their own. Fix with a connection pooler such as PgBouncer, or your provider's built-in pooling.
- Long-running transactions that block vacuum and hold locks. Fix by keeping transactions short and moving slow work into jobs.
- N+1 queries from the ORM. Fix by loading related data in batches or joins.
- Analytics on the primary. Fix with a read replica, or by moving reporting to a warehouse.
Start with one database
Start with one Postgres instance. Use tables and constraints for the core, jsonb for the loose data, full-text search for the search box, a locked table for the queue, and row-level security as a backstop. Add a second system only when you have a concrete limit you can name, measure and point to on a graph. You will ship faster, sleep better, and spend your energy on the product instead of on keeping several databases in sync.
Schema design, performance tuning and migrations are the core of our PostgreSQL development work. If you want a second pair of eyes on a schema or a stack you are about to commit to, talk to us.
If you're choosing where to host it, our roundup of the best databases for SaaS compares the managed Postgres options and the alternatives.
FAQ · 05 questions
Frequently asked questions
Is PostgreSQL good for startups?
Yes. It is free, open source, widely hosted, and flexible enough to cover relational data, JSON documents, search, queues and vector embeddings in one system. That means fewer services to run while the product is changing quickly, and a database that keeps up as you grow.
PostgreSQL or MySQL: which should I choose?
Both are mature and reliable. We default to PostgreSQL for its richer feature set: JSONB with indexing, strong full-text search, extensions such as pgvector and PostGIS, row-level security and more expressive SQL. MySQL is a fine choice if your team or hosting environment is already built around it.
PostgreSQL or MongoDB: which is better for a web app?
For most web apps with users, accounts, payments and relationships between records, PostgreSQL is the safer choice because it enforces relationships and transactions while JSONB still handles flexible data. MongoDB suits workloads that are genuinely document-shaped with few cross-document relationships.
Can PostgreSQL replace Redis?
Partly. Postgres can handle job queues, simple caching tables and pub/sub notifications for many apps. Redis is still better for high-rate counters such as rate limiting, sub-millisecond caching of hot data, and anything with very high write volume of short-lived keys. Many apps run both, with Postgres as the source of truth.
Does PostgreSQL scale?
A single well-indexed Postgres server handles far more load than most products ever reach, and read replicas, connection pooling and partitioning extend that further. Scaling problems are usually caused by missing indexes, inefficient queries or too many connections rather than by Postgres itself.