Nextgen Blog
HomeLearnAIQuantumRoboticsSecuritySpaceAbout
Nextgen Blog

By Anubhav — full stack engineer, IIT Mandi CSE. Deep dives into AI, software engineering, and the technologies shaping the next generation of tech.

Navigate

  • Home
  • Learn
  • Blog
  • Archive
  • About

Topics

  • Artificial Intelligence
  • Quantum Computing
  • Robotics
  • Cybersecurity
  • Space Tech

Connect

Built with ❤️ & By - Anubhav

© 2026 Nextgen Blog by Anubhav. All rights reserved.

Privacy PolicyTerms of Service
Phase 03 · Partitioning, Replication & CachingChapter 16 of 33
15.
Phase 03Read time ~25 minDifficulty advanced

Database Partitioning & Sharding

In this chapter
  • 01Introduction
  • 02Replication vs Partitioning vs Sharding
  • 03Replication
  • 04Partitioning
  • 05Sharding
  • 06Why Do We Need Sharding?
  • 07Vertical Partitioning
  • 08Horizontal Partitioning
  • 09Horizontal vs Vertical Partitioning
  • 10What Is a Shard Key?
  • 11Characteristics of a Good Shard Key
  • 12Even distribution
  • 13Even write distribution
  • 14Query locality
  • 15High cardinality
  • 16Stability
  • 17Bad Shard Key Example
  • 18High-Cardinality Shard Keys
  • 19Query Patterns Matter
  • 20Scatter-Gather Queries
  • 21Why Cross-Shard Queries Are Expensive
  • 22Hash-Based Sharding
  • 23Advantages of Hash Sharding
  • 24Disadvantages of Hash Sharding
  • 25Range-Based Sharding
  • 26Advantages of Range Sharding
  • 27Disadvantages of Range Sharding
  • 28Hot Partition
  • 29Directory-Based Sharding
  • 30Advantages of Directory-Based Sharding
  • 31Disadvantages of Directory-Based Sharding
  • 32Consistent Hashing
  • 33Consistent Hash Ring
  • 34Virtual Nodes
  • 35Rebalancing
  • 36Why Resharding Is Difficult
  • 37Online Resharding
  • 38Dual Writes
  • 39Change Data Capture During Migration
  • 40Shard Metadata
  • 41Shard Router
  • 42Sharding by Tenant
  • 43The Mega-Tenant Problem
  • 44Composite Shard Keys
  • 45Shard Key and Query Locality
  • 46Cross-Shard Transactions
  • 47Avoiding Cross-Shard Transactions
  • 48Co-Location
  • 49Cross-Shard Joins
  • 50Sharding and Indexes
  • 51Global Uniqueness
  • 52ID Generation in Sharded Systems
  • 53Hot Keys
  • 54Sharding + Caching
  • 55Sharding + Replication
  • 56Failure Handling
  • 57Capacity Planning for Shards
  • 58Shard Count Is an Architecture Decision
  • 59Shard Count and Connection Explosion
  • 60Choosing a Sharding Strategy
  • 61Hash Sharding
  • 62Range Sharding
  • 63Directory Sharding
  • 64Composite Sharding
  • 65Practical Design: Sharded URL Shortener
  • 66URL Shortener Architecture
  • 67Practical Design: Social Media
  • 68Practical Design: Time-Series Data
  • 69Common Mistakes
  • 70Mistake 1: Sharding too early
  • 71Mistake 2: Choosing a shard key only by cardinality
  • 72Mistake 3: Ignoring hot partitions
  • 73Mistake 4: Ignoring cross-shard queries
  • 74Mistake 5: Ignoring resharding
  • 75Mistake 6: Assuming sharding automatically solves scaling
  • 76Mistake 7: Forgetting replication
  • 77Mistake 8: Ignoring global uniqueness
  • 78Mistake 9: Ignoring transactions
  • 79Mistake 10: Creating too many connections
  • 80Interview Questions
  • 81Beginner
  • 82Intermediate
  • 83Advanced
  • 84Interview Scenario
  • 85Question
  • 86Production Sharding Checklist
  • 87Data
  • 88Querying
  • 89Operations
  • 90Availability
  • 91Performance
  • 92Master Mental Model
  • 93Replication + Sharding
  • 94Chapter Summary
  • 95Final Interview Checklist
  • 96What's Next?
  • 97Chapter 15 — Caching Fundamentals
