Picture this. You launch a small online shop. For six months, everything works. Pages load in under a second. Then a big festival sale starts, and a popular influencer shares your link.
Traffic goes up ten times in one hour. The home page now takes eight seconds to load. Checkout fails. Your server CPU looks fine, so what is wrong?
In most cases, the answer is the database. The app servers are easy to copy. The database holds the data, and data is hard to copy safely. This guide explains database scaling best practices in plain words. Each practice has a simple example. We start with the cheap and easy steps, and we finish with the big, complex ones. That order matters. Many teams jump to sharding on day one and regret it.
Who is this for? Backend developers, students and founders who run PostgreSQL, MySQL or a similar database, and who want it to stay fast as users grow.
What is database scaling?
Database scaling means your database can handle more users, more data and more queries without getting slow. There are two basic ways to do it: make one server bigger, or use more servers.
Vertical scaling (scale up)
You give the same database server more power: more CPU, more RAM, faster disks.
Simple example: Your shop database runs on a server with 4 CPU cores and 16 GB RAM. Queries get slow. You move it to 16 cores and 64 GB RAM. Now more of your data fits in memory, and queries are fast again. You changed zero lines of code.
Horizontal scaling (scale out)
You spread the work across many database servers. Each server does a part of the job.
Simple example: You keep one main server for orders and payments. You add two copies of it that only answer “show me products” queries. Reads go to the copies, and writes go to the main server.
| Point | Vertical scaling (scale up) | Horizontal scaling (scale out) |
|---|---|---|
| What you do | Buy a bigger server | Add more servers |
| Code changes | Usually none | Some to many |
| Cost curve | Cheap at first, very expensive at the top | Grows step by step |
| Limit | The biggest machine you can buy | Much higher |
| Single point of failure | Yes | Less, if set up well |
| Best time to use | First, and for as long as it works | When one server is not enough |
The honest rule: scale up first. A bigger server is boring, but boring is good. Move to scale out only when you hit a real limit, not a fear of one.
8 database scaling best practices
The practices below go roughly from easy to hard. Each step often removes the need for the next one. The checklist near the end shows the exact order to follow.
1. Measure before you change anything
You cannot fix what you cannot see. Before you add servers, find the slow queries.
Turn on the slow query log. In PostgreSQL, the pg_stat_statements extension shows which queries use the most total time. In MySQL, use the slow query log with a limit such as 500 ms.
Simple example: You think the product search is slow. The data shows something else. One small query, “count unread notifications”, runs 40,000 times per minute. It uses more database time than all other queries together. You fix that one query, and the database load drops by half.
Watch these numbers every week:
- Query time at p95 (the slowest 5% of requests)
- CPU and memory use
- Number of open connections
- Disk read and write speed
- Replication lag, if you use replicas
2. Fix your indexes and queries
This is the cheapest scaling win. A good index can turn a 3-second query into a 3-millisecond query.
An index works like the index at the back of a book. Without it, the database reads every row to find a match. That is called a full table scan.
Simple example: Your orders table has 5 million rows. This query is slow
Simple example: Your orders table has 5 million rows. This query is slow:
SELECT * FROM orders WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 10;
Check how the database runs it:
EXPLAIN ANALYZE
SELECT * FROM orders WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 10;
If you see “Seq Scan” (PostgreSQL) or “type: ALL” (MySQL), the database reads the full table. Add one index that matches the filter and the sort:
CREATE INDEX idx_orders_customer_created
ON orders (customer_id, created_at DESC);
Now the database jumps straight to customer 42 and reads only 10 rows.
Other quick query fixes:
- Select only the columns you need.
SELECT *sends extra data over the network. - Stop the N+1 problem. Do not run one query per item in a loop. Load 50 products in one query, not 50 queries.
- Paginate with a key, not a big OFFSET.
OFFSET 100000still reads 100,000 rows and throws them away. - Do not add indexes everywhere. Each index makes inserts and updates a little slower.
3. Use connection pooling
Each database connection uses memory on the server. In PostgreSQL, each connection is a separate process. A thousand idle connections can slow the database even when nobody runs a query.
A connection pooler sits between your app and the database. Many app requests share a small number of real connections.
Simple example: You run 20 app servers. Each one opens 50 connections. That is 1,000 connections. With a pooler such as PgBouncer (PostgreSQL) or ProxySQL (MySQL), those 1,000 app connections share about 50 real database connections. The database now spends its time on queries, not on connection management.
A basic PgBouncer setting looks like this:
[pgbouncer]
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 50
Tip: Serverless apps (for example, AWS Lambda functions) open many short connections. For these, a pooler is almost a must.
4. Add a cache for hot data
The fastest query is the one you never send. A cache keeps the answer to a common question in fast memory, often in Redis or Memcached.
The most common pattern is cache-aside:
- The app checks the cache.
- If the data is there (a cache hit), the app uses it.
- If not (a cache miss), the app reads the database and saves the result in the cache with an expiry time.
Simple example in Python:
import json
import redis
cache = redis.Redis()
def get_product(product_id, db):
key = f"product:{product_id}"
cached = cache.get(key)
if cached:
return json.loads(cached) # cache hit
product = db.fetch_product(product_id) # cache miss
cache.setex(key, 300, json.dumps(product)) # keep for 5 minutes
return product
Your home page shows the same 20 best-selling products to every visitor. Without a cache, 10,000 visitors cause 10,000 database queries. With a 5-minute cache, the database answers once every 5 minutes.
Cache good candidates: product pages, settings, user profiles and leaderboards. Do not cache: bank balances, stock counts during checkout, or anything that must be exact right now.
The hard part of caching is not adding it. It is deciding when old data is “too old”. Always set an expiry time, and delete the key when the data changes.
5. Send reads to read replicas
Most apps read far more than they write. A typical shop may run 90 reads for every 10 writes. Read replicas use this fact.
A read replica is a copy of your main (primary) database. The primary takes all writes. It sends each change to the replicas. The replicas answer read queries.
Simple example: Your primary database handles orders, signups and payments. Two replicas handle product listing, search and the admin reports. The heavy monthly sales report no longer slows down checkout.
Watch out for replication lag. A replica is often a few milliseconds behind the primary. Sometimes it is seconds behind. This causes a classic bug:
- A user updates their profile name.
- The page reloads and reads from a replica.
- The replica does not have the change yet, so the user sees the old name.
The common fix is read-your-own-writes: for a few seconds after a user changes data, send that user’s reads to the primary.
6. Partition large tables
Partitioning splits one big table into smaller pieces inside the same database. Your app still sees one table. The database works with smaller parts under the hood.
The most common type is range partitioning by date.
Simple example: Your events table gets 2 million rows every month. After two years, it has 48 million rows. Most queries only ask about the last 30 days. You partition it by month:
CREATE TABLE events (
id BIGINT,
user_id BIGINT,
event_type TEXT,
created_at TIMESTAMP NOT NULL
) PARTITION BY RANGE (created_at);
CREATE TABLE events_2026_11 PARTITION OF events
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
CREATE TABLE events_2026_12 PARTITION OF events
FOR VALUES FROM ('2026-12-01') TO ('2027-01-01');
Now a query for “this month” reads only one small partition. This is called partition pruning. To delete old data, you drop a whole partition in one fast step. You do not need a slow DELETE of millions of rows.
Types of partitioning
There are two main directions to split data: by rows or by columns.
Horizontal partitioning (split rows). Each part has the same columns but different rows. The events example above is horizontal partitioning. Sharding is also horizontal partitioning, but the parts live on different servers.
Vertical partitioning (split columns). You move some columns into a separate table. Each part has the same rows but different columns.
Simple example: Your users table has id, name, email, password_hash, a long bio and a large preferences JSON field. The login query only needs four small columns, but each row is big. You move bio and preferences into a user_profiles table with the same id. Login now reads small rows, and more of them fit in memory.
Horizontal partitioning has four common methods. The SQL below uses PostgreSQL syntax. MySQL supports the same ideas with slightly different syntax.
1. Range partitioning. Rows go to a part based on a range of values, such as dates or ID numbers. This is the monthly events example above. It is best for time-based data such as logs, orders and events.
2. List partitioning. Rows go to a part based on a fixed list of values, such as a region or a status.
CREATE TABLE orders (
id BIGINT,
region TEXT NOT NULL,
amount NUMERIC
) PARTITION BY LIST (region);
CREATE TABLE orders_india PARTITION OF orders FOR VALUES IN ('IN');
CREATE TABLE orders_europe PARTITION OF orders FOR VALUES IN ('DE', 'FR', 'NL');
CREATE TABLE orders_us PARTITION OF orders FOR VALUES IN ('US');
A query for Indian orders now reads only orders_india. This also helps when a law says some data must stay in one country.
3. Hash partitioning. The database runs the key through a hash function and uses the result to pick a part. You do not choose where a row goes. The hash spreads rows evenly.
CREATE TABLE sessions (
user_id BIGINT NOT NULL,
token TEXT
) PARTITION BY HASH (user_id);
CREATE TABLE sessions_p0 PARTITION OF sessions FOR VALUES WITH (MODULUS 4, REMAINDER 0);
CREATE TABLE sessions_p1 PARTITION OF sessions FOR VALUES WITH (MODULUS 4, REMAINDER 1);
CREATE TABLE sessions_p2 PARTITION OF sessions FOR VALUES WITH (MODULUS 4, REMAINDER 2);
CREATE TABLE sessions_p3 PARTITION OF sessions FOR VALUES WITH (MODULUS 4, REMAINDER 3);
Use hash when no natural range or list exists and you want an even spread. The downside: a query for a range of user IDs must check every part.
4. Composite partitioning (sub-partitioning). You combine two methods. For example, you split events by month (range), then split each month by user_id (hash). This helps very large tables where one month is still too big.
| Type | Splits by | Simple example | Best for |
|---|---|---|---|
| Range | A range of values | Orders per month | Logs, events, time-series data |
| List | A fixed list of values | Orders per region | Regions, categories, data rules by country |
| Hash | A hash of a key | Sessions spread by user_id |
Even spread with no natural grouping |
| Composite | Two methods together | Month, then user_id |
Very large tables |
| Vertical | Columns | Login columns vs profile columns | Wide tables with rarely used big columns |

