Scale-Out Series · Part 2 of 2

Database Scaling & MySQL Tuning.

Expanded notes from the database and SQL performance half of my scale-out talk. We cover read replicas, sharding architectures (directory, range, key, consistent hashing, 2ⁿ bitwise scaling and proxies), connection bottlenecks, and real MySQL EXPLAIN benchmarks that separate millisecond lookups from multi-second table scans.

  • Read Replicas & AOP Split
  • Sharding & Consistent Hash
  • 2ⁿ Bitwise Scaling
  • Azure MySQL Limits
  • EXPLAIN & Composite Indexes

01 · Scaling read-heavy workloads

Read replicas & read/write splitting.

Databases are stateful, which makes them much harder to scale out than web servers. There are two main architectural moves: adding read replicas to offload read-heavy traffic, and sharding data across multiple servers when both reads and writes outgrow a single node.

Primary-Replica Read/Write Split Architecture

Slides 6–7 · Writes go to Primary; reads fan out across Replicas
Browser Web Server (ORM / AOP) Write (INSERT / UPDATE / DELETE) Read (SELECT) Primary DB Single source of truth Binlog replication Replica DBs 1…N read-only followers

Most production web apps have an 80/20 or 90/10 read-to-write ratio. Adding read replicas immediately frees the Primary’s CPU and I/O for writes while letting reporting or search queries run safely on followers.

ORM configuration · Laravel

Built-in Read/Write Config

Modern ORMs and frameworks let you configure separate read and write hosts declaratively without rewriting repository queries:

config/database.php (Laravel)
'mysql' => [
  'read' => [
    'host' => ['192.168.1.1', '192.168.1.3'],
  ],
  'write' => [
    'host' => ['192.168.1.2'],
  ],
  'sticky'   => true,  // avoids read-after-write lag
  'driver'   => 'mysql',
  'database' => 'database',
]
AOP Routing · Java & C# / .NET

Dynamic Connection Switching with AOP

In Java (Spring) and C# (.NET), you can intercept service methods via Aspect-Oriented Programming (AOP) and switch the active DB connection in a thread-local / async-local context right before the query executes:

  • Java / Spring: Pair AbstractRoutingDataSource with an aspect checking @Transactional(readOnly = true) or a custom @ReadOnly annotation.
  • C# / EF Core: Use a DbCommandInterceptor or scoped read/write DbContext registrations (ReadDbContext vs WriteDbContext).
Watch out for Replication Lag

Because binlog replication is normally asynchronous, a user who creates a record and immediately refreshes may hit a replica that hasn’t applied the write yet. Fix this by routing critical post-write reads to Primary (e.g. a short sticky window per user/request) or using semi-synchronous replication.

02 · Scaling both reads & writes

Database sharding strategies.

Read replicas cannot solve write bottlenecks or tables that outgrow a single server’s disk and buffer pool. Horizontal sharding splits rows of the same logical table across multiple independent database groups—each with its own Primary and Replicas.

Strategy 1

Directory-Based Sharding

Maintains a dedicated lookup table / routing directory that maps each shard key (e.g. tenant_id or customer_id) to the exact shard holding its rows.

  • Strength: Most flexible strategy—you can move a large tenant to its own dedicated shard simply by migrating its rows and updating one lookup entry.
  • Risks: Connecting to the lookup table before every read or write adds latency (must be heavily cached), and the lookup service itself can become a single point of failure if corrupted or unavailable.
Strategy 2

Range-Based Sharding

Partitions rows by contiguous ranges of a chosen value—most commonly timestamps, dates, order IDs or geographic regions.

  • Real examples: COVID Tracer check-in logs, e-commerce orders partitioned by month/year, and hot/cold data separation (recent data on fast NVMe shards, older history on cheaper archival storage).
  • Risk: Does not prevent uneven data or traffic distribution—all new writes hammer the newest range, creating severe write hotspots.
Strategy 3

Key-Based (Hash) Sharding

