Skip to content

Database Performance and SQL Tuning

Intermediate 44 min read Part 5 of 18

Making databases fast: query plans, N+1 queries, connection pooling, materialized views, partitioned tables, batching, replicas, and the order to scale in.

Summary#

Most database slowness comes from a few causes: missing indexes and bad query plans, N+1 queries from application code, too many connections, unbatched writes, and tables that grew without a plan. Fix them in order of cost: first queries and indexes, then configuration and connection pooling (PgBouncer), then a bigger machine, then caching, then read replicas, then partitioning and materialized views, and only then sharding. Each step is cheaper and less risky than the next. Measure first: find the top queries by total time, read their plans with EXPLAIN ANALYZE, and fix the biggest one.

Why It Exists#

The database is usually the hardest part of a system to scale, because it holds state. Application servers can be cloned in minutes; a database cannot. Teams often reach for sharding or a new database when the real problem is three missing indexes and an ORM making 200 queries per page. Knowing the cheap fixes, and the order to apply bigger ones, saves months of work. This page builds on Database Indexing.

How It Works#

Query plans#

Every SQL statement becomes a query plan: which indexes to use, the join order and join algorithms, and where to sort. The optimizer picks it from table statistics. Start with the queries that consume the most total time (frequency × duration), not the single slowest one: pg_stat_statements in PostgreSQL and the Performance Schema or slow query log in MySQL show this.

For each one, run EXPLAIN ANALYZE and look for sequential scans on large tables, row estimates far from actual counts (stale statistics: run ANALYZE), large sorts or hash operations spilling to disk, and nested loops over many rows. Fixes are usually an index in the right column order, rewriting the query (avoid functions on indexed columns, avoid SELECT *, use keyset pagination instead of large OFFSET), or updating statistics.

Query plans in depth#

How a query becomes a plan. A SQL statement passes through four stages. The parser turns the text into a syntax tree. The analyser resolves table and column names. The rewriter expands views and rules. The planner, also called the optimizer, then searches for the cheapest way to execute it. The planner does not run the query to find out. It estimates cost from statistics and a cost model, then hands the chosen plan to the executor.

Cost-based optimization dates to IBM's System R. The paper "Access Path Selection in a Relational Database Management System" by Patricia Selinger and colleagues (SIGMOD 1979) introduced the ideas still used today. Each plan is costed in estimated page reads and CPU work. Join orders are searched with dynamic programming, and "interesting orders" are tracked, so a plan that produces sorted output can win later if a sort is needed anyway.

Statistics drive everything. PostgreSQL's ANALYZE samples each table, by default 300 × default_statistics_target (100) = 30,000 rows. It stores the fraction of nulls, the number of distinct values, a list of the most common values with their frequencies, and a histogram of the rest. From these, the planner estimates selectivity, the fraction of rows a condition keeps. For status = 'shipped' it looks up the most-common-values list. For created_at > '2026-11-01' it interpolates in the histogram. Multiply selectivity by the row count and you get the estimated row count, which decides everything downstream.

Scan types. For a single table the planner chooses among:

  • Sequential scan: read every page in order. It is the best choice when the query needs a large share of the table, often more than about 5-10% of rows, because sequential I/O is far cheaper per page than random I/O.
  • Index scan: walk the B-tree, then fetch each matching row from the heap. It is good for a few rows. Each heap fetch may be a random read.
  • Index-only scan: answer the query entirely from the index when all needed columns are in it. In PostgreSQL this also needs the visibility map to show pages as all-visible, which depends on recent vacuuming.
  • Bitmap scan: collect matching row locations from one or more indexes into a bitmap, sort them by page, then read the heap in physical order. It is the middle ground for "too many rows for an index scan, too few for a sequential scan", and it can combine two indexes with AND or OR.

Join algorithms. For each pair of inputs the planner picks one of three algorithms:

AlgorithmHow it worksBest whenCost shape
Nested loopFor each outer row, look up matches in the inner input, ideally via an indexOuter side is small (tens to thousands of rows), inner side indexedOuter rows × index lookup
Hash joinBuild a hash table on the smaller input, probe it with the largerLarge unsorted inputs, equality joinsLinear in both inputs, needs memory (work_mem)
Merge joinWalk two inputs sorted on the join key in stepBoth inputs already sorted, for example from indexesLinear, plus sorting if not presorted

A hash join whose hash table exceeds work_mem (4 MB by default in PostgreSQL) spills into batches on disk. EXPLAIN ANALYZE shows this as Batches: 8 instead of Batches: 1. The same applies to sorts that report Sort Method: external merge Disk: 120MB.

Reading EXPLAIN ANALYZE. The output is a tree read from the innermost node outward. Each node shows estimated cost and rows, then actual time, rows and loops. The single most useful check is estimated rows versus actual rows. Here is a trimmed example:

Nested Loop  (cost=0.85..412.10 rows=12 width=64) (actual time=0.05..2850.3 rows=48210 loops=1)
  ->  Index Scan using orders_status_idx on orders  (rows=12) (actual rows=48210 loops=1)
        Index Cond: (status = 'pending')
  ->  Index Scan using customers_pkey on customers  (actual time=0.05..0.05 rows=1 loops=48210)
Planning Time: 0.4 ms
Execution Time: 2862.1 ms

The planner expected 12 pending orders and found 48,210, which is a 4,000× misestimate. With 12 rows a nested loop is ideal. With 48,210 it performs 48,210 index lookups, where a hash join would have been several times faster. The cause is usually stale statistics after a bulk change, so the fix starts with ANALYZE orders. Note also loops=48210: the actual time shown on an inner node is per loop, so multiply to get its real share.

Why estimates go wrong. The planner assumes columns are independent. For city = 'Paris' AND country = 'France' it multiplies two selectivities and underestimates badly, because the two columns are correlated. PostgreSQL's CREATE STATISTICS ... (dependencies, ndistinct, mcv) (version 10 and later, MCV lists from 12) fixes this for chosen column groups. Other causes are skew (one tenant owns 40% of rows), functions on columns (WHERE lower(email) = ... hides the column from both statistics and indexes unless an expression index exists), and joins several levels deep, where errors multiply at each level.

Query rewrites that help the planner.

  • Keep predicates sargable, meaning usable by an index. Write created_at >= '2026-11-01' AND created_at < '2026-12-01' rather than date_trunc('month', created_at) = '2026-11-01'.
  • Replace deep OFFSET pagination with keyset pagination. OFFSET 100000 reads and throws away 100,000 rows. The keyset form seeks straight to the position:
-- page 1
SELECT id, created_at, title FROM posts
WHERE user_id = 42 ORDER BY created_at DESC, id DESC LIMIT 20;
-- next page: pass the last row's (created_at, id) back as a cursor
SELECT id, created_at, title FROM posts
WHERE user_id = 42 AND (created_at, id) < ('2026-11-30 10:15:00', 98231)
ORDER BY created_at DESC, id DESC LIMIT 20;
-- served by: CREATE INDEX ON posts (user_id, created_at DESC, id DESC);
  • Select only the columns you need. SELECT * prevents index-only scans, drags large TEXT and JSONB values through the network (PostgreSQL stores big values out of line in TOAST tables, and fetching them costs extra reads), and breaks when columns are added.
  • Use EXISTS rather than COUNT(*) > 0 to test for presence, so the executor can stop at the first match.
  • For "top N per group" queries, use a LATERAL join with LIMIT, which turns one huge sort into many small index seeks.

Prepared statements and generic plans. A prepared statement is planned once and re-executed. PostgreSQL plans the first five executions with the actual parameter values (custom plans), then switches to a generic plan if that plan is not estimated to be much worse. For skewed data this can be harmful. A generic plan suited to small tenants then runs for the giant tenant. plan_cache_mode = force_custom_plan is the escape hatch for such queries.

N+1 queries#

The N+1 problem: code fetches a list (1 query), then runs one more query per item (N queries).

orders = SELECT * FROM orders WHERE user_id = 42 LIMIT 50      -- 1 query
for o in orders:
    o.items = SELECT * FROM order_items WHERE order_id = o.id  -- 50 more queries

Each query may take only 1 ms, but 51 round trips add 50+ ms and load. ORMs make this easy to do by accident through lazy loading. Fixes: a join, or one batched query (WHERE order_id IN (...)), or the ORM's eager loading (includes, select_related, JOIN FETCH). In GraphQL, use a DataLoader. Detect it by logging query counts per request.

N+1 queries in depth#

Why N+1 hurts more than it looks. Each query pays a fixed cost before any data moves: a network round trip (0.2-0.5 ms within an availability zone, 1-2 ms across zones), parsing or plan lookup, executor start-up, and result serialization. Suppose each query takes 0.3 ms of database time plus 0.5 ms of round trip. A page listing 50 orders with their items and customers runs 1 + 50 + 50 = 101 queries, which adds up to about 80 ms of pure overhead. A join or two batched queries do the same work in 2-3 round trips and perhaps 3 ms. The database also burns CPU on 101 executions instead of 3, so at scale N+1 costs both latency and capacity. A service doing 1,000 page views a second turns into 101,000 queries a second.

How ORMs cause it. Object-relational mappers (ORMs) load associations lazily by default. order.items looks like a field access, but the first time it is touched, the ORM issues a query. Inside a loop or a template, that becomes N queries. The same trap appears in Rails ActiveRecord, Django, Hibernate and JPA, SQLAlchemy, and Prisma, with eager-loading escapes in each: includes and preload, select_related (join) and prefetch_related (second query with IN), JOIN FETCH and entity graphs, selectinload and joinedload, and include.

Join versus batched IN: two different fixes. A single join returns one wide row per child. That is fine for one-to-one or small one-to-many relations, but eager-loading two collections at once through joins produces a cartesian explosion. An order with 20 items and 10 shipments returns 200 rows, and the parent columns repeat in each. The batched alternative runs one query per relation, SELECT * FROM order_items WHERE order_id = ANY($1) with an array of 50 IDs, then stitches the results together in memory. That gives three queries in total, no duplication, and it scales to deep object graphs. Most ORMs offer both styles, and choosing per relation is part of tuning.

GraphQL and DataLoader. GraphQL resolvers run per field, so a query for 50 posts and each post's author naively calls the author resolver 50 times. DataLoader, a pattern and library published by Facebook, collects every key requested during one tick of the event loop, issues one batched fetch, then hands each resolver its result. It also caches by key within the request, so the same author appears only once in the batch.

const authorLoader = new DataLoader(async (ids: readonly number[]) => {
  const rows = await db.query(
    "SELECT * FROM users WHERE id = ANY($1)", [ids]);
  const byId = new Map(rows.map(r => [r.id, r]));
  return ids.map(id => byId.get(id) ?? null); // same order as requested
});
// resolver: author: (post) => authorLoader.load(post.authorId)

Detecting N+1. Use several signals:

  • Log or count queries per request, and alert when an endpoint exceeds a budget such as 20.
  • Application performance monitoring tools (Datadog, New Relic, Sentry) flag repeated identical query shapes in a single trace.
  • Libraries such as Bullet (Rails) and nplusone (Django) raise warnings in development.
  • In pg_stat_statements, an N+1 shows up as a very fast query with a huge calls count, often among the top entries by total time even though its mean time is tiny.

The opposite mistake. Do not over-fetch "just in case". Eager-loading every association on every request moves megabytes nobody uses. Load what the endpoint actually renders, and design API responses around access patterns. The goal is a small, constant number of queries per request, regardless of how many items the page shows.

Connection pooling#

Each database connection costs server memory and scheduling. In PostgreSQL every connection is a separate process using several MB, and performance degrades well before max_connections (often a few hundred) is reached. With 100 app instances each opening 20 connections, you need 2,000: too many.

A connection pool keeps a small number of database connections and lends them to requests. There are two layers:

  • In-app pools (HikariCP for Java, the pool in most drivers): reuse connections within one process.
  • External poolers such as PgBouncer or RDS Proxy: thousands of client connections share a few dozen server connections.
# pgbouncer.ini (essentials)
[databases]
app = host=10.0.1.5 port=5432 dbname=app
[pgbouncer]
pool_mode = transaction      ; a server connection is lent per transaction
max_client_conn = 5000       ; app-side connections accepted
default_pool_size = 40       ; real Postgres connections per db/user

Transaction pooling gives the most sharing but breaks features that depend on a session staying on one server connection (session SETs, advisory locks, some prepared-statement setups), so check your driver. A good starting size for the real pool is a small multiple of the database's CPU cores; more connections usually means more contention, not more throughput.

Connection pooling in depth#

Why connections are expensive. PostgreSQL uses a process per connection. Each backend process has its own memory: a few MB at idle, and much more while running queries, because every sort or hash node may use up to work_mem. A query with three such nodes on 500 connections could, in the worst case, claim 3 × 4 MB × 500 = 6 GB. Opening a connection costs a fork, authentication and often a TLS handshake, which adds several milliseconds. Hundreds of mostly idle backends also slow every transaction slightly, because building a snapshot has to scan the list of active backends. PostgreSQL 14 improved snapshot scalability significantly, but large connection counts still hurt. MySQL uses a thread per connection, which is cheaper but still suffers from context switching and lock contention beyond a few hundred active threads. Percona Server, MariaDB and MySQL Enterprise offer a thread-pool plugin for this reason.