In this chapter (97 sections)
01Introduction02Replication vs Partitioning vs Sharding03Replication04Partitioning05Sharding06Why Do We Need Sharding?07Vertical Partitioning08Horizontal Partitioning09Horizontal vs Vertical Partitioning10What Is a Shard Key?11Characteristics of a Good Shard Key12Even distribution13Even write distribution14Query locality15High cardinality16Stability17Bad Shard Key Example18High-Cardinality Shard Keys19Query Patterns Matter20Scatter-Gather Queries21Why Cross-Shard Queries Are Expensive22Hash-Based Sharding23Advantages of Hash Sharding24Disadvantages of Hash Sharding25Range-Based Sharding26Advantages of Range Sharding27Disadvantages of Range Sharding28Hot Partition29Directory-Based Sharding30Advantages of Directory-Based Sharding31Disadvantages of Directory-Based Sharding32Consistent Hashing33Consistent Hash Ring34Virtual Nodes35Rebalancing36Why Resharding Is Difficult37Online Resharding38Dual Writes39Change Data Capture During Migration40Shard Metadata41Shard Router42Sharding by Tenant43The Mega-Tenant Problem44Composite Shard Keys45Shard Key and Query Locality46Cross-Shard Transactions47Avoiding Cross-Shard Transactions48Co-Location49Cross-Shard Joins50Sharding and Indexes51Global Uniqueness52ID Generation in Sharded Systems53Hot Keys54Sharding + Caching55Sharding + Replication56Failure Handling57Capacity Planning for Shards58Shard Count Is an Architecture Decision59Shard Count and Connection Explosion60Choosing a Sharding Strategy61Hash Sharding62Range Sharding63Directory Sharding64Composite Sharding65Practical Design: Sharded URL Shortener66URL Shortener Architecture67Practical Design: Social Media68Practical Design: Time-Series Data69Common Mistakes70Mistake 1: Sharding too early71Mistake 2: Choosing a shard key only by cardinality72Mistake 3: Ignoring hot partitions73Mistake 4: Ignoring cross-shard queries74Mistake 5: Ignoring resharding75Mistake 6: Assuming sharding automatically solves scaling76Mistake 7: Forgetting replication77Mistake 8: Ignoring global uniqueness78Mistake 9: Ignoring transactions79Mistake 10: Creating too many connections80Interview Questions81Beginner82Intermediate83Advanced84Interview Scenario85Question86Production Sharding Checklist87Data88Querying89Operations90Availability91Performance92Master Mental Model93Replication + Sharding94Chapter Summary95Final Interview Checklist96What's Next?97Chapter 15 — Caching Fundamentals

1. Introduction#

In the previous chapter, we learned replication.

Replication means:

Keep multiple copies of the same data.

Sharding is different.

Sharding means:

Split data across multiple database nodes so that each node stores only part of the total dataset.

For example, suppose we have 1 billion users.

A single database might become difficult to scale:

                 1 Billion Users
                       |
                       v
                 +-----------+
                 | Database  |
                 +-----------+

With sharding:

                    1 Billion Users
                          |
             +------------+------------+
             |            |            |
             v            v            v
          Shard 1      Shard 2      Shard 3
          Users        Users        Users
        1-333M       334-666M      667-1B

Each shard stores only a portion of the data.

This can allow the system to scale beyond the limits of one database server.


2. Replication vs Partitioning vs Sharding#

These concepts are often confused.

Replication#

Copies the same data.

Primary
   |
   +---- Replica 1
   |
   +---- Replica 2

All replicas contain approximately the same dataset.


Partitioning#

Splits data into partitions.

Database
   |
   +---- Partition A
   +---- Partition B
   +---- Partition C

Partitions may exist inside one database system.


Sharding#

Distributes partitions across different database nodes.

             Database Cluster
                   |
        +----------+----------+
        |          |          |
        v          v          v
      Shard 1    Shard 2    Shard 3

A useful mental model:

Replication = Copy
Partitioning = Split
Sharding = Split across nodes

3. Why Do We Need Sharding?#

Imagine an application with:

Users = 500 million
Orders = 10 billion
Writes = 200,000/sec
Reads = 2 million/sec

A single database may encounter limits involving:

  • CPU
  • memory
  • storage
  • disk I/O
  • network bandwidth
  • connection count
  • transaction throughput
  • index size
  • write throughput

Adding read replicas can help with reads.

But consider:

              200k writes/sec
                     |
                     v
                  Primary

The primary remains responsible for writes.

Replication does not automatically distribute write ownership.

Sharding can distribute the dataset and write workload.

                Write Traffic
                     |
             +-------+-------+
             |       |       |
             v       v       v
          Shard 1 Shard 2 Shard 3