Applies a deterministic hash function to a partition key (such as user_id) to compute which shard owns the row—for example, hash(key) mod N.

  • Strength: Spreads reads and writes evenly to prevent hotspots, and routes algorithmically with no central lookup table to maintain.
  • Risk: Changing N (adding shards later) changes mod N for almost every key—unless you use Consistent Hashing or 2ⁿ doubling (next section).

Key-Based Sharding Architecture (2 Shard Groups)

Slide 11 · Each shard group has its own Primary + Read Replicas
Browser Web Server (Shard Router) PartitionKey mod 2 = 0 PartitionKey mod 2 = 1 Group 0 (Even keys) Primary DB Replicas DB Group 1 (Odd keys) Primary DB Replicas DB Write Read Write Read

03 · Growing without chaos

Consistent hashing, 2ⁿ scaling & database proxies.

The hardest moment in key-based sharding isn’t day one—it’s the day you need to expand from m shards to more shards. Two battle-tested approaches solve resharding cleanly: Consistent Hashing and Power-of-Two (2ⁿ) Doubling.

Consistent hashing · Slide 12

Hash Ring & Virtual Nodes

Consistent hashing maps both servers and data keys onto the same circular ring (0 … 2³² − 1). A key belongs to the first server found clockwise from its hash position.

When a server is added or removed, only n / m keys need to be remapped on average (where n is total keys and m is the number of slots), instead of nearly 100% under naive hash % m.

Virtual nodes (vnodes): Assigning multiple ring positions to each physical server (e.g. Server A owns slots 1, 5, 10, 13…) prevents uneven arcs and spreads load smoothly across all remaining hosts when a node fails.

Consistent Hash Ring (16 Virtual Slots · 5 Servers)

Adding Server E takes only a slice from neighbours
Hash Ring ~ n / m moved Server A · 1, 5, 10, 15 Server B · 2, 8, 12, 16 Server C · 4, 9, 13 Server D · 3, 7, 14 Server E · 6, 11 (new)
Slide 13 · Interactive 2ⁿ Bitwise Sharding

Why Power-of-Two (2 → 4 → 8) Doubling Makes Resharding Clean

Formula: hash % 2 == hash & 0b1 Note: Bitwise & is faster than modulo (%), which is more expensive than multiplication and division.

Starting with 2 shards: even keys go to server0, odd keys go to server1. Click 4 Shards or 8 Shards to see how doubling moves exactly half the keys—and every old shard splits cleanly into just one paired new shard (so in production you can clone a replica, flip routing, and delete the unused half!).

Database Proxy Layer ("A Fake Database")

Slide 14 · Centralised routing via MyCat, ProxySQL, ShardingSphere or Vitess
Browser Web Server Database Proxy (Route Config) Speaks MySQL wire protocol · e.g. MyCat / Vitess Group 0 Primary DB Replicas DB Group N Primary DB Replicas DB

A database proxy acts like a single virtual MySQL server so application services stay language-agnostic and don’t duplicate sharding logic. Trade-offs: cross-shard joins, distributed transactions and reporting / analytics become difficult—so analytical workloads are typically streamed via CDC into an OLAP store or data warehouse.

Rule of Thumb: When Should You Actually Shard?

Do not shard prematurely—sharding multiplies operational complexity. A practical MySQL heuristic from production experience: start considering sharding when a single hot table approaches ~5 million+ rows or > 2 GB and vertical tuning + caching + indexes no longer hold latency down (at tens of millions of rows, InnoDB B+Tree depth grows and DDL/backups slow down dramatically). Before sharding, exhaust the performance levers below first.

04 · Protect the database first

Throughput limits, caching & reducing database load.

Even on managed cloud databases, max_connections is a hard ceiling. Rather than immediately throwing bigger hardware or sharding at the problem, the highest-ROI wins come from reducing query execution time and avoiding database hits altogether with a cache.

Little’s Law Intuition · Slide 16

Database Throughput Calculator (Connections × Latency × Cache Hit Rate)