Active connections are what matter. A database with 16 cores can make progress on at most about 16 CPU-bound queries at once, plus some that are waiting on I/O. Beyond that, extra concurrent queries only queue inside the database, where they compete for locks, buffers and CPU caches. Queuing outside the database, in a pool, is cheaper and fairer. That is why a smaller pool often gives higher throughput and lower tail latency than a larger one.

Sizing with Little's law. The number of connections in use equals the arrival rate times the time each one is held. A service doing 4,000 transactions per second, each holding a connection for 5 ms, needs on average 4,000 × 0.005 = 20 connections. Add headroom for bursts and you might choose 30-40. If the same service held connections for 50 ms, because it makes an HTTP call to another service inside the transaction, it would need 200. The best way to need fewer connections is to hold them for less time.

A rule of thumb from the PostgreSQL community, popularised by the HikariCP documentation, is connections = (cores × 2) + effective_spindle_count for the database server. For a 16-core machine with SSD storage that suggests roughly 32-40 active connections. Treat it as a starting point for load testing, not a law.

Pool modes in PgBouncer.

ModeServer connection is held forWorks withBreaks
SessionThe whole client sessionEverythingLittle sharing: one server connection per connected client
TransactionOne transactionMost web appsSession state: SET, session advisory locks, LISTEN, temporary tables, WITH HOLD cursors
StatementOne statementAutocommit-only workloadsMulti-statement transactions

Prepared statements used to be the main problem with transaction mode, because a statement prepared on one server connection did not exist on the next. PgBouncer 1.21 (2023) added protocol-level prepared statement tracking, enabled with max_prepared_statements, which removes most of that pain for drivers that use the extended protocol.

Layered pooling. A typical production stack has two layers. Each application process keeps a small in-process pool, for example 5-10 connections in HikariCP, node-postgres or SQLAlchemy. The pools point at PgBouncer, which multiplexes thousands of client connections onto a few dozen server connections. Without the middle layer, 300 Kubernetes pods × 10 connections = 3,000 server connections, a common cause of FATAL: sorry, too many clients already during a deploy, when old and new pods overlap.