4. Vertical Partitioning#

Before discussing sharding, understand vertical partitioning.

Vertical partitioning means splitting columns.

Suppose we have:

Users
------------------------------------
id
name
email
password_hash
profile
preferences
large_bio
avatar_metadata

We might split it into:

UserCore
----------------
id
name
email
password_hash

and:

UserProfile
----------------
user_id
profile
preferences
large_bio
avatar_metadata

This can reduce row size and separate workloads.


5. Horizontal Partitioning#

Horizontal partitioning splits rows.

Suppose:

Users
 
1
2
3
4
5
6
7
8
9
10

We can divide them:

Partition A
1
2
3
4
5
 
Partition B
6
7
8
9
10

The columns remain the same.

Only the rows are divided.

This is the foundation of many sharding strategies.


6. Horizontal vs Vertical Partitioning#

Type Splits Example
Vertical Columns Profile data separated from authentication data
Horizontal Rows Users 1–1M in one partition, others elsewhere

Horizontal partitioning is particularly important for large-scale databases.


7. What Is a Shard Key?#

The shard key determines which shard stores a record.

Suppose:

user_id = 12345

The system calculates:

shard = hash(user_id) % number_of_shards

Example:

hash(12345) % 4 = 2

Therefore:

user 12345 -> Shard 2

The shard key is one of the most important design decisions in a sharded system.


8. Characteristics of a Good Shard Key#

A good shard key should ideally provide:

1. Even distribution#

Avoid sending most data to one shard.

2. Even write distribution#

Writes should be reasonably balanced.

3. Query locality#

Common queries should be able to identify the relevant shard.

4. High cardinality#

There should be many possible values.

5. Stability#

Changing the shard key should not be required frequently.


9. Bad Shard Key Example#

Suppose we shard users by:

country

Possible distribution:

India       600M
USA         200M
Europe      150M
Others       50M

Now:

Shard India = 600M
Shard USA   = 200M
Shard Europe= 150M
Shard Others= 50M

The distribution is highly uneven.

India becomes a hot shard.

This is called data skew.


10. High-Cardinality Shard Keys#

Consider:

country

Low-to-moderate cardinality.

Possible values:

India
USA
UK
Germany
France
...

Now consider:

user_id

Potentially hundreds of millions of values.

That gives much higher cardinality.

High cardinality often makes a better shard key, although the correct choice always depends on query patterns and workload.


11. Query Patterns Matter#

A shard key should not be selected only based on even distribution.

Suppose most queries are:

Get all orders for user 123

Then:

user_id

can be a strong shard key.

The system can route the query directly:

user_id = 123
       |
       v
Shard calculation
       |
       v
Shard 7

Instead of querying every shard.


12. Scatter-Gather Queries#

Suppose the shard key is user_id.

Now someone asks:

SELECT COUNT(*)
FROM orders
WHERE status = 'PAID';

There may be no user ID.

The router may need to query every shard:

              Query
                |
       +--------+--------+
       |        |        |
       v        v        v
    Shard 1  Shard 2  Shard 3
       |        |        |
       v        v        v
     Count    Count    Count
       \        |       /
        \       |      /
         +------+-----+
                |
             Combine
                |
                v
             Result

This is called a scatter-gather query.

It can be expensive.


13. Why Cross-Shard Queries Are Expensive#

Suppose there are 100 shards.

A query that needs all shards becomes:

1 request
   |
   +----> 100 shard requests

Then the system must:

  1. send requests
  2. wait for responses
  3. handle slow shards
  4. combine results
  5. handle failures

Latency may be dominated by the slowest shard.

Therefore:

Good shard-key design attempts to keep common queries shard-local.


14. Hash-Based Sharding#

A common approach is hashing the shard key.

Example:

shard = hash(user_id) % N

If:

N = 4

then:

user 101 -> hash -> 1
user 102 -> hash -> 3
user 103 -> hash -> 0
user 104 -> hash -> 2

The goal is to distribute records evenly.


15. Advantages of Hash Sharding#

Hash sharding can provide:

  • relatively even distribution
  • good write distribution
  • reduced hotspot risk for sequential identifiers
  • straightforward routing

Example:

          User IDs
             |
           Hash
             |
       +-----+-----+
       |     |     |
       v     v     v
      S1    S2    S3

16. Disadvantages of Hash Sharding#

Hash sharding can make range queries difficult.

Suppose we want:

Users 1,000,000 through 2,000,000

