Database Sharding Explained: Keys, Hash Rings, MySQL & Postgres
One chapter on sharding: the problem before it, what it solves and costs, shard keys, hash rings, hot keys, rebalancing, routing, MySQL and PostgreSQL…
In this chapter
Sharding: one table split across many database servers
Database sharding: common questions
What is the difference between sharding and partitioning?
Partitioning splits a table into pieces on one server. Sharding puts those pieces on different servers, so storage and writes scale out.
When should I shard a database?
Last: after indexes, a bigger machine, read replicas, caching and partitioning stop being enough, usually because data size or write throughput outgrow one primary.
How do you shard MySQL or PostgreSQL?
They do not shard by themselves. Shard in the application, use a sharding layer (Vitess for MySQL, Citus for PostgreSQL), or use a compatible distributed database such as TiDB, CockroachDB or YugabyteDB.
What makes a good shard key?
Many distinct values, an even spread of data and traffic, and presence in the most common queries so they hit one shard. Avoid timestamps, booleans and low-cardinality columns.
What are range, hash and directory-based sharding?
Range gives each shard a sorted span of keys, hash spreads keys with a hash function (the usual default), and a directory looks each key up in a mapping table, which is flexible but adds a lookup on every request.
More on Scaling out
Keep learning
Overview
When to shard When the numbers say shard What sharding is Same table, many servers What it solves What it costs Transactions across shards Each shard is also copied
{NUMBER.get(id)}. {title}
chapters · scaling out Sharding: one table split across many database servers What sharding fixes and what it costs, how to choose and move shards, and how MySQL, PostgreSQL and other databases do it. Why one server stops being enough is in before sharding. To see it working first, click through the sharded URL shortener. On this page Part 1 · When to shard
When the numbers say shard
The number one mistake, in interviews and in real life, is sharding before it is needed. Work out how much data and how many writes you expect, and compare them with what one server can take (numbers to know). Part 2 · What sharding is
Same table, many servers
An example. A URL shortener stores one row per short link in a table called links: the short code and the long URL it points to. Say the table has 1 million rows, and that is more than we want one server to handle. So we run 5 database servers. Each one has the same links table with the same columns, and each holds a different fifth of the rows, about 200,000: That split is sharding: one table’s rows spread across several servers. Each server only searches its own 200 k rows, so its index is 5× smaller and fits in memory again, and the five servers share the reads and writes between them. Each of these slices is a shard. Something has to decide which server each row goes to. That is the job of one column, the shard key: here, the code column. The same code always maps to the same server, so the app can always find the row again. GET /5FTOJ hash('5FTOJ') → db-3 the same code always gives db-3, so the write and every later read meet on one server The router turns the shard key into a server. Only that server runs the query.
What it solves
Storage scales 10 shards hold 10× the data. Add shards as data grows. Writes scale Each shard has its own primary, so writes spread over many machines. Smaller indexes Each server indexes only its slice, so the hot part fits in memory again. Smaller blast radius A broken shard affects its slice of users, not everyone.
What it costs
Queries without the key Search by anything else and you must ask every shard. No transactions across shards Two shards are two databases with two separate commits. No joins across shards Join in the app, or keep related rows on one shard. Hot shards A bad key or a celebrity puts most of the load on one server. Adding servers means moving data while the app keeps running. Operations × N Every schema change, backup and upgrade runs on every shard.
Transactions across shards
The biggest cost in that list, up close. On one database, “move ₹500 from Asha to Ravi” is one transaction. If Asha is on shard 1 and Ravi on shard 2, they are two databases: Shard 1 (Asha) Shard 2 (Ravi) Asha −500 app crashes before the second write never runs Ravi +0 Without coordination, ₹500 disappears. Design it away Choose the shard key (next chapter) so rows that change together live on the same shard. Needing cross-shard transactions all the time means the key is wrong. Eventual consistency Counters and copies may lag a few seconds and converge. Two-phase commit Correct but slow and fragile. Use it when the database provides it (Spanner, CockroachDB). The details are in transactions across machines.
Each shard is also copied
In the example above, each shard lives on exactly one server: the links starting 5FTOJ, … are only on db-3. If db-3’s disk dies, a fifth of all short links stop working, and if the disk is lost, they are gone for good. Splitting the data did nothing to protect it. So every shard is also copied to a second (often a third) server. This is replication, and it works the same way for a shard as for a whole database: one copy is the leader, which takes the writes, and the others are followers, which replay the leader’s changes and can take over. From here on we say node for one database server (one machine), because a node now holds more than one shard. A smaller example: the links table split into 3 shards (shard 1, 2 and 3, each a third of the links), on 3 nodes (A, B and C). Each shard needs one leader and one copy, and the copy must be on a different node from its leader, or one dead machine would take both. The simplest placement rotates: each shard’s leader sits on one node and its copy on the next one along. Where each shard lives Shard (a third of the links) Leader on Copy on Shard 1 Node A Node B Shard 2 Node C Shard 3 Node A (wraps around) Turn the same table around and look at each machine. That is why node A holds shard 1 and shard 3: it leads shard 1 and keeps the backup of shard 3. Node A leads shard 1 and keeps a copy of shard 3. Node B leads shard 2 and keeps a copy of shard 1. Node C leads shard 3 and keeps a copy of shard 2. Writes for shard 2 go to node B, its leader. B sends each change to node C, which keeps a copy. Every node does both jobs: leader for one shard, copy for another, so all three machines share the write work instead of one sitting idle as a pure spare. So sharding answers “where does this row live?” and replication answers “what if that machine dies?”. Real systems always use both.
Next
You know what sharding is and what it costs. Next: how to decide which shard each row goes to, how to add servers, how a query finds its shard, and what happens to queries that don’t carry the key, in placing data on shards. After that, how real databases do it and the interview answer: sharding in real databases, and in the interview.
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.