Serverless and connection storms. Functions on AWS Lambda or Cloud Run scale to hundreds of instances in seconds, and each may open its own connection. Without a proxy, a traffic spike becomes a connection storm, and the database spends its CPU on authentication. Managed proxies (Amazon RDS Proxy, Google Cloud SQL Auth Proxy with a pooler, Supabase's Supavisor) and HTTP-based database drivers exist largely for this case.

Timeouts that protect the pool. Three settings matter most:

  • Acquire timeout: fail fast if no connection is free within, say, 1-2 seconds, rather than piling up requests.
  • Statement timeout (statement_timeout): kill runaway queries so they cannot hold connections forever.
  • Idle-in-transaction timeout (idle_in_transaction_session_timeout): reclaim connections whose application forgot to commit.

Together they turn a slow database into fast, visible errors instead of a cascading outage where every request thread waits on a pool.

Pooling and replicas. Proxies such as ProxySQL (MySQL), Pgpool-II and Vitess's vttablet do more than pooling. They can route reads to replicas, rewrite or block query patterns, and cache results. Each feature is another component to run and monitor, so add routing only when the application cannot easily do it itself.

Denormalization and materialized views#

When a read needs expensive joins or aggregations on every request, precompute it:

  • Denormalized columns: store comment_count on posts and update it with the comment insert, instead of COUNT(*) on every page view.
  • Materialized views: a stored query result, refreshed on demand or on a schedule.
CREATE MATERIALIZED VIEW daily_sales AS
SELECT product_id, date_trunc('day', created_at) AS day, sum(total_cents) AS revenue
FROM orders GROUP BY 1, 2;
CREATE UNIQUE INDEX ON daily_sales (product_id, day);
REFRESH MATERIALIZED VIEW CONCURRENTLY daily_sales;   -- e.g. every 10 minutes

The cost is staleness and extra write work. For heavy analytics, move the workload to a warehouse instead. See Data Modeling.

Denormalization and materialized views in depth#

The core trade. Normalisation stores each fact once, so writes are simple and consistent but reads may need joins and aggregates. Denormalisation stores some facts redundantly, so reads are cheap but every write must update several places. Most systems read far more than they write, often 100:1 and sometimes 1,000:1, so moving work from read time to write time usually pays off. It stops paying off when writes are heavy. A denormalised schema under a high write load can perform worse than its normalised version, because each logical write fans out into several physical writes and more lock contention.

Ways to keep redundant data correct, from strongest to weakest consistency:

  1. Same transaction. Insert the comment and run UPDATE posts SET comment_count = comment_count + 1 in one transaction. This is always consistent. The cost is a hot row: a viral post's counter becomes a lock queue (see Concurrency Control and Locking).
  2. Database trigger. It gives the same consistency, enforced even for writes that bypass the application. Triggers are hidden logic, though, harder to test and to reason about during migrations.
  3. Materialized view. The database recomputes a stored query result on refresh. Data is stale between refreshes.
  4. Asynchronous derivation. A change data capture stream or an outbox feeds a worker that updates summary tables, a cache or a search index. This is eventually consistent but scales independently of the primary.

Materialized views in PostgreSQL. REFRESH MATERIALIZED VIEW recomputes the entire query and takes an exclusive lock that blocks reads of the view until it finishes. The CONCURRENTLY option computes the new result separately, diffs it against the old one, and applies only the changes, so readers keep working. It requires a unique index on the view and takes longer overall. Either way the full query re-runs, so a view over a 2-billion-row table refreshed every 5 minutes may cost more than the queries it replaced. Core PostgreSQL has no incremental maintenance. The pg_ivm extension adds a limited form of it. Oracle supports "fast refresh" using materialized view logs that record changes to base tables, and SQL Server's indexed views are maintained synchronously on every write.

Streaming and incremental view maintenance. Systems such as Materialize and RisingWave keep SQL views continuously up to date by processing a change stream. Their ideas build on differential dataflow, research by Frank McSherry and colleagues. ClickHouse materialized views act as insert triggers that aggregate each new block of rows into a target table. When a dashboard needs second-level freshness over a large event history, these tools beat periodic full refreshes.

Summary tables and rollups. The most common hand-built form of denormalisation is a rollup table. page_views_hourly(page_id, hour, views) is updated by a job that aggregates the last hour of raw events, and queries for "views in the last 30 days" sum 720 hourly rows instead of scanning millions of raw events. Rollups compose: roll hourly data into daily data, and keep raw events only for a short retention window.

Tightening the schema. Smaller rows mean more rows per 8 KB page, more of the table in cache, and less I/O.

  • Use the narrowest correct type: integer (4 bytes) rather than bigint (8 bytes) when values stay under about 2.1 billion. Use bigint for IDs that will grow, because migrating an exhausted int key on a big table is painful.
  • Use numeric or DECIMAL, or integer cents, for money, never floating point.
  • Store large blobs (images, PDFs) in object storage and keep only the key and metadata in the row.
  • Declare NOT NULL where it is true. It documents intent and helps some optimizers.
  • In PostgreSQL, varchar(n), text and char(n) perform the same, and char(n) pads with spaces, so prefer text with a check constraint. Advice that fixed-width CHAR is faster comes from engines with fixed-length row formats, such as older MySQL storage formats.

Federation and vertical partitioning. Splitting by function is a coarse cousin of denormalisation. Users, products and forums each move to their own database. Each database gets less traffic, a hotter cache and its own write throughput. The cost is that cross-domain joins become application code. Within one database, the same idea applies to a single table: move rarely used wide columns, such as a bio or settings_json, into a side table, so the hot table stays narrow and fits in memory.

Partitioned tables#

Table partitioning splits one large table into smaller physical pieces inside the same database, by range (month), list (region) or hash (user ID). Queries that filter on the partition key read only matching partitions (partition pruning), indexes stay small enough to fit in memory, and old data is removed by dropping a partition instantly instead of a huge DELETE.

CREATE TABLE events (id bigint, user_id bigint, created_at timestamptz, payload jsonb)
  PARTITION BY RANGE (created_at);
CREATE TABLE events_2026_12 PARTITION OF events
  FOR VALUES FROM ('2026-12-01') TO ('2027-01-01');
-- Retention: DROP TABLE events_2026_01;  (instant, no vacuum debt)

Partitioning is not sharding: everything is still on one server. It helps manageability and query speed for very large tables, typically hundreds of millions of rows and up, especially time-series data. See Partitioning and Sharding.

Partitioned tables in depth#

What the database does with partitions. In PostgreSQL's declarative partitioning (version 10 and later), the parent table holds no rows. Each partition is a real table with its own storage, indexes and vacuum state. On insert, the row is routed to the partition whose bounds match its key. On query, the planner compares the WHERE clause with the partition bounds and skips partitions that cannot match. This partition pruning happens at plan time for constants, and at execution time (version 11 and later) for parameters and join values, which matters for prepared statements.

Choosing the partition key. Most queries and the retention policy should filter on the key.

  • Range by time is the default for events, logs, orders and metrics. Queries ask for "the last 7 days", and retention drops whole months.
  • List suits a small fixed set, such as region or tenant tier.
  • Hash spreads rows evenly when no natural range exists. It helps vacuum and index size, but gives no pruning for range queries.

Sub-partitioning (range by month, then hash by customer) is possible but multiplies the partition count.

Worked example. An events table receives 50 million rows a day, about 580 inserts a second on average, and keeps 13 months. Unpartitioned, it reaches roughly 20 billion rows. Its indexes become larger than RAM, and a nightly DELETE of 50 million old rows generates huge WAL traffic, bloats the table, and leaves dead tuples for vacuum to clean. Partitioned by day, each partition holds 50 million rows. "Last 24 hours" queries touch one or two partitions whose indexes stay hot in memory, and retention becomes DROP TABLE events_2025_11_01, a metadata operation that finishes in milliseconds. Partitioned by month instead, the same table has 13 partitions of about 1.5 billion rows each. That is also reasonable, and it means fewer objects to plan over.

How many partitions. Hundreds of partitions are routine. Thousands work in modern versions, but planning time and memory grow for queries that cannot prune, and every partition adds files and catalog entries. Pick a granularity where each partition is somewhere between tens of GB and a few hundred GB, and where a typical query touches a handful of partitions.

Rules and limits to know.

  • A primary key or unique constraint on a partitioned table must include the partition key, because each partition enforces uniqueness only locally. A table partitioned by created_at therefore cannot enforce a global unique email by itself.
  • Indexes are created per partition. An index defined on the parent is propagated to every partition, and new partitions inherit it.
  • Partitions must exist before rows arrive, or inserts fail, unless a DEFAULT partition catches them. Tools such as pg_partman pre-create future partitions and drop expired ones on a schedule.
  • ALTER TABLE ... DETACH PARTITION ... CONCURRENTLY (version 14 and later) removes a partition without blocking queries, so you can archive it to cheaper storage before dropping it.
  • MySQL supports range, list, hash and key partitioning, but foreign keys are not supported on partitioned InnoDB tables, and every unique key must include all partitioning columns.

Hot partitions. Time-range partitioning concentrates all writes on the newest partition. That is fine on one server, where the newest partition is simply the hottest part of the cache. It becomes a problem only if the partitions are spread across servers, which is the distinction between partitioning and sharding covered in Partitioning and Sharding.

Partitioning without the feature. Before declarative partitioning existed, teams used separate tables per period (events_2026_12) and a view, or application routing. A related trick also predates the feature: move the hot subset of a table into its own table so it stays in memory, for example active carts versus completed orders, or open tickets versus closed ones.

Batching writes#

Every transaction pays fixed costs: a network round trip, parsing, and a log flush at commit. Inserting rows one per transaction might reach a few thousand rows per second; batching hundreds of rows per statement or using bulk load (COPY in PostgreSQL, LOAD DATA in MySQL) can reach hundreds of thousands.

  • Multi-row INSERT ... VALUES (...), (...), ... of 100-1,000 rows.
  • Group many small updates into one transaction where the business logic allows it.
  • Buffer high-rate events (clicks, metrics) in a queue and write in batches.

Keep batches bounded: huge transactions hold locks longer, bloat the log and lag replicas.

Batching writes in depth#

Where the time goes in a single-row write. An autocommit INSERT does four things. It makes a network round trip (about 0.5 ms), parses and plans the statement, modifies the heap and every index, and then at commit waits for the write-ahead log (WAL) to be flushed to durable storage. The flush is the expensive part. A local NVMe SSD with power-loss protection flushes in tens of microseconds, while a network-attached cloud volume often takes 0.5-2 ms. A single client inserting one row per transaction is therefore capped at about 1 / (round trip + flush) ≈ 500-1,000 rows per second, however fast the CPU is.

What batching changes. If 500 rows share one statement and one commit, the round trip and the flush are paid once instead of 500 times. Throughput is then limited by CPU and index maintenance. Typical figures on one PostgreSQL server are:

MethodRows per second (one client, narrow rows, rough)
One row per transaction500 - 2,000
Many rows per transaction, one statement each10,000 - 30,000
Multi-row INSERT ... VALUES (500 rows)50,000 - 150,000
COPY from a client stream200,000 - 1,000,000

Exact numbers vary with row width, the number of indexes and the hardware, but the ratios hold. Each step is roughly one order of magnitude faster than the previous one.

Group commit. Databases already batch commits across concurrent sessions. When many transactions are waiting for a flush, one fsync can make all of their WAL durable together. PostgreSQL's commit_delay and MySQL's binary-log group commit tune this. Group commit helps many concurrent clients. It does nothing for a single client committing serially, which still needs application-side batching.

Relaxing durability, knowingly. PostgreSQL's synchronous_commit = off returns success before the WAL flush. A crash can lose the last few hundred milliseconds of commits, by default up to about three times wal_writer_delay (200 ms), but it cannot corrupt data. It can be set per transaction, so analytics events can use it while payments do not. MySQL's innodb_flush_log_at_trx_commit = 2 is a similar trade-off.

Bulk-load techniques.

  • Use COPY (PostgreSQL) or LOAD DATA INFILE (MySQL) for large imports.
  • For a one-time load into a new table, create it without secondary indexes, load the data, then build the indexes. Building an index once over sorted data is much faster than maintaining it row by row.
  • Pass arrays to INSERT ... SELECT * FROM unnest($1::bigint[], $2::text[]) to send thousands of rows as two parameters, which also sidesteps the 65,535 bind-parameter limit of the protocol.
  • Batch upserts with INSERT ... ON CONFLICT (key) DO UPDATE. Sort the rows by key first, so that concurrent batches lock rows in the same order and avoid deadlocks.

Batch sizing. Larger is not always better. A batch of 1 million rows in one transaction holds locks for its whole duration, keeps one large WAL burst replicating to standbys (replica lag spikes), and, if it fails at row 999,999, rolls back everything. Batches of 500-5,000 rows, or about 1-10 MB, capture most of the gain. Make each batch idempotent, using upserts or a batch ID, so a retry after a timeout is safe.

Queue-and-batch architecture. For high-rate events such as clicks, views, metrics and locations, do not write each event to the database on the request path. Producers append to a durable log such as Kafka. A consumer accumulates events for, say, 1 second or 5,000 events, whichever comes first, then writes one batch. That smooths bursts, because the queue absorbs spikes while the database sees a steady rate. It also enables hierarchical aggregation: the consumer collapses 5,000 "+1 view" events into 300 UPDATE ... SET views = views + n statements, one per page. See Scaling Writes for load shedding and aggregation trees.

A cautionary example: location updates. Consider a ride-hailing service where every active driver sends a GPS position every few seconds. With, say, 2 million active drivers reporting every 5 seconds, that is 400,000 writes a second. Writing each update directly as a row in a relational table, then running proximity queries over that raw table, is the design the Uber problem breakdown labels as the bad baseline. The write rate overwhelms a single primary. Every update rewrites index entries for a constantly changing location. Proximity searches over millions of fast-changing rows are slow, and the result is overload and poor latency. The usual fixes:

  • Keep only the latest position per driver in an in-memory store with geospatial support (for example Redis GEOADD), overwriting rather than appending.
  • Batch or sample the history writes into a log or time-series store.
  • Accept that a position a few seconds old is fine for matching.

The general lesson: when data is high-rate, short-lived and overwritten, the relational primary is the wrong place for every individual write. See Geospatial Indexing.

Read replicas#

Read replicas are copies of the primary that receive its changes through replication and serve read queries. For read-heavy workloads (often 10:1 or more), they multiply read capacity. Writes still go to the primary, and asynchronous replicas lag behind (usually milliseconds, sometimes seconds), so a user may not see their own write. Route reads that must be fresh to the primary. See Replication.

Read replicas in depth#

How replicas keep up. A PostgreSQL streaming replica receives the primary's WAL and replays it. Replay of ordinary changes is a single process, so a primary that writes with 32 parallel sessions is replayed by one. Under heavy write load, replicas can fall behind even on identical hardware. This is the main reason a replica fleet does not scale forever. Every replica must also apply every write, so adding replicas adds read capacity but never write capacity. MySQL replicas can apply changes in parallel (replica_parallel_workers, with dependency tracking based on the binary log's write sets in recent versions), which narrows but does not close the gap.

