"Logic in the database doesn't scale" - I hear it regularly. Instead of arguing, I measured. The subject is a small public CRM: crm.rust.db.app - users, clients, teams, projects with stages and comments, plus a service desk. All the data logic lives in PL/pgSQL procedures and SQL functions, and the Rust API (axum, tokio-postgres) does only HTTP, the session and one CALL or one SELECT per request.

A bonus: the project started as Kotlin + Spring Boot on SQL Server 2025 Express and was rewritten step by step to Rust + PostgreSQL 18, with the same HTTP contract and the same front end. So I have three runs of the same test on the same data and the same hardware. All results, scripts and raw logs are in `perf/`.

Data and scenario

Data5 M clients, 5 M projects (+5 M stage history rows), 2 M comments, 5 000 users, 900 teams
Database size5.4 GB in PostgreSQL (7.6 GB of files in SQL Server)
Loadk6, 200 virtual users: 2 min ramp-up, 10 min full traffic, 1 min ramp-down
Trafficsearches and details dominate, about a quarter of iterations write (new client, stage change, comment, new project)
Hardwareone laptop, 16 cores, 30 GB RAM, everything in Docker (k6 too)
Thresholdsp95 < 500 ms, p99 < 1 s, errors < 1%

90% of the users are salespeople (SALES) who see only their own clients and their teams' projects. That visibility rule lives in the database, not in the API - and it is the most expensive part.

Results

p95 response time: SQL Server Express 56.1 ms, with indexes 8.5 ms, PostgreSQL 18 4.63 ms
RunStackWhat changedRequestsp95p99DB CPU (avg)
1Kotlin + SQL Server Expressbaseline260 563 (334/s)56.1 ms81.2 ms198%
2Kotlin + SQL Server Expressread indexes + SALES project search263 307 (338/s)8.5 ms10.4 ms58%
PG 1Rust + PostgreSQL 18.6the schema with the run-2 indexes264 711 (339/s)4.63 ms5.52 ms27%

100% CPU = one core. Zero failed requests in the PostgreSQL run, median 0.51 ms.

The most important lesson is in the first two rows, not the third: the same SQL Server with good indexes went from 56 to 8.5 ms, and the worst project search from 6.76 s to 74 ms. A single "all projects by due date" call read 102 267 pages and took 8.6 s; with a (due_date, id) index it reads 260 pages in 5 ms. Changing the platform then halved it once more. Indexes first, engine migrations later.

Per endpoint (p95)

EndpointSQL Server (run 2)PostgreSQL
GET /api/projects (search)10.5 ms5.56 ms
GET /api/clients (search)4.0 ms1.26 ms
GET /api/clients (next page)4.5 ms0.87 ms
POST /api/projects/{id}/stage3.4 ms1.79 ms
POST /api/projects2.6 ms1.58 ms
GET /api/projects/{id}0.8 ms0.47 ms
POST /api/auth/login (bcrypt)57.7 ms51.21 ms

Login is the slowest - as it should be: bcrypt is about 40 ms of CPU by design, once per user.

Resources

ContainerCPU avgCPU maxMemory
PostgreSQL27%39%2.3 GiB (2 GB of it shared_buffers)
API (Rust)4%13%36 MiB
for comparison: SQL Server58%88%3.9 GiB
for comparison: API on the JVM9%35%about 480 MiB

339 requests per second, and the database uses a third of a core on average. Cache hit ratio: 99.87%.

What makes the difference: four patterns

1. Keyset paging instead of OFFSET

One table worth showing to anyone who writes Skip() / Take():

Page 200 000 of the client list8 KB blocksTime
OFFSET90 171330 ms
keyset830.11 ms

OFFSET has to read and throw away every earlier row. Keyset paging starts from the last key of the previous page, so page 200 000 costs the same as page 1:

SQL
SELECT c.id, c.name, c.city, c.status, crm.row_version(c.xmin)
FROM crm.clients AS c
WHERE (lower(c.name) COLLATE "C") LIKE v_pattern
  AND (v_owner_id IS NULL OR c.assigned_user_id = v_owner_id)
  AND (v_after_key IS NULL OR ((lower(c.name) COLLATE "C"), c.id) > (v_after_key, p_after_id))
ORDER BY (lower(c.name) COLLATE "C"), c.id
LIMIT p_page_size + 1;          -- +1: we know whether there is a next page, without COUNT(*)

The row comparison (name, id) > (…, …) is a condition the (lower(name) COLLATE "C", id) index serves directly. COLLATE "C" lets LIKE 'abc%' use the index too.

2. plan_cache_mode = force_custom_plan for optional filters

The search function has five optional filters. A generic plan (the same for every combination of NULLs) can be terrible, so the function gets a plan for the values actually passed:

SQL
CREATE OR REPLACE FUNCTION app.client_search(p_actor_id int, p_name_prefix text, /* … */ p_page_size int)
    RETURNS TABLE (/* … */)
    LANGUAGE plpgsql
    STABLE
    SECURITY DEFINER
    SET search_path = pg_catalog, pg_temp
    SET plan_cache_mode = force_custom_plan
AS $$ … $$;

The cost: planning on every call (fractions of a millisecond). The gain: an index chosen for the filter the user actually typed.

3. Covering and partial indexes

The project list is sorted by due date and the page needs a few columns. INCLUDE adds them to the index leaf, so the read doesn't touch the table (Index Only Scan). "Overdue" means open projects only - a partial index doesn't keep the closed ones:

SQL
CREATE INDEX ix_projects_due ON crm.projects (due_date, id)
    INCLUDE (stage, team_id, client_id, owner_user_id);