With hashing, those users may be spread across many shards.

Therefore:

Range Query
     |
     +----> S1
     +----> S2
     +----> S3
     +----> S4

This can become a scatter-gather query.


17. Range-Based Sharding#

Instead of hashing, divide the key space into ranges.

Example:

Shard 1:
user_id 1 - 1,000,000
 
Shard 2:
user_id 1,000,001 - 2,000,000
 
Shard 3:
user_id 2,000,001 - 3,000,000

Architecture:

              User ID
                 |
          +------+------+
          |             |
       Range          Range
          |             |
          v             v
        Shard 1       Shard 2

18. Advantages of Range Sharding#

Range sharding is useful when queries frequently use ranges.

Example:

WHERE created_at BETWEEN
'2026-01-01' AND '2026-01-31'

A time-based range can make it easier to locate the relevant partition.


19. Disadvantages of Range Sharding#

Range sharding can create hotspots.

Suppose new records always have increasing IDs:

1
2
3
4
...
999999
1000000
1000001

New writes may all target the latest range.

Old shards:
mostly idle
 
Latest shard:
########################
heavy writes

This is a hot partition.


20. Hot Partition#

A hot partition is a partition receiving disproportionately high traffic.

Example:

Shard 1   10k writes/sec
Shard 2   11k writes/sec
Shard 3   9k writes/sec
Shard 4   500k writes/sec  <-- HOT

The entire cluster can be healthy while one shard becomes the bottleneck.

This is why average cluster CPU can be misleading.


21. Directory-Based Sharding#

Another strategy is to maintain a mapping:

user_id -> shard

Example:

User 101 -> Shard A
User 102 -> Shard C
User 103 -> Shard B

A routing service or metadata store maintains this information.

Architecture:

Application
    |
    v
Shard Directory
    |
    +----> Shard A
    +----> Shard B
    +----> Shard C

22. Advantages of Directory-Based Sharding#

It provides flexibility.

A user can move:

User 101
Shard A
   |
   | migration
   v
Shard C

The directory is updated:

101 -> C

The application does not need to know the physical placement.


23. Disadvantages of Directory-Based Sharding#

The directory becomes important infrastructure.

Potential issues:

  • directory availability
  • stale mappings
  • lookup latency
  • consistency
  • operational complexity

The directory itself may need replication and high availability.


24. Consistent Hashing#

Normal modulo hashing has a major problem.

Suppose:

shard = hash(key) % 4

Now add a fifth shard:

shard = hash(key) % 5

Many keys map to different shards.

This can cause massive data movement.

Consistent hashing reduces the amount of data that must move when nodes are added or removed.


25. Consistent Hash Ring#

Imagine a circular hash space:

             0
         .-------.
      .             .
    3                 1
      .             .
         '-------'
             2

Nodes are placed on the ring.

A key is hashed onto the ring and assigned to the next node according to the chosen algorithm.

Conceptually:

Key
 |
 v
Hash
 |
 v
Ring
 |
 v
Shard

26. Virtual Nodes#

A shard can be represented by multiple positions on a consistent hash ring.

Shard A -> A1, A2, A3
Shard B -> B1, B2, B3
Shard C -> C1, C2, C3

This helps improve distribution.

Virtual nodes can also make rebalancing more manageable.


27. Rebalancing#

As the system grows, you may need more shards.

Initially:

S1
S2
S3

Later:

S1
S2
S3
S4
S5
S6

Data must be redistributed.

This is called rebalancing or resharding.


28. Why Resharding Is Difficult#

Moving data while the application is running introduces challenges:

  • data movement
  • network bandwidth
  • disk I/O
  • consistency
  • dual writes
  • synchronization
  • routing changes
  • rollback
  • failures during migration

For a billion-row dataset, moving everything at once is not practical.


29. Online Resharding#

A production system may migrate data gradually.

Conceptually:

Old Shard
   |
   | copy data
   v
New Shard

During migration:

Application
   |
   v
Routing Layer
   |
   +---- old location
   |
   +---- new location

The system keeps the old and new locations synchronized until the migration is safe.

Then routing switches to the new shard.


30. Dual Writes#

During migration, an application may temporarily write to both locations:

Application
     |
     +----> Old Shard
     |
     +----> New Shard

This is called a dual-write strategy.

But dual writes introduce difficult failure scenarios.

For example:

Write Old = SUCCESS
Write New = FAILURE

Now the two copies differ.

Therefore dual writes require careful reconciliation and validation.


31. Change Data Capture During Migration#