Sources of lag. Lag can come from:

  • Bursty writes, such as a bulk import, a big UPDATE or an index build, that the replica replays serially.
  • Long queries on the replica that conflict with replay. In PostgreSQL, replay of a vacuum cleanup may need to remove rows a replica query still sees. The replica either delays replay, up to max_standby_streaming_delay (30 seconds by default), or cancels the query. hot_standby_feedback = on prevents the cancellation by telling the primary to keep those rows, at the cost of bloat on the primary.
  • Network limits for cross-region replicas, where lag of hundreds of milliseconds is normal.
  • An undersized replica, a slower disk, or a replica busy with its own read load.

Making lag safe for users. Several techniques work, alone or together:

  • Read-your-writes by routing. After a user writes, send that user's reads to the primary for a short window, for example 5-10 seconds, tracked in the session or a cookie.
  • Read-your-writes by position. Return the commit's log position to the client. A replica serves the read only after it has replayed past that position: compare pg_last_wal_replay_lsn() with the token, or use MySQL's WAIT_FOR_EXECUTED_GTID_SET.
  • Staleness budget per query. Product listings tolerate seconds of lag. Account balances and "did my payment go through" pages do not. Encode the requirement at the call site rather than routing everything blindly.
  • Monitor and eject. Remove a replica from the read pool when its lag exceeds the budget, rather than serving stale data silently.

Replicas for isolation, not only scale. A dedicated replica for analytics, exports or reporting keeps heavy scans away from the primary's buffer cache. A delayed replica, applying WAL one hour late (recovery_min_apply_delay), gives a quick recovery path from an accidental DROP TABLE. Replicas are also the failover targets for high availability, covered with synchronous versus asynchronous trade-offs in Replication.