CREATE INDEX ix_projects_open_due ON crm.projects (due_date, id)
    INCLUDE (stage, team_id, client_id, owner_user_id)
    WHERE stage IN ('NEW', 'ACCEPTED', 'ACTIVE', 'ON_HOLD');

Every index ends on id - the second sort key - so LIMIT stops reading after one page.

4. Statistics kept by the procedures instead of COUNT(*)

Team statistics (how many projects in each stage, the sum of budgets) over 5 M projects are a heavy GROUP BY. In SQL Server it was an indexed view. In PostgreSQL it is a crm.team_project_stats table that every procedure writing a project updates in the same transaction:

SQL
-- Rows always in (team_id, stage) order: two concurrent moves cannot deadlock.
FOR r IN
    SELECT d.team_id, d.stage, sum(d.n) AS n, sum(d.budget) AS budget
    FROM (VALUES (p_old_team_id, p_old_stage, -1, -p_old_budget),
                 (p_new_team_id, p_new_stage,  1,  p_new_budget)) AS d (team_id, stage, n, budget)
    WHERE d.team_id IS NOT NULL
    GROUP BY d.team_id, d.stage
    ORDER BY d.team_id, d.stage
LOOP
    INSERT INTO crm.team_project_stats (team_id, stage)
    VALUES (r.team_id, r.stage)
    ON CONFLICT (team_id, stage) DO NOTHING;

    UPDATE crm.team_project_stats AS s
    SET project_count = s.project_count + r.n,
        budget_total  = s.budget_total + r.budget
    WHERE s.team_id = r.team_id AND s.stage = r.stage;
END LOOP;

Reading the statistics: at most 6 rows, 0.03 ms, whatever the number of projects. Here logic in the database wins outright: the counter changes in the same transaction as the project, so it cannot drift - no event, no queue, no nightly "recalculate statistics" job.

Where the time goes now

The most expensive call is the project search for a salesperson: 3.4 ms on average and 4 000-6 000 blocks per call, because "projects of my clients" probes the ix_projects_client index once per client of the user. Denormalising (the client's owner copied to the project) would bring it down, but with a p95 around 5 ms it isn't justified. Measuring also tells you what not to do.

The database-side measurements use standard PostgreSQL tools, no APM agents:

SQL
-- shared_preload_libraries = pg_stat_statements, track_functions = pl, track_io_timing = on
SELECT funcname, calls, round((total_time / calls)::numeric, 2) AS avg_ms
FROM pg_stat_user_functions
WHERE schemaname = 'app'
ORDER BY total_time DESC;

pg_stat_statements.track = all also counts the statements inside procedures, and EXPLAIN (ANALYZE, BUFFERS) on single calls gives the number of blocks - the same unit (an 8 KB page) as logical reads in SQL Server, so the plans could be compared one to one. They read a similar number of pages in both engines.

Being honest about the comparison

This is not a SQL Server vs PostgreSQL benchmark. More than the engine changed: the API went from the JVM to Rust, and SQL Server was the Express edition (at most 4 cores, about 1.4 GB of buffer pool). In no run was the database the bottleneck - CPU was far from its limit. The gain came from shorter single calls and a lighter API.

But that edition limit leads to the most interesting conclusion.

PostgreSQL has no per-core licence - and that changes the scaling maths

With SQL Server every core costs money. Express is free but capped at 4 cores and about 1.4 GB of memory for the data cache. Standard is licensed per core, in 2-core packs (about USD 3,945 per pack at list price), with a minimum of 4 cores per virtual machine. Going from 4 to 8 vCPUs is not just a bigger VM rate - it is more licences.

PostgreSQL has no editions and no per-core licence. In the cloud that means something very practical: when the database starts to struggle, you add more vCPUs and more RAM and pay only for the machine. No talk with procurement, no licence recount, no "let's stay on 4 cores because of Standard".

And logic in the database makes good use of it:

  • More RAM = bigger shared_buffers and OS cache. In this test 2 GB of shared_buffers plus the OS cache gave a 99.87% hit ratio. A bigger data set? A bigger machine and the same code.
  • More vCPUs = more procedures in parallel. Every request is one short transaction on one pooled connection. 339 req/s took a third of a core - the headroom on 16 cores is huge, and when it runs out, scaling is a slider in the cloud console.
  • The API costs next to nothing. 36 MiB and 4% CPU - the money goes where the work is: the database's RAM.
  • Read replicas at no extra charge. Read views and functions can run on a streaming replica - also without a licence.

That doesn't mean you should scale vertically forever. It means that the simplest move - a bigger machine - is also the cheapest, and it doesn't require rewriting the application into microservices, a cache in front of the database or queues "for performance".

Takeaways

  1. Logic in the database scales - 339 req/s, p95 4.6 ms, 5 M clients and 5 M projects on a laptop, the database on a third of a core.
  2. Indexes give more than a platform change: 56 → 8.5 ms on the same SQL Server.
  3. Keyset instead of OFFSET, INCLUDE and partial indexes, statistics kept in the transaction - patterns that work in any engine.
  4. Measure with the database's own tools: pg_stat_user_functions, pg_stat_statements, EXPLAIN (ANALYZE, BUFFERS).
  5. Without a per-core licence, scaling is a slider in the cloud: more vCPUs and RAM cost what the machine costs.

The code, the k6 scenario, the measuring scripts and the raw results: github.com/kldev/crm.rust.db.app/tree/main/perf. You can run it yourself with a few commands from perf/README.md - I encourage it, especially if you have "procedures are slow" in your head.