How I cut response time by 40% on a multi-tenant SaaS with PostgreSQL and Redis
On a multi-tenant SaaS at Media Telekomunikasi Mandiri, application response time dropped by 40% through query tuning and caching. There was no rewrite. This is the order of work I would repeat on any slow product.
1. Measure before changing anything
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
SELECT round(total_exec_time) AS total_ms,
calls,
round(mean_exec_time::numeric, 1) AS mean_ms,
left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;The extension needs shared_preload_libraries = 'pg_stat_statements' and a restart. Sort by total time, not by mean. A 20 ms query called 500,000 times costs more than a two-second report that runs twice a day.
2. Index for the tenant first
In a multi-tenant schema almost every query filters by tenant. Put the tenant column first in a composite index, then the columns you filter and sort by.
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM invoices
WHERE tenant_id = 42 AND status = 'unpaid'
ORDER BY due_date
LIMIT 20;
CREATE INDEX CONCURRENTLY idx_invoices_tenant_status_due
ON invoices (tenant_id, status, due_date);In the plan, look for Seq Scan and a large Rows Removed by Filter. After the index you should see an index scan and no separate sort step. CONCURRENTLY builds the index without blocking writes.
3. Remove N+1 queries
An ORM that loads a list and then runs one query per row shows up in pg_stat_statements as a cheap query with a huge call count. Replace it with a join, or load the related rows in one query with WHERE id = ANY($1).
4. Cache what is read often and changes rarely
async function getPlan(tenantId) {
const key = 'tenant:' + tenantId + ':plan'
const hit = await redis.get(key)
if (hit) return JSON.parse(hit)
const plan = await db.plans.findByTenant(tenantId)
await redis.set(key, JSON.stringify(plan), 'EX', 300)
return plan
}- Put the tenant id in every key. A key without it leaks data between tenants.
- Always set a TTL. A cache entry that never expires becomes a bug you find months later.
- On a write, delete the key. Do not try to update the cached value in place.
- Do not cache permission checks unless you can invalidate them the moment access changes.
5. Verify with the same measurement
Run SELECT pg_stat_statements_reset();, wait for a comparable period, and read the top ten again. Then compare p95 response time from your load balancer or APM for the same weekday before and after. If the number did not move, the change did not matter.