Another strategy is to:

  1. copy existing data
  2. capture changes occurring during the copy
  3. replay those changes on the destination
  4. validate
  5. switch routing

Conceptually:

Old Shard
   |
   +---- Initial Copy ----> New Shard
   |
   +---- Change Stream ---> New Shard

This allows migration while the source remains active.


32. Shard Metadata#

Large systems need metadata describing shard placement.

Example:

Shard Map
 
Range / Key        Shard
-------------------------
0 - 999999         S1
1000000 - 1999999  S2
2000000 - 2999999  S3

The routing layer uses this map to find the correct shard.

The metadata itself becomes a critical system component.


33. Shard Router#

A shard router determines where a request should go.

                 Application
                      |
                      v
                 Shard Router
                      |
           +----------+----------+
           |          |          |
           v          v          v
          S1         S2         S3

Example:

const shard = getShard(userId);
 
return shard.query(...);

The real implementation may use:

  • hash functions
  • shard maps
  • metadata services
  • connection pools
  • routing caches

34. Sharding by Tenant#

For SaaS systems, a common strategy is:

tenant_id -> shard

Example:

Tenant A -> Shard 1
Tenant B -> Shard 2
Tenant C -> Shard 1
Tenant D -> Shard 3

Advantages:

  • tenant data locality
  • easier tenant isolation
  • easier tenant-level migration
  • potentially simpler queries

But a very large tenant can become a hot shard.


35. The Mega-Tenant Problem#

Suppose:

Tenant A = 1 million requests/sec
Tenant B = 10k requests/sec
Tenant C = 5k requests/sec

If tenant ID determines the shard:

Tenant A -> Shard 1

Shard 1 becomes overloaded.

Possible solutions include:

  • splitting large tenants
  • tenant + secondary key
  • dedicated shards
  • dynamic placement

This illustrates why a shard key must account for workload distribution, not just data distribution.


36. Composite Shard Keys#

Sometimes one field is insufficient.

A system may use:

tenant_id + user_id

or:

tenant_id + hash(user_id)

This can preserve tenant locality while distributing users within a large tenant.

Example:

Tenant A
   |
   +---- hash(user 1) -> S1
   +---- hash(user 2) -> S3
   +---- hash(user 3) -> S2

This is more flexible but increases routing complexity.


37. Shard Key and Query Locality#

Suppose the most common query is:

Get orders for user_id

Then:

shard key = user_id

may be useful.

Suppose the most common query is:

Get all orders for tenant_id

Then:

shard key = tenant_id

may provide better locality.

The correct key depends on the application's access patterns.


38. Cross-Shard Transactions#

Transactions become more complicated when data lives on different shards.

Example:

User data -> Shard 1
Order data -> Shard 2
Payment data -> Shard 3

Now suppose one business operation updates all three.

Transaction
    |
    +---- S1
    +---- S2
    +---- S3

A traditional single-database transaction cannot automatically provide the same semantics across independently managed shards.

Distributed transaction mechanisms may be required.

They can introduce:

  • coordination
  • latency
  • failure complexity
  • blocking
  • operational overhead

39. Avoiding Cross-Shard Transactions#

A common system-design strategy is to design data ownership so a business operation stays within one shard.

For example:

user_id
   |
   v
Shard 7
 
User
Orders
Cart
Preferences

If most operations are user-centric, placing related data together can reduce cross-shard operations.

This is sometimes called co-location.


40. Co-Location#

Suppose:

Users
Orders
Cart

all use:

user_id

as a routing key.

Then:

User 123
   |
   +---- Users -> S4
   +---- Orders -> S4
   +---- Cart -> S4

A request involving all three can remain on the same shard.

This can significantly simplify architecture.


41. Cross-Shard Joins#

Suppose:

SELECT *
FROM users
JOIN orders ON users.id = orders.user_id;

If users and orders are distributed differently, the database may need to perform a distributed join.

That can be expensive.

A common solution is to:

  • co-locate related data
  • denormalize
  • precompute results
  • use a dedicated analytics/search system

42. Sharding and Indexes#

Each shard typically maintains indexes for the data it owns.

Shard 1
  |
  +-- Data
  +-- Indexes
 
Shard 2
  |
  +-- Data
  +-- Indexes

This can make local indexes smaller than one giant global index.

But global uniqueness can become harder.


43. Global Uniqueness#

Suppose email addresses must be globally unique.

With one database:

UNIQUE(email)

is straightforward.

With many shards:

S1 -> users
S2 -> users
S3 -> users