Active DB Connections (Pool Limit)300
Average SQL Query Latency120 ms
Read Cache Hit Rate (Redis / App Cache)0%
Estimated Effective Throughput
2,500 req/s
DB capacity alone: 2,500 QPS (300 conns ÷ 0.120 s). Try lowering query latency from 120 ms to 10 ms—or enabling an 80% Redis cache hit rate—to see throughput multiply without adding a single DB server.
Azure Database for MySQL Tier vCore(s) Default max_connections Min Max Limit
Basic1501050
Basic210010100
General Purpose230010600
General Purpose4625101,250
General Purpose81,250102,500
General Purpose162,500105,000
General Purpose325,0001010,000
General Purpose6410,0001020,000
Memory Optimized2 – 32625 – 10,000101,250 – 20,000
Pillar 1 · Reduce DB requests

Keep Unnecessary Work Out of MySQL

  • Cache before hitting the DB: Serve hot lookups from Redis / Memcached so repeated reads never consume a DB connection.
  • Move formatting & FK logic to the app at scale: Let backend code handle date/string formatting and, on high-throughput or sharded tables, enforce referential integrity in the application layer to avoid foreign-key lock contention.
  • Guard against buffer pool pollution: Even a single unindexed SELECT scanning millions of cold rows can evict hot working pages from InnoDB’s Buffer Pool ("cache poisoning") and drag down every other query on the host.
Pillar 2 · Deep pagination trap

Fixing Deep LIMIT … OFFSET Queries

With a large offset, MySQL reads and discards millions of full table rows before returning 10. Rewriting with a Deferred Join scans only the slim primary-key index first, then fetches the 10 matching rows:

Deep OFFSET Optimization (Slide 17 notes)
-- Fast: small offset
SELECT * FROM report_template ORDER BY id LIMIT 10 OFFSET 10;

-- Slow: reads & discards 6,196,500 full rows!
SELECT * FROM report_template ORDER BY id LIMIT 10 OFFSET 6196500;

-- Deferred Join: scans slim PK index, fetches only 10 rows
SELECT a.*
FROM report_template a
INNER JOIN (
  SELECT id FROM report_template ORDER BY id LIMIT 10 OFFSET 6196500
) b ON a.id = b.id;

-- Even better when random page jumps aren't needed (Keyset / Cursor):
SELECT * FROM report_template WHERE id > 6196500 ORDER BY id LIMIT 10;

05 · SQL hygiene & query analyzer

SQL performance tuning, index types & reading EXPLAIN.

A handful of disciplined SQL habits eliminate the majority of production slow queries before you ever touch infrastructure.

Rule 01

SELECT Explicit Fields

Specify only the columns you need instead of SELECT *. This cuts network and memory I/O, skips wide TEXT/BLOB columns, and unlocks covering indexes (no table lookup required).

Rule 02

Avoid SELECT DISTINCT

Unnecessary DISTINCT forces MySQL to sort or build an internal temporary table to deduplicate results. Fix duplicate joins at the root instead of papering over them with DISTINCT.

Rule 03

Use Explicit INNER JOIN

Write explicit INNER JOIN … ON clauses rather than comma-separated tables in WHERE. It prevents accidental Cartesian products and makes join conditions unambiguous.

Rule 04

Filter in WHERE, Not HAVING

WHERE discards rows before grouping and can leverage indexes; HAVING runs after aggregation. Reserve HAVING strictly for aggregate predicates like COUNT(*) > 5.

Index Type Supported Operators Range / Ordering MySQL Reality
B-Tree (B+Tree) =, >, >=, <, <=, BETWEEN, prefix LIKE 'abc%' Yes (ordered leaves) Default workhorse in InnoDB; supports range scans, prefix matches and index-order ORDER BY.
Hash Index Equality only: =, IN, <=> No range or sort Ultra-fast O(1) exact lookups (used in MEMORY engine and InnoDB’s internal Adaptive Hash Index), cannot handle <, > or prefix matches.
Query Analyzer · Slide 20

Reading MySQL EXPLAIN: type & Extra

Always run EXPLAIN (or DESC) on queries touching large tables. The type column ranks how MySQL locates rows, from fastest (left) to slowest (right):

system const eq_ref ref fulltext ref_or_null index_merge unique_subquery index_subquery range index ALL

