Prompt
How do I scale PostgreSQL as my app grows past the first few thousand users?
Latest observation
Scaling PostgreSQL usually means doing less work per request, then using the right mix of indexing, caching, read replicas, and partitioning before you ever think about sharding.
Here’s a practical path that works well as an app grows.
1) Start with measurement
Before changing architecture, find the bottleneck:
- Slow queries (
pg_stat_statements) - High CPU
- IO saturation
- Lock contention
- Too many connections
- Memory pressure
- Autovacuum falling behind
Useful tools:
EXPLAIN (ANALYZE, BUFFERS)for slow queriespg_stat_statementsto rank query cost- Monitoring for:
- p95/p99 query latency
- active connections
- buffer cache hit ratio
- replication lag
- dead tuples / autovacuum activity
2) Fix query and schema issues first
This is the cheapest scaling win.
Index correctly
- Add indexes for frequent
WHERE,JOIN,ORDER BY, andGROUP BYcolumns. - Use composite indexes that match your query patterns.
- Consider partial indexes for common subsets:
CREATE INDEX ON orders (user_id, created_at DESC) WHERE status = 'open'; - Avoid over-indexing; every index slows writes.
Make queries efficient
- Don’t
SELECT *unless you need everything. - Use pagination carefully:
- Prefer keyset pagination over offset pagination for large tables.
- Avoid N+1 query patterns.
- Return only needed rows and columns.
Keep transactions short
- Long transactions block vacuum and increase bloat.
- Avoid holding locks while doing application work.
Watch data types
- Use appropriate types:
uuid,bigint,timestamptz,jsonbwhere suitable
- Don’t store everything as text.
3) Use connection pooling
Postgres doesn’t like thousands of idle app connections.
- Use PgBouncer or a managed equivalent.
- Keep a reasonable number of DB connections per app instance.
- Pooling often gives an immediate improvement in stability.
Typical rule:
- App servers can have many threads/processes
- Postgres should have a much smaller number of active backend connections
4) Add caching where it makes sense
Use cache to reduce repeated reads, not as a band-aid for bad design.
Common options:
- Redis for hot reads, sessions, rate limits, computed data
- Application-level caching for expensive lookups
- CDN for static/public content
Best candidates:
- User profiles
- Feature flags
- Common reference data
- Aggregates that don’t need real-time accuracy
Be careful with:
- Cache invalidation
- Serving stale data unintentionally
- Over-caching write-heavy data
5) Separate reads from writes with replicas
When reads dominate, add read replicas.
How it helps:
- Primary handles writes
- Replicas serve read-only traffic
Good for:
- Dashboards
- Search/filter pages
- Analytics-lite queries
- Public content
Tradeoffs:
- Replication lag
- Read-after-write consistency issues
- Operational complexity
Pattern:
- Writes go to primary
- Reads go to replica when stale data is acceptable
- Use primary for critical “just wrote this” flows
6) Partition big tables
If tables get very large, partitioning helps with:
- Faster pruning of irrelevant data
- Easier retention/deletion
- Better maintenance on large tables
Good partitioning keys:
- Time-based (
created_at) - Tenant-based in multi-tenant systems
- Category or region, if access is well-distributed
Best for:
- Event logs
- Activity feeds
- Time-series data
- Large append-only tables
Not a cure-all:
- If your queries don’t use the partition key, benefits are limited
- Too many partitions can add complexity
7) Reduce bloat and vacuum issues
As the app grows, UPDATE/DELETE-heavy tables can degrade.
- Make sure autovacuum is healthy
- Tune autovacuum if necessary
- Watch table and index bloat
- Use
fillfactorfor heavily updated tables - Consider
VACUUM (ANALYZE)and periodic maintenance
Symptoms of trouble:
- Slow queries on “small” tables
- Table size much larger than expected
- Rising dead tuples
- Autovacuum lag
8) Scale the app vertically first, then horizontally
Postgres can go surprisingly far on one strong machine.
Vertical scaling:
- More CPU
- More RAM
- Faster NVMe storage
- Proper shared buffers / work_mem tuning
Often the biggest gains come from:
- More RAM to keep hot data in memory
- Faster disk for write-heavy workloads
Horizontal scaling:
- Read replicas
- Partitioning
- Eventually sharding
9) Be careful with sharding
Sharding is usually the last step.
Use it when:
- One database can no longer hold the data or traffic
- Writes exceed what a single primary can handle
- You have clear tenant/user partitioning
Costs:
- Cross-shard joins become hard
- Transactions across shards are complex
- Migrations and rebalancing are painful
Only shard if you’ve already exhausted:
- Query optimization
- Caching
- Pooling
- Replicas
- Partitioning
- Vertical scaling
10) Design around your workload
Different apps need different strategies.
Mostly read-heavy SaaS
- Pooling
- Caching
- Read replicas
- Index tuning
- Maybe partitioning by time or tenant
Write-heavy event/log platform
- Batch inserts
- Partitioning
- Compression/archival
- Aggressive retention
- Async processing
Multi-tenant app
- Index by tenant_id
- Consider partitioning by tenant or tenant groups
- Prevent noisy-neighbor issues
- Potentially isolate large tenants later
11) Operational best practices
- Use migrations carefully and online when possible
- Back up and test restores
- Monitor replication lag
- Set alerts on latency, disk, and connections
- Keep extensions/version upgrades planned
- Avoid running heavy analytics on the primary
A simple growth roadmap
If you want a practical order of operations:
- Add monitoring and query visibility
- Fix slow queries and missing indexes
- Add connection pooling
- Add caching for hot reads
- Add read replicas
- Partition large tables
- Tune vacuum and storage
- Consider sharding only if necessary
Rule of thumb
Most apps don’t need “big data” architecture at a few thousand users. They need:
- Better queries
- Better indexes
- Fewer connections
- Some caching
- Maybe one replica
If you want, I can give you a step-by-step scaling checklist for PostgreSQL or help you design a plan for your specific app pattern.
Brands