A unique email could theoretically exist on two shards.

Possible approaches:

  • centralized uniqueness service
  • deterministic routing by unique field
  • globally coordinated ID/constraint system
  • application-level validation

Each adds complexity.


44. ID Generation in Sharded Systems#

Auto-increment IDs can become complicated.

Suppose:

Shard 1 -> ID 1
Shard 2 -> ID 1

Now IDs collide globally.

Possible strategies:

  • UUIDs
  • ULIDs
  • Snowflake-style IDs
  • shard-specific ID ranges
  • centralized ID generation

The choice depends on ordering, size, indexing, and operational requirements.


45. Hot Keys#

A shard can also become hot because one key receives extreme traffic.

Example:

celebrity_user_id = 123
 
Requests:
10 million/sec

If all requests route to one shard:

Shard 7
###########
###########
###########

The shard becomes a bottleneck.

Solutions can include:

  • caching
  • key replication
  • request coalescing
  • splitting the workload
  • adding a secondary distribution key

Sharding alone does not solve hot-key problems.


46. Sharding + Caching#

Suppose:

User 123 profile

is requested millions of times.

Instead of querying the shard every time:

Clients
   |
   v
Cache
   |
 cache hit
   |
   v
Response

Only cache misses reach the shard.

This reduces database pressure.


47. Sharding + Replication#

A common production architecture combines both.

                Shard Router
                     |
       +-------------+-------------+
       |             |             |
       v             v             v
    Shard A       Shard B       Shard C
      /  \          /  \          /  \
     v    v        v    v        v    v
   R-A1 R-A2     R-B1 R-B2     R-C1 R-C2

Each shard may have:

  • one primary
  • multiple replicas

Therefore:

Sharding = distribute data
Replication = copy each shard

This combination is extremely common in large distributed systems.


48. Failure Handling#

Suppose:

Shard B Primary
       X

Its replica can potentially be promoted:

Shard B Replica
      |
      v
New Shard B Primary

Other shards continue operating:

Shard A -> healthy
Shard B -> failover
Shard C -> healthy

The failure of one shard should ideally not bring down the entire cluster.

This is another reason for isolating failure domains.


49. Capacity Planning for Shards#

Suppose one shard safely handles:

20,000 writes/sec

and we need:

100,000 writes/sec

A simple starting estimate:

100,000 / 20,000 = 5

At least five shards are required under that simplified assumption.

But production systems need headroom.

If we target 60% utilization:

Required capacity =
100,000 / 0.60
= 166,667 writes/sec

Then:

166,667 / 20,000
≈ 8.34

So approximately nine shards may be needed under these assumptions.

Capacity planning must also consider:

  • reads
  • storage
  • memory
  • indexes
  • replication
  • failover capacity
  • growth
  • uneven workloads

50. Shard Count Is an Architecture Decision#

Too few shards:

S1
S2

May cause:

  • overloaded nodes
  • difficult scaling
  • large migration later

Too many shards:

S1 S2 S3 S4 S5 S6 S7 S8 S9 S10 ...

May cause:

  • operational overhead
  • more connections
  • more metadata
  • more cross-shard operations
  • more monitoring
  • more failure scenarios

The goal is not maximum shard count.

The goal is appropriate distribution with sufficient headroom.


51. Shard Count and Connection Explosion#

Suppose:

100 application instances

and:

50 shards

If every application instance opens:

20 connections/shard

then:

100 × 50 × 20
= 100,000 database connections

That can be disastrous.

Therefore large sharded systems need careful connection management.

Solutions may include:

  • connection pooling
  • database proxies
  • multiplexing
  • limiting per-shard connections
  • routing only to relevant shards

52. Choosing a Sharding Strategy#

Hash Sharding#

Useful when:

  • even distribution is important
  • point lookups dominate
  • range queries are less important

Range Sharding#

Useful when:

  • range queries are important
  • ordered data access matters
  • time-based workloads benefit from locality

But watch for hot ranges.

Directory Sharding#

Useful when:

  • flexible placement is important
  • entities may move
  • centralized routing metadata is acceptable

Composite Sharding#

Useful when:

  • one key does not sufficiently distribute workload
  • locality and distribution both matter

53. Practical Design: Sharded URL Shortener#

Suppose:

100 million new URLs/day

A URL shortener stores:

short_code
long_url
created_at
user_id

A possible shard key:

short_code

For a lookup:

GET /abc123

the router can calculate:

hash("abc123")
        |
        v
     Shard 7

Then:

Shard 7
   |
   +---- abc123 -> https://example.com/...

This makes the read path shard-local.


54. URL Shortener Architecture#

                    Client
                      |
                      v
                Load Balancer
                      |
                      v
                API Servers
                      |
                      v
                 Shard Router
                      |
       +--------------+--------------+
       |              |              |
       v              v              v
     Shard 1        Shard 2        Shard 3
      /  \           /  \           /  \
     R1  R2         R1  R2         R1  R2

Reads can be distributed among replicas within the selected shard.

Writes go to the primary of the selected shard.


55. Practical Design: Social Media#

Suppose a social network has:

Users
Posts
Followers
Likes
Comments

A possible approach is:

user_id -> shard

Then user-centric data can be co-located.

User 123 -> Shard 4
 
Posts      -> Shard 4
Profile    -> Shard 4
Settings   -> Shard 4

However, a celebrity with millions of followers can create hot-key problems.

The architecture may need:

  • caching
  • feed fan-out strategies
  • replicated hot data
  • asynchronous processing

Sharding is one component of the overall design.


56. Practical Design: Time-Series Data#

Suppose we store:

IoT sensor readings

with:

device_id
timestamp
value

A range/time-based strategy might partition data by:

day
week
month

Example:

2026-01 -> Partition 1
2026-02 -> Partition 2
2026-03 -> Partition 3

This can make time-range queries efficient.

But if all writes target the current time partition, that partition can become hot.

A secondary distribution strategy may be needed.


57. Common Mistakes#

Mistake 1: Sharding too early#

If one well-designed database can handle the workload, sharding may add unnecessary complexity.

Mistake 2: Choosing a shard key only by cardinality#

High cardinality does not guarantee good query locality.

Mistake 3: Ignoring hot partitions#

Average load can hide one overloaded shard.

Mistake 4: Ignoring cross-shard queries#

A system can become slow if common queries require every shard.

Mistake 5: Ignoring resharding#

Data grows.

Your architecture must support future expansion.

Mistake 6: Assuming sharding automatically solves scaling#

Poor shard-key design can simply move the bottleneck to one shard.

Mistake 7: Forgetting replication#

Sharded systems still need high availability.

Mistake 8: Ignoring global uniqueness#

Unique constraints become harder across shards.

Mistake 9: Ignoring transactions#

Cross-shard business operations can be expensive.

Mistake 10: Creating too many connections#

Application × shard × pool size can explode.


58. Interview Questions#

Beginner#

  1. What is database sharding?
  2. What is partitioning?
  3. What is the difference between replication and sharding?
  4. What is horizontal partitioning?
  5. What is vertical partitioning?
  6. What is a shard key?
  7. Why do we need sharding?

Intermediate#

  1. How does hash sharding work?
  2. What is range-based sharding?
  3. What is a hot partition?
  4. What is a scatter-gather query?
  5. Why are cross-shard joins expensive?
  6. What is resharding?
  7. What is consistent hashing?
  8. What are virtual nodes?
  9. How would you choose a shard key?

Advanced#

  1. How would you perform online resharding?
  2. How would you avoid cross-shard transactions?
  3. How would you handle global uniqueness?
  4. How would you generate globally unique IDs?
  5. How would you handle a hot tenant?
  6. How do you combine sharding and replication?
  7. How do you prevent connection explosion?
  8. How would you migrate a billion records to new shards?
  9. How would you design a globally distributed sharded database?

59. Interview Scenario#

Question#

You have 10 shards. One shard is receiving 40% of all traffic while the other nine share the remaining 60%. What could be wrong?

Possible causes:

1. Poor shard key
2. Data skew
3. Hot key
4. Hot tenant
5. Uneven traffic distribution
6. Range hotspot
7. Application routing bug

Investigation:

Traffic
  |
  v
Shard distribution
  |
  +---- requests/shard
  +---- storage/shard
  +---- CPU/shard
  +---- hot keys
  +---- query patterns

Potential solutions:

  • change shard key
  • split the hot shard
  • add a secondary distribution key
  • cache hot records
  • isolate a large tenant
  • rebalance data

60. Production Sharding Checklist#

Data#

  • Dataset is large enough to justify sharding
  • Shard key selected from real access patterns
  • Data distribution tested
  • Write distribution tested
  • Hot-key behavior understood

Querying#

  • Common queries are shard-local
  • Scatter-gather queries identified
  • Cross-shard joins minimized
  • Cross-shard transactions minimized

Operations#

  • Shard metadata is highly available
  • Rebalancing strategy exists
  • Resharding strategy exists
  • Backups exist
  • Restore procedures tested