When to take action on type: Aim for const, eq_ref, ref or tight range. If you see index (full index scan) or ALL (full table scan) on a large table, rewrite the SQL or add a proper index.

Red flags in Extra: Watch out for Using filesort (extra sorting pass because the index doesn’t match ORDER BY) and Using temporary (internal temp table for GROUP BY / DISTINCT). Green flags: Using index (covering index) and Using index condition (ICP).

06 · Real MySQL evidence

Live benchmarks, index killers & optimizer exceptions.

Having an index on a column does not guarantee MySQL will use it. Below are the exact benchmark outputs from the talk showing how a single expression on an indexed column turns a 0.00 sec lookup into a 1.92 sec full table scan—and when the MySQL optimizer intentionally skips an index for good reason.

Benchmark 1: Arithmetic on the Primary Key (Slide 21)

BAD · Arithmetic wraps indexed column
mysql> SELECT * FROM report_template WHERE id + 10 < 20;
+----+------+-------------+----------+----------+
| id | name | description | reportId | hasScore |
+----+------+-------------+----------+----------+
|  1 | 1    | NULL        |        1 |     NULL |
...
|  9 | 1    | NULL        |        1 |     NULL |
+----+------+-------------+----------+----------+
9 rows in set (1.92 sec)  ← Full table scan!
GOOD · Keep indexed column bare (SARGable)
mysql> SELECT * FROM report_template WHERE id < 10;
+----+------+-------------+----------+----------+
| id | name | description | reportId | hasScore |
+----+------+-------------+----------+----------+
|  1 | 1    | NULL        |        1 |     NULL |
...
|  9 | 1    | NULL        |        1 |     NULL |
+----+------+-------------+----------+----------+
9 rows in set (0.00 sec)  ← Instant B-Tree range!

Benchmark 2: Date Function on Indexed created Column (Slide 22)

BAD · datediff(now(), created) < 100
mysql> EXPLAIN SELECT * FROM report_template
       WHERE datediff(now(), created) < 100\G
         table: report_template
          type: ALL
 possible_keys: NULL
           key: NULL
          rows: 97241
         Extra: Using where
GOOD · Move computation to the constant side
mysql> EXPLAIN SELECT * FROM report_template
       WHERE created < adddate(now(), -100)\G
         table: report_template
          type: range
 possible_keys: idx_created
           key: idx_created
       key_len: 6
          rows: 9999
         Extra: Using index condition
Index Anti-Patterns · Slide 23

Five Common Patterns That Disable Indexes

Anti-Pattern Why It Fails Better Alternative
!=, <>, NOT IN, NOT EXISTS, NOT LIKE Negations typically match most of the table, defeating B-Tree narrowing. Use positive ranges, explicit IN (...) sets, or LEFT JOIN … IS NULL where appropriate.
Implicit type conversion
WHERE name = 1 (when name is VARCHAR)
MySQL casts every stored string to a number (CAST(name AS DOUBLE) = 1), making the index unusable. Always match literal types to column types: WHERE name = '1'.
Leading wildcard
LIKE '%abc%'
B-Tree keys are ordered from the leftmost character, so an unknown prefix forces a full scan. Use prefix search LIKE 'abc%' (uses index) or a full-text / Elasticsearch index for substring search.
Calculations / functions on column
WHERE id + 10 < 20
The engine must evaluate the function on every row before comparing. Move all arithmetic and date math to the constant side: WHERE id < 10.
Unindexed OR
WHERE name = '1' OR created = '2021-05-02'
If either branch lacks a usable index, MySQL falls back to a full table scan. Index both columns (allowing index_merge) or split into two indexed queries combined with UNION ALL.
Cost-Based Optimizer · Slide 25

Exception: When MySQL Intentionally Skips a Valid Index

Even when your predicate is perfectly SARGable and possible_keys lists the index, MySQL’s cost-based optimizer may still choose type: ALL if it estimates a sequential table scan will be faster than jumping back and forth between the secondary index and clustered primary key (bookmark lookups):

  • Tiny table: Fewer than ~10 rows with short row length—reading one data page beats traversing an index.
  • No usable filter: Neither WHERE nor ON constrains any indexed column.
  • High match ratio: The condition matches a large share of the table (typically > 20–30%, like filtered: 50.00 on the right), making random index lookups slower than sequential disk reads.
  • Low cardinality: A column with very few distinct values (e.g. boolean flag or 2-state enum) points to too many rows per key.
