Database Scaling: Vertical, Horizontal, and Read Replicas
Learn strategies for scaling databases beyond a single instance: vertical scaling, read replicas, write scaling, and when to choose each approach.
Database scaling starts with identifying the resource or query path that limits the workload. Vertical capacity, read replicas, caching, and sharding address different constraints and add different operational costs. Measure throughput and user-facing latency under a representative load before choosing a change. This guide compares scaling options, explains common bottlenecks, and points to a capacity-planning worksheet for deeper estimates.
Introduction
Vertical scaling means bigger servers. More CPU cores, more memory, faster disks. This is the simplest approach. You take your existing database and move it to a more powerful machine.
The advantage is simplicity. No application changes required. Your single-server transactions stay ACID-compliant. Your queries work exactly as before.
The disadvantage is limits. Server sizes have caps. A database that needs 64 cores is not going to fit on a server with 32. And costs scale faster than capacity. A server with twice the resources rarely costs twice as much.
Vertical scaling works best early in a system’s life. When traffic is modest and growth is predictable, throwing bigger iron at the problem is often the cheapest solution in engineering time.
Measure Capacity Before Scaling
Capacity planning
Track workload and service signals together: request latency percentiles, errors, query throughput, connection-pool waits, lock waits, CPU, memory pressure, storage latency, free disk, and replica lag where relevant. A single utilization percentage does not tell you whether the database is at capacity. For example, a low CPU average can hide one serialized query or a full connection queue.
Record the database engine and version, topology, dataset shape, query mix, test data, concurrency, and the SLOs you intend to meet. Capacity predictions only make sense with those assumptions attached. For detailed capacity-planning methods, see Capacity Planning.
Capacity worksheet and load-test procedure
The following worksheet makes a benchmark repeatable. Fill in the workload and pass criteria before running it; do not use the values from another system as a forecast.
| Worksheet field | Record for this system |
|---|---|
| Database engine, version, instance size, and topology | Include primary, replicas, pooler, and storage type |
| Dataset | Row counts, table sizes, indexes, and representative value distribution |
| Request mix | Read/write operations, query shapes, transaction sizes, and batch jobs |
| Target load | Expected throughput and concurrency for normal and peak periods |
| Pass criteria | Application p95/p99 latency, error rate, and freshness targets from the service SLO |
| Saturation signals | Pool wait, lock wait, CPU, I/O latency, memory pressure, disk runway, and replica replay lag |
| Recovery check | Repeat the workload while exercising the intended failover or recovery procedure |
A practical test loop is:
- Restore a production-like dataset to an isolated environment and record the exact engine version and configuration.
- Warm the system, then run the normal query mix long enough to establish a baseline.
- Increase concurrency or request rate in documented steps. Record throughput, latency percentiles, errors, pool queueing, database waits, and storage metrics at each step.
- Repeat the expected peak and a recovery scenario. A test that measures only a healthy primary does not describe failover capacity.
- Compare the results with the pass criteria. Repeat any run that was affected by unrelated load or an incomplete warmup.
- Choose a scaling trigger from the metric that is approaching its SLO or capacity limit. Record who responds and how much headroom is needed for maintenance and recovery.
Treat the results as a measurement of the tested workload and environment. They do not predict a different data distribution, query mix, version, or failure mode. Use the capacity planning guide for estimates that need to include growth and recovery assumptions.
Cost & Decision Framework
Compare changes against the measured bottleneck
| Option | Consider it when | Costs and checks |
|---|---|---|
| Vertical capacity | The workload is limited by a resource and the platform offers useful headroom on a larger instance | Compare a current provider quote with a representative load test; larger instances may have different price and performance curves |
| Read replicas | Reads dominate and the application can tolerate or route around replica lag | Replicas add read capacity only for eligible queries; monitor replay lag and account for extra instances and failover work |
| Cache | Repeated reads can use a defined freshness window | Measure hit rate and origin load; specify invalidation and behavior when the cache is unavailable |
| Sharding | A single node cannot meet storage, write, or recovery objectives within the available operating envelope | Routing, cross-shard operations, rebalancing, backups, and recovery become application and operations concerns |
Compare capacity plans with a worksheet
Do not treat a server size, price, or throughput number from another environment as a break-even result. Fill in this table with current provider quotes and measurements from the same workload, dataset, region, and test window:
| Input | Single primary / vertical plan | Replica or shard plan | Evidence and date |
|---|---|---|---|
| Instance types, storage, and network | Measure or quote | Measure or quote | Record provider, region, and quote date |
| Read and write throughput at target SLO | Load-test result | Load-test result | Include query mix, data shape, and concurrency |
| Failover and recovery behavior | Rehearsal result | Rehearsal result | Include recovery time and data-loss window |
| Monthly service and operations cost | Current quote plus operation estimate | Current quote plus operation estimate | Include storage, network, backups, and labor assumptions |
Choose by the constraint, not a user-count stage
There is no fixed user or QPS threshold at which every database should add replicas, cache, or shard. Start with the metric that misses its SLO or is approaching a tested limit. If a larger primary passes the workload and recovery tests at acceptable cost, vertical scaling may be simpler. If reads are the limit, test replica routing and lag. Consider a cache only when measured repeated reads and freshness requirements support it. Shard when the current design cannot meet the required workload or recovery objective within its practical limits, and the team can operate the added routing and recovery paths.
Use the breached SLO or measured constraint to choose what to investigate next. These signals do not prescribe a topology change by themselves:
| Signal under the representative workload | Next check |
|---|---|
| p95/p99 latency misses its target while average CPU is low | Inspect query plans, lock waits, connection queueing, and storage latency |
| CPU or storage stays saturated at expected peak and latency misses its target | Compare a query or configuration change with a larger instance in the same load test |
| Connection-pool wait time rises | Check pool limits across all application instances and the database’s connection capacity |
| Replica replay age exceeds the read-freshness target | Route freshness-sensitive reads appropriately and test replica capacity and recovery |
| Disk runway conflicts with retention, maintenance, or recovery needs | Recheck data growth, indexes, backup retention, and storage options |
Start with the simplest change that addresses the measured constraint. Re-run the same workload and recovery checks before keeping it.
Consistency Considerations
Scaling introduces consistency trade-offs. Read replicas are typically asynchronously replicated. Writes to primary take time to propagate to replicas.
# This might fail if replica lags behind primary
user = replica_db.query("SELECT * FROM users WHERE id = ?", user_id)
if user['email'] != new_email:
# User might see old email briefly
primary_db.execute("UPDATE users SET email = ?", new_email)
Read-after-write consistency is not guaranteed with replicas. A user might write data and immediately read it from a replica that has not yet received the write. Solutions include:
- Read from primary after writes
- Synchronous replication (higher latency, lower availability)
- Session-based routing (read from primary for a window after writes)
Eventual consistency is acceptable only for reads whose consumers can tolerate stale results. Set a freshness target for each read path and route writes or freshness-sensitive reads accordingly.
Query Performance Optimization
Query Optimization Deep Dive
Inspect query plans before adding infrastructure. An index can reduce the work for a particular query, but it also adds storage and write cost; the effect depends on the plan, table shape, and workload. Start with the queries that contribute most to measured latency or resource use, change one thing, and compare results.
Step 1: Capture the right queries. Enable slow query logging in PostgreSQL with log_min_duration_statement = 1000 (logs queries over 1 second) or use the pg_stat_statements extension to track cumulative resource usage across all queries. In MySQL, performance_schema and the sys.metrics schema give you similar visibility. The goal is to sort queries by total time — queries that run frequently and take 50ms each consume more resources than a single 5-second query that runs once a day. Focus on the top 10 queries by total time first.
Step 2: Classify the pattern. Most slow queries fall into a handful of patterns with specific fixes:
| Pattern | How to spot it | Fix |
|---|---|---|
| Missing index | Seq Scan in EXPLAIN on large table | Add index on WHERE/JOIN column |
| N+1 query | One query per loop iteration in app | Batch fetch or JOIN |
| Inefficient join | Cross product in EXPLAIN | Add filter conditions, rewrite JOIN order |
| Unnecessary sort | Sort on unindexed columns | Add index to eliminate sort, or remove ORDER BY |
| Full table scan | Large rows estimate vs small actual | Partition the table, or add targeted index |
| Stale statistics | Rows estimate >> actual rows | Run ANALYZE/VACUUM |
Step 3: Benchmark before touching anything. Record current p50, p95, and p99 query latency, plus the query plan from EXPLAIN ANALYZE. Apply one change at a time — if you add an index, change the query rewrite, and increase shared_buffers simultaneously, you will not know which change helped. After each change, re-run the benchmark and compare. Record the before-and-after latency and resource use from the same dataset and query mix. Treat a plan change as useful only if the result meets the workload’s pass criteria without creating an unacceptable write or storage cost.
Step 4: Validate with the production workload. Test queries against real data volume. A query that performs well on 10,000 rows may be fine on 100,000 rows only if an index makes the difference. EXPLAIN ANALYZE shows actual rows versus estimated rows — a large gap means the query planner is making poor decisions because statistics are stale. After adding an index, check that the query plan uses it (Index Scan, not Seq Scan) and that actual rows match estimates.
The most common mistake is adding indexes without verifying they are used. Run EXPLAIN ANALYZE on the same query after adding the index and confirm the plan changed. An index that exists but is not used consumes storage and slows writes for no benefit.
Reading EXPLAIN Plans
Every major database provides execution plan visualization:
-- PostgreSQL
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT u.name, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at > '2024-01-01'
GROUP BY u.id;
-- Key things to look for:
-- - Seq Scan: full table scan (often indicates missing index)
-- - Hash Join vs Nested Loop: Hash is better for large sets
-- - Rows estimate vs actual rows: large mismatch means stale statistics)
For MySQL:
EXPLAIN FORMAT=JSON
SELECT u.name, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at > '2024-01-01'
GROUP BY u.id;
Critical patterns to identify in EXPLAIN output:
| Pattern | Indicates | Action |
|---|---|---|
| Seq Scan on large table | Missing index on WHERE/JOIN column | Add appropriate index |
| Hash Join with large rows | May exceed memory for hash table | Increase work_mem or use partial indexes |
| Nested Loop with large inner | O(n²) behavior | Add index, rewrite to use Hash Join |
| Rows estimate ≫ actual | Stale statistics | Run ANALYZE or VACUUM ANALYZE |
| Index Only Scan | Optimal — data from index alone | Ensure covering indexes for frequent queries |
Hypothetical Failure Scenarios
Use these as review exercises, not as reports of documented production incidents. Replace any workload inputs with measurements from the system being designed.
A cache outage drives a read surge
A service loses cache entries or cannot reach its cache, so requests fall through to the database. Check whether the database can handle the resulting miss rate, whether retries will multiply the traffic, and how the application sheds load if it cannot. Test cache recovery without letting every instance refresh the same hot keys at once.
A shard grows faster than its neighbors
A tenant or key range accumulates more rows and traffic than the average shard. Track data size and request distribution per shard, then rehearse moving that range while writes continue. A uniform hash may spread new keys but still leave historical skew or expensive cross-shard queries.
A reporting workload makes replicas stale
A dashboard polls a replica more often than its users need fresh results. Compare its query rate and replay age with the dashboard’s freshness target. Cache or coalesce identical requests where appropriate, and keep reports from retrying aggressively when the replica is already behind.
Application pools exceed database capacity
Each application process opens its own pool. The total possible connections are approximately process count times pool size, before accounting for migrations, monitoring, and administration. Compare that total with the database’s safe connection budget and test pool wait behavior during scale-out.
A synchronous standby stops acknowledging writes
If a required standby becomes unreachable, commit behavior depends on PostgreSQL’s synchronous-standby and timeout configuration. Exercise the partition and recovery paths, including fencing and promotion rules; do not assume writes can switch to asynchronous mode safely without an explicit policy.
Trade-off Analysis
Database scaling involves fundamental trade-offs. Understanding these helps you make decisions that match your workload requirements.
Consistency vs. Availability
| Approach | Consistency | Availability | Use Case |
|---|---|---|---|
| Synchronous replication | Strong | Lower (replica required) | Financial transactions, inventory |
| Asynchronous replication | Eventual | High | Read-heavy apps, social feeds |
| Multi-leader | Eventual | Highest | Geographic distribution |
| Leaderless (quorum) | Configurable | Very high | Distributed systems, Cassandra |
Recommendation: Start with asynchronous replication. Add synchronous replication only when consistency requirements demand it, and implement proper timeouts and fallback behavior.
Write Scaling vs. Complexity
| Approach | Write Scale | Operational Complexity | Data Integrity |
|---|---|---|---|
| Single primary | Limited | Low | Strong |
| Multi-leader | Medium | High | Conflict-dependent |
| Sharding | High | Very high | Application-managed |
Recommendation: Test vertical capacity and read replicas where they address the measured constraint before adopting sharding. Sharding adds routing, rebalancing, cross-shard query, backup, and recovery work; estimate that operating cost for the system rather than using a fixed multiplier.
Index Overhead vs. Query Performance
| Index Strategy | Write Overhead | Read Performance | Storage |
|---|---|---|---|
| No indexes | Lowest | Full table scans | Lowest |
| Minimal (primary lookups) | Low | Good for point queries | Low |
| Covering indexes | Medium | Excellent for specific queries | Medium |
| Many indexes | High | Fast for varied queries | High |
Recommendation: Add indexes based on query patterns measured in production. Remove unused indexes. Balance read performance gains against write overhead.
Connection Pool Sizing
| Pool Size | Throughput | Latency | Risk |
|---|---|---|---|
| Too small | Low | High (queuing) | Underutilization |
| Optimal | High | Low | Balanced |
| Too large | Medium | High (contention) | Memory pressure |
Recommendation: Start with the formula (core_count * 2) + effective_spindle_count. Monitor connection wait times and adjust based on observed behavior.
Common Pitfalls / Anti-Patterns
-
Scaling too late: Monitoring gaps cause sudden performance crises. Monitor proactively and scale before hitting limits.
-
Premature sharding: Sharding introduces significant complexity. Vertical scaling plus caching handles most workloads longer than expected.
-
Ignoring read-after-write consistency: With replicas, reads might return stale data immediately after writes. Implement appropriate consistency levels.
-
Cache invalidation complexity: Caching stale data is worse than no caching. Ensure invalidation is correct before caching frequently-changing data.
-
Connection pool misconfiguration: Too few connections starve the application. Too many exhaust database resources. Size appropriately.
-
Not testing failover: If failover is broken, you only find out during an outage. Test regularly in staging.
-
Sharding without clear access patterns: Without understanding how data is accessed, shard keys will be wrong. Design access patterns first.
-
Caching without measuring: Cache adds complexity. Measure cache hit rates and only cache when it provides meaningful benefit.
Architecture Sketches (Hypothetical)
These examples illustrate design questions. They do not describe the current internals of a named company.
Read-heavy question-and-answer service
Suppose a question page combines a post, answers, and a small set of related data. A cache may reduce repeated reads if the product accepts a defined freshness window. Test the cache with the actual page mix and dataset, then compare cache hit rate, origin query load, p95/p99 latency, and invalidation behavior after an edit or new answer. An index should still make cache misses affordable; a cache does not repair an inefficient query plan.
Geographic search service
A travel-search service could partition listings by region when most queries filter to one region. That routes common searches to a small part of the data, but cross-region searches need fan-out and result merging. Measure the distribution of records and query volume before choosing the region key; popular destinations can create skew, and rebalancing must work while the service is in use.
Repository-hosting service
A code-hosting service could keep most data for one repository together so repository-scoped reads and writes route to one shard. Cross-repository search and account-wide activity then become multi-shard operations. A routing map can make shard placement changeable, but it introduces its own consistency, caching, and recovery requirements. Test the query paths that cross the boundary before adopting the key.
Interview Questions
The bottleneck is CPU, not memory. More RAM would help if the bottleneck was cache misses — if you were hitting disk because data did not fit in memory, adding RAM would reduce disk I/O and CPU time spent waiting. But with CPU at 90% and memory at 40%, your working set fits in memory and the CPU is doing compute work. Options: upgrade CPU (vertical scaling), add read replicas to distribute read queries across multiple servers, optimize slow queries to reduce CPU per transaction, or implement caching for hot queries to reduce database load.
First confirm that reads are the bottleneck and identify which queries can tolerate replica freshness. A read-heavy mix alone does not tell you how much capacity replicas will add: query cost, replica size, routing, and replay lag all matter. Benchmark the same request mix with the primary and candidate replicas, include failure behavior, and compare the measured result with a vertical capacity option and its current cost.
If writes are the bottleneck and replicas do not help (because replicas still funnel writes through the primary), you need to reduce write volume or distribute writes. Options: optimize write-heavy queries — maybe an UPDATE runs more often than necessary or an index is causing excessive write overhead; implement caching for data that does not need to be written to the database immediately; shard the database to distribute writes across multiple primaries; or move to a write-optimized database for specific write-heavy tables while keeping the rest on the primary.
The decision should be data-driven, not time-based. Shard when you have exhausted vertical scaling (cannot get a bigger server or the cost exceeds what sharding would cost), when you have measured that writes — not reads — are the bottleneck (replicas do not help writes), and when your data size exceeds what a single server can reasonably store. If you have a 2TB database and your largest available server has 4TB of storage, you have headroom but not for growth. If that server is already at 80% CPU and 90% storage, you need to shard or upgrade. The key metric is whether you can achieve your SLA for write latency and availability with your current architecture under projected load.
ACID (Atomicity, Consistency, Isolation, Durability) provides strong consistency guarantees with transaction isolation. It ensures that writes are immediately visible to all subsequent reads and that transactions are all-or-nothing. BASE (Basically Available, Soft State, Eventually Consistent) sacrifices strong consistency for availability and partition tolerance. ACID is appropriate for financial transactions, inventory systems, or any system where reading stale data causes real harm. BASE is appropriate for social feeds, activity logs, user sessions, or read-heavy workloads where milliseconds of staleness is acceptable. The CAP theorem shows you cannot have all three (Consistency, Availability, Partition Tolerance) simultaneously — BASE prioritizes availability while ACID prioritizes consistency.
Replication lag is the time delay between a write being committed on the primary and that write being applied on a replica. It occurs because most replication is asynchronous — the primary does not wait for replicas to confirm writes before returning success to the client. Monitoring: PostgreSQL's `pg_stat_replication` shows `sent_lsn`, `write_lsn`, `flush_lsn`, and `replay_lag`; MySQL's `SHOW REPLICA STATUS` shows `Seconds_Behind_Master`. Mitigation strategies: use synchronous replication (higher latency but zero lag), route critical reads to the primary after writes (read-after-write consistency), session-based routing (sticky reads to primary for a window after writes), or accept eventual consistency for non-critical reads. High replication lag causes stale reads where users see outdated data after updates.
A good shard key distributes writes evenly across shards (avoids hotspots), is frequently used in query filters (enables efficient routing), and has high cardinality (many distinct values). User ID or customer ID often works well because writes naturally distribute by user and queries often filter by user. A bad shard key causes hotspots: timestamp-based keys concentrate writes on the latest shard; geographic regions may cause uneven distribution if some regions have more activity. Avoid keys with low cardinality (e.g., boolean status field creates only two shards). Cross-shard queries (joining data across shards) are expensive — design keys to co-locate frequently joined data on the same shard. Test key distribution under realistic write patterns before production deployment.
Cache stampede (thundering herd) occurs when a popular cache entry expires and multiple concurrent requests all miss the cache, overwhelming the database with identical queries. Prevention strategies: probabilistic early expiration (randomize TTL so entries don't all expire at once), cache locking (only one request fetches from DB, others wait for the cached result), jittered TTLs (add random delay to TTL to spread out expiration), proactive warming (refresh popular entries before they expire), and background refresh (use a background job to refresh cache before expiration). The goal is to ensure only one request hits the database when a cache miss occurs.
Compare query or index changes with infrastructure changes on the same representative workload. An index may reduce reads for one query and increase storage or write work elsewhere. Use query plans and load-test results to decide whether the change meets the service's latency and capacity targets.
Connection pooling maintains a cache of database connections that can be reused across requests. Without pooling, each request opens a new connection (expensive handshake, authentication, session setup) and closes it afterward. With pooling, requests borrow an existing connection from the pool, use it, and return it — avoiding connection overhead. Pooling is important because: database connections are finite resources (each consumes memory, file descriptors, and server-side processes); establishing connections is slow (TCP handshake + TLS + authentication); and connection overhead limits throughput. Tools: PgBouncer for PostgreSQL, ProxySQL for MySQL, built-in pools in ORMs. Pool sizing: too small starves requests, too large wastes resources. Rule of thumb: (core_count * 2) + effective_spindle_count for PostgreSQL, adjusted based on observed wait times.
Single-leader (one primary receives writes, multiple replicas) is simple, well-understood, and provides strong write ordering — but write capacity is limited to the primary. Multi-leader (multiple primaries accept writes, each replicates to others) scales writes and provides geographic distribution but requires conflict resolution for concurrent writes and is operationally complex. Leaderless (writes go to any replica, quorum-based reads) eliminates single point of failure and scales write capacity but requires complex conflict resolution and quorum tuning. Use single-leader for most workloads — the simplicity outweighs limitations. Multi-leader for geographic distribution with write-heavy workloads. Leaderless for maximum availability and fault tolerance (Cassandra, DynamoDB). Chain replication (write flows through a chain) provides simple ordering but latency increases with chain length.
B-tree indexes maintain sorted data and support both equality and range queries — they are the default for most databases because they handle `WHERE column > value` and `BETWEEN` efficiently. Hash indexes support only equality lookups (`WHERE column = value`) but are faster for simple key lookups. Use B-tree for: columns used in range conditions, ORDER BY, GROUP BY, and any query that filters by a prefix of the index. Use hash for: lookup tables, session storage, and columns with high cardinality where only equality checks occur. Hash indexes cannot handle range scans — if you ever need `created_at > '2024-01-01'`, a hash index will not help. Index maintenance overhead matters: every write to an indexed column updates the index, so too many indexes slow writes. Balance read performance needs against write overhead.
A covering index (index-only scan) includes all columns needed by a query in the index itself, so the database never accesses the table — only the index. Use when you frequently query specific columns together and want to avoid table lookups entirely. A partial index indexes only rows matching a condition — for example, only pending orders — making the index smaller, faster to maintain, and used only for relevant queries. Use partial indexes when: a subset of rows is queried frequently (like active users vs archived), the filtered column has high cardinality but queries target a specific value, or you want to reduce index size for write-heavy tables. Both reduce I/O and improve performance, but covering indexes serve queries that need specific columns while partial indexes serve queries that filter on a specific condition.
PgBouncer (PostgreSQL) and ProxySQL (MySQL) sit between the application and database, maintaining a pool of database connections that are reused across requests. Without pooling, each request opens a new connection (TCP handshake, authentication, session setup), which is slow and resource-intensive. With pooling, requests borrow an existing connection, execute their query, and return the connection — eliminating connection overhead. Pool modes: session mode (connection returned after transaction), transaction mode (connection returned after each transaction — most common), and statement mode (connection returned after each statement). Trade-offs: connection pooling adds latency for connection reuse logic but reduces database resource usage; transaction mode pooling can break session-specific state (like `SET SESSION` variables); too-small pools starve requests, too-large waste resources; pools do not help if the bottleneck is query performance rather than connection overhead.
Read-after-write consistency means that after a user writes data, subsequent reads from the same user return the new data — not stale data from a replica that has not yet received the write. With asynchronous replication, writes propagate to replicas with a delay, so a user might write data and immediately read it from a replica that has not yet applied the write, seeing old data. Achieving read-after-write consistency: read from primary after writes (guaranteed but defeats replica benefits); synchronous replication (replicas confirm writes before client returns — higher latency, lower availability); session-based routing (sticky reads to primary for a window after writes, e.g., 30 seconds); or use causal consistency protocols that track causal dependencies. Most applications use session-based routing because it balances consistency with performance — critical reads go to primary for a short window after writes, other reads use replicas normally.
Cache stampede occurs when a popular entry expires and multiple concurrent requests all miss the cache, hitting the database simultaneously with identical queries. Prevention strategies: probabilistic early expiration (refresh cache before expiration with some probability, so entries do not all expire simultaneously); cache locking (only one request fetches from the database while others wait for the cached result — prevents duplicate DB queries); jittered TTLs (add random delay to TTL values so expiration times are spread out); proactive warming (background job refreshes popular entries before they expire); and background refresh (dedicated process updates cache independently of user requests). The goal is ensuring only one request hits the database when a cache miss occurs. Cache stampede is especially problematic for expensive queries on hot data — the thundering herd can overwhelm the database at the worst time (when the cache becomes empty).
Application-level sharding (custom shard router in code) gives you full control over shard key selection, routing logic, and cross-shard operations — you can implement any strategy that fits your access patterns. However, you must manage shard topology, handle resharding (when you add shards), and the application becomes coupled to the sharding scheme (tests and migrations are harder). Database-native sharding (MongoDB sharding, CockroachDB, Vitess for MySQL) automates shard management, rebalancing, and failover — the database handles distribution transparently. The trade-off: native sharding is easier to operate but less flexible; application-level is more flexible but adds operational complexity. Consider native sharding when your database supports it well and your access patterns fit its model. Consider application-level when you have unusual requirements (specific shard key distribution, complex cross-shard transactions) that native sharding cannot handle.
PostgreSQL uses physical streaming replication. When the primary receives a write, it records the change in the WAL (Write-Ahead Log) before applying it to the data files — this ensures durability (writes survive crashes). The primary streams WAL records to replicas via the streaming replication protocol, and replicas continuously apply them to stay in sync. Replicas are called hot standbys and can serve reads while they apply WAL. The replication slot mechanism ensures replicas retain WAL they have not yet applied, preventing the primary from removing WAL that replicas still need. Monitoring: `pg_stat_replication` shows state, sent LSN, write LSN, flush LSN, and replay lag. By default, replication is asynchronous (writes commit before replicas confirm) — synchronous replication with `synchronous_commit = on` ensures writes are confirmed by replicas before returning to the client, at the cost of higher latency. Logical replication (table-level) is separate and used for migrations and selective replication.
Column order in a composite index determines which query patterns can use the index. An index on (A, B, C) can serve queries that filter on A, on A and B, or on A, B, and C — but cannot efficiently serve queries that filter only on B or C (without A). Rule: put equality conditions first, range conditions last. If you frequently query `WHERE region = 'US' AND date > '2024-01-01'`, index on (region, date) works. If you frequently query `WHERE date > '2024-01-01'` alone, the region-first index cannot use the date range efficiently. Also consider: cardinality (high-cardinality columns first filters more rows), query frequency (put columns used in more frequent queries first), and write overhead (columns updated frequently add index maintenance cost). Test with EXPLAIN ANALYZE — if a query shows Seq Scan instead of Index Scan, the index order may not match query patterns. Avoid indexing low-cardinality columns first (like boolean status) because it creates large intermediate result sets.
Choose PostgreSQL when: you need ACID compliance (financial, inventory, any system where consistency matters), you have complex queries (joins, subqueries, window functions), you need strong JSON support (JSONB with GIN indexes), or you need advanced features (CTEs,full-text search,Geospatial with PostGIS). Choose MySQL when: you need high write throughput (MySQL's InnoDB handles write concurrency well), you prioritize read performance with replication (MySQL's replication is mature and fast), or you are building a LAMP/LEMP stack where MySQL is well-integrated. Choose MongoDB when: your data is document-structured (JSON-like, nested, variable schema), you need horizontal scaling out of the box (MongoDB sharding is mature), or your application benefits from flexible schema (rapid iteration, polymorphic data). Key factors: consistency requirements (PostgreSQL > MySQL > MongoDB for strong guarantees), scaling needs (MongoDB for automatic sharding, PostgreSQL with extensions for application-level sharding), query complexity (relational joins favor PostgreSQL/MySQL), and team expertise (familiarity matters for operational reliability).
Further Reading
Database Fundamentals
Relational databases give you ACID guarantees that make transactions reliable — particularly useful when scaling write-heavy workloads. NoSQL databases trade consistency for horizontal scalability, which matters once you outgrow what a single relational server can handle. Time series databases handle append-heavy timestamped data differently from the general-purpose databases in this guide.
Scaling relational databases is a different problem from scaling NoSQL systems. Relational databases optimize for consistency and join efficiency — you can write a query that joins across ten tables and get correct, consistent results. That strength becomes a limitation when you need to distribute data across multiple servers, because joins across network boundaries are expensive. Vertical scaling works until you hit hardware limits. Replicas handle read-heavy loads well. Sharding is where it gets hard — you have to design your schema and queries around data distribution.
NoSQL databases are built for horizontal scaling from the start. Key-value stores like Redis and DynamoDB distribute data by key with minimal coordination. Document databases like MongoDB handle variable schema and scale by collection. Column-family databases like Cassandra optimize for write throughput and geographic distribution. The catch is that your application ends up managing consistency guarantees the database used to handle for you — if you need transactions across multiple collections in MongoDB, that is application code you have to write.
Time series databases target a specific pattern: append-heavy writes (sensor readings, metrics, events) with infrequent updates, and reads that aggregate over time ranges. They use specialized storage engines (LSM trees, columnar compression) that make time-range queries fast and write throughput high. For monitoring metrics, IoT sensor data, or event logs, a time series database beats a general-purpose relational database by an order of magnitude.
- Relational Databases — Understand ACID properties, normalization, and query fundamentals
- NoSQL Databases — Compare document, key-value, column-family, and graph databases
- Time Series Databases — Optimized storage for timestamped data streams
Scaling Deep Dives
Horizontal sharding partitions rows across multiple database instances — the main tool for write scaling when your primary becomes the bottleneck. Object storage offloads binary assets (images, documents, backups) to dedicated services, letting the database handle structured data only. Both add operational complexity, which is why this guide tells you to measure before you migrate.
Sharding is where database scaling gets hard. Before sharding, every query runs on one server. After sharding, your application routes each query to the correct shard, handles cross-shard operations (joins, aggregations, transactions), and manages resharding when you add capacity. The access patterns that determine your shard key — which columns you filter on, which tables you join — become architectural constraints that are expensive to change later.
Object storage solves a different problem. Databases handle structured data with indexes well. They are bad at unstructured binary data — images, videos, backups. Object storage services (S3, GCS, Azure Blob Storage) are built for binary data: infinite scale, low cost per GB, built-in redundancy. Storing images in the database means your database grows by gigabytes per day for data that never benefits from indexing. Storing images in object storage means your database stores only a URL, and you get CDN integration, automatic replication, and lower storage costs.
Both have real operational complexity. Sharding needs careful shard key design, hotspot monitoring, and a resharding plan. Object storage needs managing the mapping between database records and stored objects, handling deletion or expiration, and making sure the application recovers if object storage is temporarily unavailable. Neither is a set-it-and-forget-it solution.
- Horizontal Sharding — Deep-dive on shard key selection, rebalancing, and cross-shard queries
- Object Storage — Scaling storage separately from compute
Operational Excellence
Scaling decisions only hold up if your operational practices keep pace. PostgreSQL, MySQL, and MongoDB each have mature monitoring ecosystems — understanding replication mechanisms and available metrics helps you catch issues before they become outages. Bookmark these official docs for when you need to debug replication lag, tune connection pools, or set up alerting thresholds.
The metrics that matter most are not the obvious ones. CPU and memory utilization show current load, but replication lag shows whether your read replicas are falling behind the primary — and whether your application might be serving stale data. Connection pool utilization shows whether your application is starved for connections or leaving them unused. Query latency percentiles (p50, p95, p99) show whether most queries are fine while a tail is suffering.
Setting up alerting is easier than setting up useful alerting. A generic “CPU > 80%” alert fires during normal spikes and trains your team to ignore it. Tie alerts to SLOs: if your database p99 latency SLO is 100ms, alert at 150ms. If your replication lag SLO is 5 seconds, alert at 15 seconds. This way, alerts fire only when something is actually wrong, and the on-call engineer knows exactly what needs fixing.
Failover testing is the most neglected operational practice. If your primary fails, how long does failover take? Does your application reconnect automatically? Do pending transactions retry correctly? You find out during an outage if you have not tested. Run failover drills in staging quarterly. Measure failover time, verify application reconnection, and document the procedure so the on-call engineer is not debugging blind at 3am.
-Database observability — PostgreSQL monitoring guide
- MySQL replication documentation — Official MySQL replication docs
- MongoDB replication explained — Replica set concepts and operations
Performance Tuning
- PostgreSQL EXPLAIN analyzer — Visualize and understand query plans
- use-the-index-luke.com — Comprehensive indexing guide for PostgreSQL and MySQL
- database-sizing calculator — Estimate database resource needs
Conclusion
Key Bullets:
- Scale vertically first, then add read replicas, then cache, then shard (in that order)
- Read replicas solve read scale; sharding solves write scale
- Caching provides the best ROI for reducing database load when access patterns allow
- Monitor CPU, memory, connection counts, and replication lag
- Test failover procedures before you need them in production
- Choose scaling approach based on actual bottleneck (measure first)
Copy/Paste Checklist:
# Read replica routing with connection pooling
from sqlalchemy import create_engine
from sqlalchemy.pool import QueuePool
# Primary for writes
primary_engine = create_engine(
"postgresql://user:***@primary:5432/mydb",
pool_size=5, max_overflow=10
)
# Replica for reads
replica_engine = create_engine(
"postgresql://user:***@replica:5432/mydb",
pool_size=20, max_overflow=20
)
# Use primary for writes, replica for reads
def write_operation(sql, params):
with primary_engine.connect() as conn:
return conn.execute(sql, params)
def read_operation(sql, params):
with replica_engine.connect() as conn:
return conn.execute(sql, params)
Observability Checklist
Metrics to Monitor:
- Query latency by type (read, write, analytical)
- Database CPU, memory, disk I/O utilization
- Connection pool utilization and wait times
- Replication lag (seconds behind primary)
- Cache hit ratio and memory utilization
- Shard distribution and hotspot detection
- Throughput (queries per second, transactions per second)
- Queue depths and backpressure indicators
Logs to Capture:
- Slow query logs (queries exceeding thresholds)
- Connection events (opens, closes, failures)
- Replication status changes and errors
- Failover events and decision rationale
- Cache evictions and expiration patterns
- Application errors related to database access
Alerts to Set:
- CPU or memory utilization > 80%
- Replication lag > 30 seconds
- Connection pool > 80% utilized
- Cache hit ratio < threshold (e.g., < 80%)
- Query latency p99 exceeding SLA
- Shard skew exceeding threshold (e.g., > 2x average)
- Disk usage > 85%
# Database scaling monitoring example
def check_db_health(db_config):
metrics = {
'cpu_percent': get_db_cpu(),
'memory_percent': get_db_memory(),
'connections': get_connection_count(),
'replication_lag': get_replication_lag(),
'cache_hit_ratio': get_cache_hit_ratio()
}
alerts = []
if metrics['cpu_percent'] > 80:
alerts.append(f"CPU critical: {metrics['cpu_percent']}%")
if metrics['replication_lag'] > 30:
alerts.append(f"Replication lag: {metrics['replication_lag']}s")
return metrics, alerts
Security Checklist
- Use strong authentication for all database connections
- Implement TLS encryption for all database connections
- Apply principle of least privilege for application database users
- Rotate credentials regularly and use secret management
- Audit database access logs for security review
- Use network segmentation (databases not directly internet-accessible)
- Encrypt data at rest (filesystem or application-level encryption)
- Implement query whitelisting or restrictions for application users
- Monitor for unauthorized access attempts
- Test database access controls with penetration testing
- Secure backup data with encryption
- Implement read-only users separate from read-write users
Category
Related Posts
Database Capacity Planning: A Practical Guide
Plan database capacity from measured growth, retention, workload, and provisioning time. Includes a storage forecast and PostgreSQL-specific memory guidance.
Connection Pooling: HikariCP, pgBouncer, and ProxySQL
Learn connection pool sizing, HikariCP, pgBouncer, and ProxySQL, timeout settings, idle management, and when pooling helps or hurts performance.
Read/Write Splitting
Master-slave replication for read scaling. Routing strategies, consistency lag considerations, and when this pattern helps vs hurts your architecture.