Availability#

  • Each shard has replicas where needed
  • Failover is defined
  • Failure domains are separated
  • One shard failure does not unnecessarily stop the entire application

Performance#

  • Connection pools are controlled
  • Hot partitions monitored
  • Query latency monitored
  • Storage growth monitored
  • Capacity headroom maintained

61. Master Mental Model#

Remember sharding with this diagram:

                         APPLICATION
                              |
                              v
                        SHARD ROUTER
                              |
            +-----------------+-----------------+
            |                 |                 |
            v                 v                 v
         SHARD A           SHARD B           SHARD C
        /       \          /       \          /       \
       v         v        v         v        v         v
     Primary   Replica  Primary   Replica  Primary   Replica

Think in this order:

1. What is the data?
2. How is it accessed?
3. What should determine its shard?
4. Will data be evenly distributed?
5. Will traffic be evenly distributed?
6. Can common queries stay on one shard?
7. How will shards be rebalanced?
8. What happens when a shard fails?
9. How do we replicate each shard?
10. How will the system grow?

62. Replication + Sharding#

The most important combined mental model from Chapters 13 and 14 is:

                 DATASET
                    |
             +------+------+
             |             |
           SHARD          SHARD
             |             |
        +----+----+   +----+----+
        |         |   |         |
     Primary   Replica Primary Replica

Replication answers:

How do we keep multiple copies of each shard?

Sharding answers:

How do we distribute the total dataset across nodes?

Together:

Sharding
   +
Replication
   =
Scalable + Highly Available Database Architecture

But this still does not solve every problem.

You may also need:

  • caching
  • load balancing
  • queues
  • partition-aware routing
  • observability
  • backups
  • disaster recovery

63. Chapter Summary#

In this chapter, we learned:

  • database partitioning
  • horizontal partitioning
  • vertical partitioning
  • database sharding
  • replication vs partitioning vs sharding
  • shard keys
  • cardinality
  • query locality
  • hash sharding
  • range sharding
  • directory-based sharding
  • consistent hashing
  • virtual nodes
  • hot partitions
  • hot keys
  • data skew
  • scatter-gather queries
  • cross-shard joins
  • cross-shard transactions
  • co-location
  • composite shard keys
  • tenant-based sharding
  • mega-tenant problems
  • global uniqueness
  • distributed ID generation
  • resharding
  • online migration
  • dual writes
  • change-data-capture migration
  • shard metadata
  • shard routers
  • connection explosion
  • capacity planning
  • sharding + replication
  • production failure handling
  • real-world system-design patterns

The central idea is:

Replication copies data to improve availability and read scaling. Sharding splits data to distribute storage and workload. Large-scale systems often combine both.


64. Final Interview Checklist#

Before moving forward, make sure you can explain:

  • Replication vs sharding
  • Horizontal partitioning
  • Vertical partitioning
  • Shard key
  • Cardinality
  • Query locality
  • Hash sharding
  • Range sharding
  • Directory sharding
  • Consistent hashing
  • Virtual nodes
  • Hot partitions
  • Hot keys
  • Data skew
  • Scatter-gather
  • Cross-shard queries
  • Cross-shard transactions
  • Co-location
  • Composite shard keys
  • Tenant sharding
  • Global uniqueness
  • Distributed ID generation
  • Resharding
  • Online migration
  • Dual writes
  • Shard metadata
  • Shard routing
  • Connection management
  • Sharding + replication
  • Failure handling
  • Capacity planning

65. What's Next?#

Chapter 15 — Caching Fundamentals#

Next we move to one of the most important performance and scalability topics in system design: caching.

We will learn:

  • What caching is
  • Why caching dramatically improves performance
  • Cache hit and cache miss
  • Cache-aside pattern
  • Read-through caching
  • Write-through caching
  • Write-back caching
  • Write-around caching
  • TTL
  • Cache eviction
  • LRU and LFU
  • Cache invalidation
  • Cache consistency
  • Distributed caches
  • Redis fundamentals
  • Hot keys
  • Cache stampede
  • Cache penetration
  • Cache avalanche
  • Cache warming
  • Local vs distributed cache
  • CDN cache vs application cache
  • Real-world caching architectures
  • Interview questions
  • Practical exercises
  • A production caching mini-project

Finished this chapter?

Mark it as complete to track your mastery.

Previous ChapterChapter 13 — Database ReplicationNext ChapterChapter 15 — Caching Fundamentals
PrevNext