Slide 25 · Flipping < to > flips the plan to ALL!
mysql> EXPLAIN SELECT * FROM report_template
       WHERE created > adddate(now(), -100)\G
         table: report_template
          type: ALL
 possible_keys: idx_created   ← Index IS eligible!
           key: NULL          ← Optimizer skipped it
          rows: 97241
      filtered: 50.00         ← Too many rows match
         Extra: Using where

07 · Multi-column mastery & gotchas

Composite INDEX(a, b, c) & everyday MySQL pitfalls.

A composite B-Tree index stores keys sorted first by a, then by b within equal a, then by c within equal (a, b)—just like a phone book ordered by (Last Name, First Name, Middle Initial). Click any query row below to inspect how the Leftmost Prefix Rule behaves.

Interactive Leftmost Prefix Matrix — INDEX(a, b, c)

Click any row to see why
Query Predicate Index Used? Columns Used
WHERE a = 3 Yes, only using a a
WHERE a = 3 AND b = 5 Yes, using a, b a, b
WHERE a = 3 AND b = 5 AND c = 4 Yes, using a, b, c a, b, c
WHERE a = 3 AND b = 5 ORDER BY c Yes, using a, b, c a, b (lookup) + c (sort)
WHERE b = 3 OR c = 4 No None
WHERE a = 3 AND c = 4 Yes, only using a a (b missing breaks c)
WHERE a = 3 AND b > 10 AND c = 7 Yes, using a, b a, b (range on b stops c)
WHERE a = 3 AND b LIKE 'xx%' AND c = 7 Yes, using a, b a, b (prefix range stops c)
WHERE a = 3 → Yes, only using a

Matches the leftmost column (a), so MySQL performs a clean B-Tree ref lookup on a.

Covering Index & UPDATE Locking Bonus (Slide 24 notes)

Compare SELECT * FROM report WHERE organisationId = 1 AND type = 2 against SELECT id, organisationId, type, date FROM report WHERE organisationId = 1 AND type = 2: when every selected column already lives inside the composite index (plus InnoDB’s implicit primary key id), MySQL answers straight from the index (Extra: Using index) with zero table lookups. Also remember UPDATE queries rely on indexes too—in InnoDB, an UPDATE without a usable index can lock every scanned row in the table!

Pitfall 1 · Three-valued NULL

Check NULL with IS NULL / ISNULL()

In SQL, NULL represents an unknown value, not an empty string or zero. Standard equality operators never return true for NULL:

  • NULL = NULL evaluates to NULL (not TRUE)
  • NULL <> NULL evaluates to NULL (not FALSE)
  • NULL <> 1 evaluates to NULL

Always use IS NULL, IS NOT NULL, or ISNULL(expr) (and prefer IS NULL in WHERE clauses so indexes remain usable).

Pitfall 2 · Race conditions

Enforce Uniqueness with a UNIQUE INDEX

If business logic forbids duplicate values (e.g. email addresses, invoice numbers, idempotency keys), add a UNIQUE INDEX in the database.

Application-level "check-then-insert" code inevitably suffers race conditions under concurrent requests; only a database unique constraint guarantees integrity atomically.

Pitfall 3 · ORM full-row saves

UPDATE Only Changed Fields

Avoid blindly issuing UPDATE table SET col1=…, col2=…, … col30=… when only one field changed.

Overwriting unchanged columns increases concurrency and lock conflict risk (especially overwriting concurrent edits from another request), triggers unnecessary secondary-index maintenance, lowers write performance, and bloats binlog file size under row-based replication.

Scale-Out Series · Complete

Scale horizontally where it’s cheap; tune ruthlessly where it’s stateful.

Want to revisit how traffic reaches your application servers in the first place—including Layer 2 DSR, Layer 4 vs Layer 7 routing, and the interactive Load Balancer Simulator?