7. Shard only when you must
Sharding splits your data across different database servers. Each server (a shard) holds a part of the rows. This is the most powerful scaling method. It is also the most painful.
Partitioning vs sharding in one line: partitioning splits a table inside one server; sharding splits data across many servers.
Simple example: A school app has 2,000 schools. You put schools 1 to 1,000 on shard A and schools 1,001 to 2,000 on shard B. The app looks at school_id and sends each query to the right shard. Here, school_id is the shard key.
The shard key is the most important choice. A good shard key:
- Spreads data and traffic evenly
- Keeps related data together, so most queries hit one shard
- Does not change over time
A bad shard key creates a hot shard. For example, if you shard by country and 70% of your users live in India, one shard does 70% of the work.
What gets harder after sharding:
- Joins across shards
- Transactions across shards
- Reports that need all data
- Moving data when you add new shards (resharding)
You do not always need to build sharding yourself. Tools such as Vitess (for MySQL) and Citus (for PostgreSQL) add sharding on top of a database you know. Distributed SQL databases such as CockroachDB, YugabyteDB and Google Cloud Spanner shard data for you automatically.
8. Move slow work to background queues
Not every write must happen right now. Some work can wait a few seconds.
A message queue (such as RabbitMQ, Amazon SQS or Apache Kafka) holds tasks. Background workers pick them up and write to the database at a steady speed.
Simple example: A customer places an order. The app must save the order right away. But the confirmation email, the invoice PDF, the loyalty points update and the analytics event can all wait. You save the order, put the other four tasks in a queue, and reply to the customer at once.
During a flash sale, the queue absorbs the spike. The database sees a smooth flow of writes, not a sudden flood. This also makes your checkout page faster, because the user does not wait for slow side tasks.
Common database scaling mistakes
These mistakes show up again and again in real projects:
- Sharding too early. A team with 50,000 users shards “to be ready”. They now spend every sprint on cross-shard bugs. One well-tuned PostgreSQL or MySQL server can handle far more than most startups need.
- Guessing instead of measuring. The team adds Redis everywhere, but the real problem was one missing index.
- Caching without an expiry. Users see a price from last week. Support tickets pile up.
- Ignoring replication lag. Users save a change, reload, and think the app lost their data.
- Running reports on the primary. One big analytics query at 10 a.m. slows down every checkout. Send reports to a replica or a separate analytics store.
- No backups for the new setup. More servers means more things that can break. Test your restore process, not just your backup job.
The database scaling ladder: a quick checklist
Climb one step at a time. Move up only when the current step no longer solves your problem.
| Step | Action | Effort | Move to the next step when |
|---|---|---|---|
| 1 | Measure: slow query log, metrics | Low | You know which queries hurt |
| 2 | Add indexes, fix queries | Low | Queries are tuned, but load is still high |
| 3 | Connection pooling | Low | Connections are fine, but reads are heavy |
| 4 | Cache hot data | Medium | Cache hit rate is good, but the database is still busy |
| 5 | Scale up the server | Low | You are near the largest practical machine |
| 6 | Read replicas | Medium | Writes, not reads, are the bottleneck |
| 7 | Partition big tables | Medium | One server cannot hold the data or the write load |
| 8 | Background queues | Medium | Write spikes still overload the primary |
| 9 | Sharding or distributed SQL | High | You have reached a scale few apps ever reach |
FAQ: database scaling
What is the best way to scale a database?
Start with the cheap steps. Measure your slow queries, add the right indexes, use connection pooling and cache hot data. Then scale up the server. Add read replicas, partitioning and sharding only when the earlier steps are not enough.
What is the difference between vertical and horizontal scaling?
Vertical scaling makes one database server more powerful with more CPU, RAM or faster disks. Horizontal scaling adds more servers and spreads the work across them. Vertical is simpler. Horizontal goes further but adds complexity.
When should I shard my database?
Shard when one primary server cannot handle your write load or your data size, even after tuning, caching, replicas and partitioning. For most small and medium apps, that day never comes.
What is the difference between partitioning and sharding?
Partitioning splits a large table into smaller parts inside one database server. Sharding splits data across several database servers. Partitioning is much easier to manage.
Do read replicas help with write-heavy apps?
No. Replicas only take read traffic. Every write still goes to the primary. For heavy writes, look at batching, background queues, partitioning or sharding.
Is Redis a replacement for my database?
Usually not. Use Redis as a fast cache in front of your main database. Keep your main database as the source of truth.
Conclusion
Database scaling is not one big switch. It is a ladder. Most performance problems disappear on the first few steps: measure, index, pool and cache. Those steps cost little and carry almost no risk.
Keep the big tools, such as replicas, partitions and shards, for when the numbers ask for them. Your future self will thank you for the simpler system.
Your next step: open your slow query log today. Find your top five slowest queries and run EXPLAIN ANALYZE on each. You may find your next big speed-up in less than an hour.