When replicas are the wrong tool. Replicas do not help write-bound workloads, and they make a bad query more expensive, because now it runs on several machines. If the read load comes from a few hot keys (a celebrity profile, a homepage), a cache absorbs it at a fraction of the cost. Replicas fit broad read load over a large working set, which a cache cannot hold. See Scaling Reads.

Vertical scaling#

A bigger machine (more CPU, RAM and faster disks) is often the cheapest next step: no code changes, no new failure modes. Cloud databases scale to instances with hundreds of vCPUs and terabytes of RAM. More RAM is especially effective because the working set (hot data and indexes) then fits in the buffer pool, removing most disk reads. Limits: cost grows faster than capacity at the top end, there is still a ceiling, and resizing may need a brief failover. See Scaling Up vs Scaling Out.

Vertical scaling in depth#

How far one machine goes today. Hardware has grown faster than most textbooks assume. General-purpose cloud instances reach 128 vCPUs and 512 GiB of memory (for example AWS's m6i.32xlarge). Memory-optimised instances reach 4 TB (x1e.32xlarge), and high-memory instances reach 24 TB. Local NVMe instances offer tens of TB of SSD. A modern NVMe drive handles hundreds of thousands of random reads per second at around 100 µs each. Many systems that were sharded in 2012 would fit comfortably on one primary today. Advice to "shard at 100 GB" is badly out of date. A single PostgreSQL or MySQL primary with multiple terabytes of data is routine when the working set fits in memory and the queries are indexed.

What a bigger box buys, resource by resource.

  • RAM is usually the most valuable. When the hot working set (frequently read rows plus the upper levels of every index) fits in the buffer pool, most reads never touch disk, and p99 latency drops sharply. A cache hit ratio falling from 99.9% to 99% means ten times more disk reads.
  • CPU helps with concurrent queries, parallel query plans and compression, but per-query latency depends more on single-core speed.
  • Disk IOPS and throughput matter for write-heavy workloads, checkpoints, vacuum and cache misses. On cloud volumes, provisioned IOPS is often the cheapest upgrade.
  • Network matters for replication fan-out and bulk exports.

Its limits. Price grows faster than capacity at the top end. The largest instances can cost several times more per core than mid-sized ones. One primary is still one failure domain and one write path, and resizing usually means a failover to a pre-sized replica, which is a brief blip of seconds to a minute. Some limits do not move with hardware at all: a single hot row, a lock-heavy schema, or replication replay on a replica. Vertical scaling is the right next step far more often than interviews suggest, as long as you know which of those walls you will eventually meet. See Scaling Up vs Scaling Out.

The order to apply database scaling strategies#

Move down only when the previous step is exhausted, because each step adds cost, complexity or consistency problems. Steps 1-3 rarely change the architecture; step 4 adds staleness; step 5 adds replica lag; step 7 changes how the application queries data and is hard to reverse. See Caching Fundamentals.

The scaling order in depth: one service, growing#

The order makes more sense when traced through one system. Take an online store's catalogue and order service on PostgreSQL, and grow it.

Stage 1: 200 requests per second, 4 vCPU and 16 GB. Pages feel slow at peak, and database CPU sits at 85%. pg_stat_statements shows that the top query by total time is the product page's "related products" lookup. Each call is 40 ms because of a sequential scan on product_tags, and it runs 150 times a second. A composite index cuts it to 0.4 ms, and CPU drops to 30%. The second entry is an N+1 on order history, fixed with one batched query. No architecture changed. This stage commonly removes 50-90% of the load.

Stage 2: 2,000 requests per second. Errors appear during deploys: too many clients. Forty pods × 20 connections overlap with forty new pods. PgBouncer in transaction mode with 40 server connections fixes it, and statement timeouts are added. The nightly import that inserted 2 million rows one at a time took 70 minutes. Rewritten with COPY into a staging table and a single INSERT ... ON CONFLICT, it takes 3 minutes.

Stage 3: 5,000 requests per second, 400 GB of data. The cache hit ratio slips to 97% as the working set outgrows 16 GB, and p99 latency triples. Moving to 32 vCPU and 256 GB puts the whole hot set in memory. That is a 30-second failover and a bigger bill, but no code change.

Stage 4: 20,000 requests per second, 90% of them reads. Product pages are read millions of times and change a few times a day, so a Redis cache with a 60-second TTL and explicit invalidation on product updates absorbs 95% of those reads. The cache hit rate, not the database, now determines read capacity. See Caching Fundamentals.

Stage 5: 40,000 requests per second, broad read load. Search-result pages and order history have too many distinct keys to cache well. Two read replicas take the order-history and reporting queries. Order confirmation pages read from the primary for 10 seconds after checkout, to avoid "where is my order" confusion caused by replica lag.

Stage 6: 3 TB of data, a 6-billion-row events table. Retention deletes run for hours and vacuum never catches up. Monthly partitions turn retention into partition drops. The admin dashboard's revenue-by-day query, which scanned 200 million rows, moves to a rollup table refreshed every 5 minutes.

Stage 7: 25,000 writes per second at peak. The primary's WAL volume and checkpoint I/O are saturated during sales, and replicas lag by 20 seconds. Now the write path itself is the limit, and the options are:

  • Move high-rate writes such as click tracking onto a queue with batched writers.
  • Split off a functional domain (inventory) into its own database.
  • Finally, shard orders by customer ID with Citus or Vitess, or by hand.

Each of these changes how the application queries data. That is why they come last.

Benchmark before you migrate. At each stage, replay realistic load before trusting a change. pgbench with custom scripts for PostgreSQL and sysbench for MySQL generate database load. Tools such as k6, JMeter, or the classic ab drive the application end to end. Profile with the slow query log, log_min_duration_statement, and the auto_explain module, which logs the plans of slow queries automatically. Benchmark with production-sized data. A 10 GB test database fits in RAM and hides exactly the problems that appear at 400 GB.

A note on query caches. MySQL once had a built-in query cache that returned stored results for identical query text. It was invalidated on every write to any table involved, and it was protected by a global mutex, so on write-heavy or highly concurrent workloads it often reduced throughput. It was deprecated in MySQL 5.7.20 and removed in 8.0. The lesson generalises: cache at the application layer, where you control keys and invalidation, rather than relying on a database-wide result cache.

Performance cheat sheet#

SymptomLikely causeFirst fix
One query slowMissing or wrong index, stale statisticsEXPLAIN ANALYZE, composite index, ANALYZE
Page slow, each query fastN+1 queriesJoins, batched IN queries, eager loading
"Too many connections", high memoryNo poolingPgBouncer / RDS Proxy, smaller app pools
Deep pages slowLarge OFFSETKeyset (cursor) pagination
High CPU, many identical readsHot read path hitting the DBCache, denormalized counters
Slow bulk ingestRow-by-row commitsMulti-row inserts, COPY, queue and batch
Writes wait, timeouts on one rowLock contentionShorter transactions, atomic updates
Table and index bloat, slow over timeDead rows not cleaned (Postgres)Tune autovacuum, partition and drop old data
Disk reads highWorking set larger than RAMMore RAM, smaller indexes, archive cold data
Writes at primary's limitWrite volume beyond one nodeBatch, then shard

Numbers to know for database performance#

These are rough, order-of-magnitude figures for current hardware, useful for back-of-the-envelope estimates. Always measure your own workload.

QuantityTypical valueWhy it matters
Read from RAM (buffer pool hit)about 100 ns per access, microseconds per rowCached queries are CPU-bound
NVMe SSD random readabout 100 µsA cache miss costs about 1,000× a RAM hit
Network round trip, same AZ0.2 - 0.5 msDominates simple queries, multiplies with N+1
Round trip, cross-AZ / cross-region1 - 2 ms / 50 - 150 msSynchronous replication and chatty clients
WAL flush on a cloud block volume0.5 - 2 msCaps serial single-row commits
Simple indexed point read on one PostgreSQL / MySQL node1 - 5 ms end to end, tens of thousands per second per nodeOne primary serves a lot of reads
Batched inserts on one node50,000 - 500,000+ rows per secondBatching beats sharding for ingest
Useful active connectionsabout 2-4 × CPU coresBigger pools add contention
Cache hit ratio target (OLTP)99% or higherBelow this, disk I/O dominates
Replica lag (healthy, same region)milliseconds to under a secondSeconds under write bursts
Single primary data size, comfortablesingle-digit TB with a hot set in RAMShard for write rate before size
Single hot rowa few hundred to a few thousand updates per secondFix with model changes, not hardware

Common estimation mistakes. Interviewers often see candidates:

  • Sharding a database that would fit on one modern server.
  • Assuming every query costs 10 ms or more when indexed point reads cost about 1 ms.
  • Adding Kafka and a fleet of workers for a write rate a single primary handles with batching.

The reverse mistake also happens: claiming one row can absorb 50,000 increments a second. Use the table above to sanity-check both directions.

When to Use It#

  • Any time p95 or p99 latency rises, or database CPU, I/O or connections near their limits.
  • Before proposing sharding or a new database; prove the cheaper steps are exhausted.
  • During capacity planning for 10x growth.

When NOT to Use It#

  • Do not micro-tune queries that run once a day; focus on total time.
  • Do not add caches or replicas to hide an obviously missing index.
  • Do not shard because a single table is "large"; partitioning or archiving may be enough.

How to Implement It#

  1. Measure: enable pg_stat_statements or the slow log; track p95 latency, connections, CPU, cache hit ratio and replica lag.
  2. Fix the top queries by total time with indexes and rewrites; eliminate N+1 patterns.
  3. Add pooling, right-size pools, and batch writes.
  4. Scale up until the working set fits in memory.
  5. Add caching and read replicas for read-heavy paths, with a freshness plan.
  6. Partition large time-based tables; add materialized views for heavy aggregates.
  7. Shard only with a clear write or size limit in sight, and a shard key from your access patterns.
TechnologyFits when
pg_stat_statements, MySQL Performance SchemaFinding the most expensive queries
PgBouncer, RDS Proxy, ProxySQLConnection pooling and routing
pganalyze, Percona Monitoring, Datadog DBMOngoing query and plan monitoring
Citus, VitessSharding PostgreSQL or MySQL when needed

Trade-offs#

StepGainCost
Indexes and query fixesOften 10-1000x on specific queriesSome write overhead
Pooling and batchingMore throughput, fewer connectionsPool configuration; transaction-mode limits
Vertical scalingSimple, immediateCost; hard ceiling
CachingLarge read offloadStaleness, invalidation
Read replicasRead capacityReplica lag, read-your-writes issues
Partitioning / materialized viewsSmaller scans, cheap retentionPartition-key design; refresh staleness
ShardingWrite and size scaleCross-shard queries, operational complexity
Connection pooler (PgBouncer, RDS Proxy)Thousands of clients on a few dozen server connectionsAnother hop, transaction-mode session limits
Rollup tables and incremental viewsDashboards read thousands of rows instead of billionsRefresh jobs, staleness, backfill logic
Queue-and-batch writesSmooths bursts, 10-100x ingest per nodeLatency until flush, at-least-once semantics, idempotent writes
Relaxed commit durabilityMany times more small commits per secondCan lose the last fraction of a second of commits on crash

Common Pitfalls#

  • Optimising the slowest query instead of the one with the most total time.
  • ORMs with lazy loading in loops (N+1).
  • Huge app-side pools that overwhelm the database.
  • Sharding before trying indexes, pooling and replicas.
  • Partitioning on a column most queries do not filter by, so pruning never happens.
  • Trusting EXPLAIN estimates without ANALYZE, and missing a 1,000x row misestimate.
  • Deep OFFSET pagination on large tables instead of keyset cursors.
  • Raising max_connections to fix "too many clients" instead of adding a pooler.
  • Doing HTTP calls inside open transactions, inflating connection hold time.
  • Benchmarking on a small test database that fits in RAM.
  • Refreshing a full materialized view over billions of rows every few minutes.

Real-World Examples#

PgBouncer is widely used in front of PostgreSQL to multiplex many client connections onto a small number of server connections, and managed services such as Amazon RDS Proxy offer the same pattern.

Vitess, created at YouTube to scale MySQL, adds connection pooling, query rewriting and sharding on top of MySQL, and is now a CNCF project.

Stack Overflow has publicly described serving its very high traffic from a small number of large SQL Server machines with large amounts of RAM, a well-known example of vertical scaling and query tuning instead of early sharding.

Slack, GitHub and Shopify have each written publicly about adopting Vitess to shard MySQL once single clusters reached their write and size limits.

In the Interview#

Handling database performance questions in an interview#

Lead with numbers, not tools. When the interviewer asks "what if the database becomes the bottleneck?", first estimate whether it actually is one. For example: "10 million daily users, 20 reads each, is about 2,300 reads a second on average and maybe 10,000 at peak. A single primary with indexed queries and a cache handles that. The write side is 200 a second. So I would not shard. I would index for the three access patterns, pool connections, cache the product pages, and add a replica for reporting." That shows judgement, which is what the question tests.

Name the bottleneck resource. "Slow" is not a diagnosis. Say which resource is saturated: CPU (bad plans, too many queries), memory (working set larger than RAM), disk I/O (cache misses, checkpoints), connections (no pooling), locks (hot rows), or the write path (WAL volume, replica replay). Each has a different fix, and naming it is what separates a staff-level answer from a list of buzzwords.

Walk the ladder out loud, briefly. "Queries and indexes first, then pooling and batching, then a bigger instance, then cache, then replicas, then partitioning and rollups, then sharding." Give one sentence per rung and tie each to your design's numbers. Then spend the time on the rung your design actually needs.

Expect these follow-ups:

  • "How would you find the slow query?" Use pg_stat_statements sorted by total time, then EXPLAIN (ANALYZE, BUFFERS) and compare estimated with actual rows.
  • "Why not just add replicas?" They add read capacity only, they lag, and they do not fix a bad plan. Caching the hot keys is cheaper.
  • "How many connections?" Use Little's law: transactions per second times hold time, plus headroom, behind PgBouncer.
  • "Your write rate is 100,000 per second." Queue and batch first, aggregate where possible, then shard by the key that keeps transactions on one shard.
  • "When would you denormalise?" When the read-to-write ratio is high and the join or aggregate is on the hot path. Say how you keep the copy correct: same transaction, trigger, or CDC.

Red flags to avoid: sharding at "100 GB", ignoring connection limits for a fleet of pods, caching without an invalidation story, and assuming replicas are always fresh.

Deep Dive: Memory, autovacuum and plan stabilityShow

Working set and buffer cache hit ratio. For OLTP, aim for a buffer cache hit ratio above 99%. When the working set outgrows RAM, latency jumps because random reads go to disk; this often appears suddenly as data grows past a threshold.

Autovacuum in PostgreSQL. Updates and deletes leave dead row versions. Autovacuum cleans them and also prevents transaction ID wraparound. Default settings are conservative for large, busy tables; tune per-table thresholds, and watch for long-running transactions that block cleanup.

Plan regressions. The same query can suddenly switch to a bad plan after statistics change or data skews. Defences: monitor plans of top queries, extended statistics for correlated columns, and in some databases plan pinning or hints. Parameterised queries can hit generic plans that suit typical values but not rare ones.

Write path tuning. Larger WAL and checkpoint settings smooth I/O spikes; faster disks cut commit latency; group commit helps many small concurrent transactions.

Deep Dive: Inside the cost-based optimizer and why plans failShow

Plan search is a combinatorial problem. For a join of n tables, the number of possible join orders grows factorially. With bushy trees allowed, 10 tables already have billions of orderings. System R's dynamic programming avoids enumerating them all. It finds the best plan for every subset of tables, building from pairs up, and keeps the cheapest plan per subset and per "interesting" sort order. That is still exponential, so PostgreSQL switches to a randomised genetic search (GEQO) when a query joins 12 or more relations (geqo_threshold). It also stops reordering explicit joins beyond join_collapse_limit (8). Queries with very many joins can therefore get worse plans simply because the search gave up.

Cardinality estimation is the weak link. Viktor Leis and colleagues tested several optimizers on a real-data benchmark (the Join Order Benchmark) in "How Good Are Query Optimizers, Really?" (VLDB 2015). They found that row-count estimates for multi-join queries were routinely wrong by orders of magnitude, and that these errors, more than the cost model, caused bad plans. Errors compound. If each of four joins is misestimated by 5×, the final estimate can be off by 625×. That is why the most valuable tuning habit is comparing estimated with actual rows in EXPLAIN ANALYZE, and fixing the first node where they diverge.

The cost model in brief. PostgreSQL costs plans in abstract units. seq_page_cost (1.0) is the baseline, random_page_cost (4.0 by default) is the penalty for random page reads, and cpu_tuple_cost and cpu_operator_cost cover CPU work. The defaults assume spinning disks. On SSDs, many teams lower random_page_cost to about 1.1-1.5, which makes index scans look cheaper and is often correct. effective_cache_size tells the planner how much data is probably cached, and a realistic value also favours index plans.

Defending against plan regressions.

  • Keep statistics fresh. Raise the statistics target on skewed columns (ALTER TABLE ... ALTER COLUMN ... SET STATISTICS 1000), and add extended statistics for correlated columns.
  • Log plans of slow queries with auto_explain, so a regression can be compared with yesterday's plan.
  • Use plan pinning where it exists. SQL Server's Query Store can force a known-good plan. Oracle has SQL Plan Management. PostgreSQL has no built-in hints, but the pg_hint_plan extension adds them, and Aurora PostgreSQL offers query plan management.
  • Test major-version upgrades against captured production queries, because planner changes between versions are a common source of regressions.

Adaptive and learned approaches. Some engines adjust plans during execution. Oracle's adaptive plans and SQL Server's adaptive joins switch between nested loop and hash join once the actual row count is known. Research systems explore learned optimizers. Bao, by Ryan Marcus and colleagues (SIGMOD 2021), learns which hint sets to apply to a traditional optimizer from observed run times, rather than replacing it. Production systems still rely mainly on classical cost-based planning plus good statistics.

Memory knobs that change plans. work_mem decides whether a hash join or sort fits in memory. Raising it from 4 MB to 64 MB for a reporting role can turn a disk-spilling plan into an in-memory one. Set it per role or per session, not globally, because it applies per operation per connection. shared_buffers is commonly about 25% of RAM on a dedicated PostgreSQL server, with the operating system's page cache holding much of the rest. InnoDB's innodb_buffer_pool_size is commonly 50-75% of RAM, because InnoDB bypasses the OS cache for its data files.

Key Takeaways#

  • Start with measurements: fix the queries with the most total time using EXPLAIN and the right indexes.
  • Eliminate N+1 queries, pool connections (PgBouncer) and batch writes; these are cheap and large wins.
  • Scale in order: queries, config and pooling, bigger machine, cache, read replicas, partitioning and materialized views, then sharding.
  • Partitioning splits a table on one server and makes retention cheap; sharding splits data across servers.
  • Each step adds cost or consistency trade-offs, so move to the next only when the previous one is exhausted.
  • Diagnose the saturated resource first: CPU, memory, I/O, connections, locks or the write path.
  • Compare estimated and actual rows in EXPLAIN ANALYZE; misestimates cause most bad plans.
  • Size pools with Little's law and keep transactions short; fewer active connections often means more throughput.
  • Batching turns about 1,000 rows per second into 100,000+ by amortising round trips and log flushes.
  • Modern single servers hold terabytes and serve tens of thousands of queries per second; shard for write rate, not size.