Architecture Patterns in Practice
Data at Scale: CQRS, Read Replicas and Sharding in Practice
October 10, 2026 · 20 min read
Software Architecture, Design Patterns, C#, Python, CQRS, Databases, Sharding, Scalability, Distributed Systems
This post is part of Architecture Patterns in Practice, a series that takes the patterns named in my architecture patterns map and gives each one runnable code. This is part 4, and it covers the data patterns you reach for when one database, used one way, stops being enough.
All three patterns here do the same basic thing: they make more than one copy or one shape of your data. CQRS keeps a second shape for reading. Read replicas keep extra copies for reading. Sharding splits the data so each database holds part of it. Every one of them trades simplicity, and usually consistency, for scale. So before any of them, I'd check the boring fixes: a missing index, an N+1 query, a bigger instance, and a cache. Those solve most "the database is slow" problems.
| Pattern | The problem it solves | What it costs | The old idea underneath |
|---|---|---|---|
| CQRS | Reads and writes need very different shapes | Two models, and the read side lags | Command-Query Separation, at system scale |
| Read replicas | Reads vastly outnumber writes | Replication lag: replicas can be stale | A routing Proxy |
| Sharding | One database can't hold or serve all the data | Cross-shard queries and resharding are hard | Strategy (the shard key) plus a routing Proxy |
| Event sourcing | You need full history, not just current state | High. See the 2025 series | Command log, replayed |
The code runs as is: C# as .NET 10 file-based apps (dotnet run file.cs) and Python 3.12 with only the standard library. The "databases" are dictionaries, so the patterns are visible without a cluster.
CQRS: separate models for writing and reading
The problem. The model that's good for enforcing rules is rarely the model that's good for screens. Placing an order needs normalized data and validation: does the order exist, does every line have a positive quantity. The "my account" page wants something else entirely: order count, lifetime spend, the three most recent orders, in one lookup. If one model serves both, you either join five tables on every page view, or you bend the write model around the screen and the rules get harder to see.
The pattern. Command Query Responsibility Segregation splits the two. Commands change state and go through the write model, which enforces the rules. Queries read from a separate read model that's shaped like the screen. Something keeps the read model up to date: here, the write side records an event, and a projector applies it to the read model.
The example records events in an outbox list in the same step as the write. That's the transactional outbox idea: the state change and "tell the read side" are saved together, so neither can be lost.
Python
from collections import deque
from dataclasses import dataclass
# ---- Write side: commands, rules, a normalized model ----
@dataclass(frozen=True)
class PlaceOrder:
order_id: str
customer_id: str
lines: list[tuple[str, int, int]] # (sku, qty, unit_cents)
class OrderCommands:
def __init__(self, outbox: deque):
self.orders: dict[str, dict] = {} # write model: shaped for rules, not screens
self._outbox = outbox
def handle(self, cmd: PlaceOrder) -> None:
if cmd.order_id in self.orders:
raise ValueError("order already exists")
if not cmd.lines or any(qty <= 0 for _, qty, _ in cmd.lines):
raise ValueError("an order needs at least one line with qty > 0")
total = sum(qty * cents for _, qty, cents in cmd.lines)
self.orders[cmd.order_id] = {"customer_id": cmd.customer_id, "lines": cmd.lines, "total": total}
self._outbox.append({"type": "OrderPlaced", "order_id": cmd.order_id,
"customer_id": cmd.customer_id, "total": total, "items": len(cmd.lines)})
# ---- Read side: a projection shaped exactly like the screen ----
class CustomerOrdersProjection:
def __init__(self):
self.by_customer: dict[str, dict] = {} # read model: one lookup, no joins
self._applied: set[str] = set()
def apply(self, event: dict) -> None:
if event["order_id"] in self._applied: # events arrive at least once
return
self._applied.add(event["order_id"])
view = self.by_customer.setdefault(event["customer_id"], {"order_count": 0, "lifetime_cents": 0, "recent": []})
view["order_count"] += 1
view["lifetime_cents"] += event["total"]
view["recent"] = ([f"{event['order_id']} ({event['items']} items)"] + view["recent"])[:3]
class CustomerQueries:
def __init__(self, projection: CustomerOrdersProjection):
self._p = projection
def summary(self, customer_id: str) -> dict:
return self._p.by_customer.get(customer_id, {"order_count": 0, "lifetime_cents": 0, "recent": []})
outbox: deque = deque()
commands = OrderCommands(outbox)
projection = CustomerOrdersProjection()
queries = CustomerQueries(projection)
commands.handle(PlaceOrder("o-1", "c-7", [("sku-1", 2, 999), ("sku-2", 1, 2500)]))
commands.handle(PlaceOrder("o-2", "c-7", [("sku-3", 1, 1200)]))
print("before projector runs:", queries.summary("c-7")) # the read side lags
while outbox: # in production: a background worker
projection.apply(outbox.popleft())
print("after projector runs: ", queries.summary("c-7"))
try:
commands.handle(PlaceOrder("o-3", "c-7", []))
except ValueError as e:
print("rejected:", e)
before projector runs: {'order_count': 0, 'lifetime_cents': 0, 'recent': []}
after projector runs: {'order_count': 2, 'lifetime_cents': 5698, 'recent': ['o-2 (1 items)', 'o-1 (2 items)']}
rejected: an order needs at least one line with qty > 0
The first line is the cost of CQRS in one line: the orders were saved, but the read model hasn't heard yet. With a background projector, that gap is usually milliseconds, but it's never zero, and your UI has to cope. The common fixes: return the new data from the command so the screen can show it straight away, or have the client wait until the read model reports it has processed that event.
C#
var outbox = new Queue<OrderPlaced>();
var commands = new OrderCommands(outbox);
var projection = new CustomerOrdersProjection();
commands.Handle(new PlaceOrder("o-1", "c-7", [new("sku-1", 2, 999), new("sku-2", 1, 2500)]));
commands.Handle(new PlaceOrder("o-2", "c-7", [new("sku-3", 1, 1200)]));
Console.WriteLine($"before projector: {projection.Summary("c-7")}");
while (outbox.TryDequeue(out var e)) projection.Apply(e); // in production: a background worker
Console.WriteLine($"after projector: {projection.Summary("c-7")}");
try { commands.Handle(new PlaceOrder("o-3", "c-7", [])); }
catch (InvalidOperationException ex) { Console.WriteLine($"rejected: {ex.Message}"); }
// ---- Write side: commands and rules ----
record Line(string Sku, int Qty, int UnitCents);
record PlaceOrder(string OrderId, string CustomerId, List<Line> Lines);
record OrderPlaced(string OrderId, string CustomerId, int TotalCents, int Items);
sealed class OrderCommands(Queue<OrderPlaced> outbox)
{
private readonly Dictionary<string, PlaceOrder> _orders = []; // write model: shaped for rules
public void Handle(PlaceOrder cmd)
{
if (_orders.ContainsKey(cmd.OrderId)) throw new InvalidOperationException("order already exists");
if (cmd.Lines.Count == 0 || cmd.Lines.Any(l => l.Qty <= 0))
throw new InvalidOperationException("an order needs at least one line with qty > 0");
_orders[cmd.OrderId] = cmd;
outbox.Enqueue(new(cmd.OrderId, cmd.CustomerId, cmd.Lines.Sum(l => l.Qty * l.UnitCents), cmd.Lines.Count));
}
}
// ---- Read side: shaped like the screen ----
record CustomerSummary(int OrderCount, int LifetimeCents, string Recent);
sealed class CustomerOrdersProjection
{
private readonly Dictionary<string, CustomerSummary> _byCustomer = []; // read model: one lookup
private readonly HashSet<string> _applied = [];
public void Apply(OrderPlaced e)
{
if (!_applied.Add(e.OrderId)) return; // at-least-once delivery
var v = _byCustomer.GetValueOrDefault(e.CustomerId, new(0, 0, ""));
_byCustomer[e.CustomerId] = new(v.OrderCount + 1, v.LifetimeCents + e.TotalCents,
string.Join(", ", new[] { e.OrderId }.Concat(v.Recent.Split(", ", StringSplitOptions.RemoveEmptyEntries)).Take(3)));
}
public CustomerSummary Summary(string customerId) => _byCustomer.GetValueOrDefault(customerId, new(0, 0, ""));
}
before projector: CustomerSummary { OrderCount = 0, LifetimeCents = 0, Recent = }
after projector: CustomerSummary { OrderCount = 2, LifetimeCents = 5698, Recent = o-2, o-1 }
rejected: an order needs at least one line with qty > 0
Both projections skip events they've already applied, because event delivery is at least once. A projection that counts orders and isn't idempotent will count a redelivered event twice.
You don't need separate databases to get most of the benefit. The lightest version of CQRS is separate classes or handlers for commands and queries in the same app, with queries free to use hand-written SQL or a database view. Go to a separate read store only when the read load or read shape really needs it.
The old idea underneath. Bertrand Meyer's Command-Query Separation: a method should either change state or return data, not both. CQRS applies that rule to whole models. The commands themselves are the GoF Command pattern, and the projector is an Observer of the write side.
When not to use it.
- Plain CRUD. If the screen shows what the form saved, one model is simpler. Martin Fowler's warning about CQRS is that for most systems it adds risky complexity.
- When users must read their own write instantly and you can't design around the lag.
- Everywhere at once. CQRS works best in the one part of the system where reads and writes really differ, not as a default for every module.
Read replicas
The problem. Your app does 50 reads for every write. The primary database spends most of its time on reads, and writes start to queue behind them.
The pattern. Add one or more replicas: copies of the database that receive the primary's change log and apply it. Writes go to the primary. Reads go to the replicas. Most managed databases support this directly: Azure SQL read scale-out (connect with ApplicationIntent=ReadOnly), PostgreSQL streaming replication, Amazon RDS read replicas.
The catch is replication lag. Replication is usually asynchronous, so a replica can be behind the primary. The classic bug: a user saves their profile, the page reloads from a replica, and their change seems to have vanished.
The fix in the code below is read-your-own-writes. After a write, the session remembers the write's log sequence number (LSN). A read goes to the replica only if the replica has applied at least that LSN. Otherwise it goes to the primary. Other users, who didn't make the change, keep reading from the replica, where a few milliseconds of staleness doesn't hurt them.
Python
class Primary:
def __init__(self):
self.data: dict[str, str] = {}
self.log: list[tuple[int, str, str]] = [] # (lsn, key, value): the replication stream
def write(self, key: str, value: str) -> int:
self.data[key] = value
self.log.append((len(self.log) + 1, key, value))
return len(self.log) # the write's log sequence number
class Replica:
def __init__(self, primary: Primary):
self.primary, self.data, self.applied_lsn = primary, {}, 0
def catch_up(self) -> None: # replication is asynchronous; this runs "later"
for lsn, key, value in self.primary.log[self.applied_lsn:]:
self.data[key] = value
self.applied_lsn = lsn
class Router:
"""Writes go to the primary. Reads go to a replica, unless it hasn't seen this session's last write."""
def __init__(self, primary: Primary, replica: Replica):
self.primary, self.replica = primary, replica
def write(self, session: dict, key: str, value: str) -> None:
session["last_write_lsn"] = self.primary.write(key, value)
def read(self, session: dict, key: str) -> tuple[str, str | None]:
if self.replica.applied_lsn >= session.get("last_write_lsn", 0):
return "replica", self.replica.data.get(key)
return "primary", self.primary.data.get(key) # read-your-own-writes
primary = Primary()
replica = Replica(primary)
router = Router(primary, replica)
alice, bob = {}, {}
router.write({}, "profile:alice", "bio v1")
replica.catch_up()
router.write(alice, "profile:alice", "bio v2")
print("alice reads:", router.read(alice, "profile:alice")) # her own write, replica is behind
print("bob reads: ", router.read(bob, "profile:alice")) # stale, and that's acceptable for him
replica.catch_up()
print("after catch-up, alice:", router.read(alice, "profile:alice"))
print("after catch-up, bob: ", router.read(bob, "profile:alice"))
alice reads: ('primary', 'bio v2')
bob reads: ('replica', 'bio v1')
after catch-up, alice: ('replica', 'bio v2')
after catch-up, bob: ('replica', 'bio v2')
Alice sees her own change immediately, from the primary. Bob sees the old bio for a moment, from the replica. Once the replica catches up, both read from the replica again. That's the right outcome for a profile page: the person who made the change never sees it disappear, and the primary only serves the reads that need it.
C#
var primary = new Primary();
var replica = new Replica(primary);
var router = new Router(primary, replica);
Session alice = new(), bob = new();
router.Write(new Session(), "profile:alice", "bio v1");
replica.CatchUp();
router.Write(alice, "profile:alice", "bio v2");
Console.WriteLine($"alice reads: {router.Read(alice, "profile:alice")}"); // her own write; replica is behind
Console.WriteLine($"bob reads: {router.Read(bob, "profile:alice")}"); // stale, acceptable for him
replica.CatchUp();
Console.WriteLine($"after catch-up, bob: {router.Read(bob, "profile:alice")}");
sealed class Session { public long LastWriteLsn; }
sealed class Primary
{
public Dictionary<string, string> Data { get; } = [];
public List<(long Lsn, string Key, string Value)> Log { get; } = []; // the replication stream
public long Write(string key, string value)
{
Data[key] = value;
Log.Add((Log.Count + 1, key, value));
return Log.Count;
}
}
sealed class Replica(Primary primary)
{
public Dictionary<string, string> Data { get; } = [];
public long AppliedLsn { get; private set; }
public void CatchUp() // asynchronous in real life
{
foreach (var (lsn, key, value) in primary.Log.Skip((int)AppliedLsn)) { Data[key] = value; AppliedLsn = lsn; }
}
}
sealed class Router(Primary primary, Replica replica)
{
public void Write(Session s, string key, string value) => s.LastWriteLsn = primary.Write(key, value);
public (string From, string? Value) Read(Session s, string key) =>
replica.AppliedLsn >= s.LastWriteLsn
? ("replica", replica.Data.GetValueOrDefault(key))
: ("primary", primary.Data.GetValueOrDefault(key)); // read-your-own-writes
}
alice reads: (primary, bio v2)
bob reads: (replica, bio v1)
after catch-up, bob: (replica, bio v2)
In a real app, the session's LSN lives in a cookie or a token, and the replica's position comes from the database (PostgreSQL exposes it, for example, through pg_last_wal_replay_lsn()). A simpler version that many apps use: send a user's reads to the primary for a few seconds after they write.
The old idea underneath. The router is a Proxy in front of two real objects, choosing per call. The routing rule is a Strategy: always replica, replica unless stale, or primary for a few seconds after a write.
When not to use it.
- When writes are the bottleneck. Replicas add read capacity only. Every replica still has to apply every write, so they don't help a write-heavy system. That's when sharding comes up.
- For reads that drive decisions. "Is there stock left?" before taking payment must read the primary, or you'll sell the same item twice.
- Before a cache. If the same hot rows are read again and again, cache-aside is cheaper than a second database.
Sharding
The problem. The data no longer fits on one database, or the write rate is more than one primary can handle. Replicas don't help, because they copy everything and replay every write.
The pattern. Split the data across several databases, called shards, by a shard key. Each tenant's (or user's, or device's) rows live on exactly one shard, and a router sends each request to the right one.
Choosing the key is most of the work. A good key:
- Spreads load evenly. Hashing the key helps. A key like "country" doesn't, because one country will be much larger than the rest.
- Keeps related data together. If almost every query is "for tenant X", shard by tenant, and those queries stay on one shard.
- Never changes. Moving a row because its key changed is a cross-database move.
The second most important decision is how keys map to shards. The obvious way, hash(key) % number_of_shards, has a nasty property: adding one shard changes the answer for most keys, so most of your data has to move. The standard fix is a fixed number of slots (Redis Cluster uses 16,384) mapped to shards through a table. Adding a shard means moving a fair share of slots to it. Nothing else changes.
Python
import hashlib
from collections import Counter
SLOTS = 1024 # fixed forever; shards own ranges of slots
def stable_hash(shard_key: str) -> int:
# Python's built-in hash() changes per process, so never use it for routing.
return int.from_bytes(hashlib.sha256(shard_key.encode()).digest()[:8], "big")
def slot_for(shard_key: str) -> int:
return stable_hash(shard_key) % SLOTS
class ShardMap:
"""slot -> shard. Adding a shard moves some slots, not every key."""
def __init__(self, shards: list[str]):
self.owner = {slot: shards[slot % len(shards)] for slot in range(SLOTS)}
def shard_for(self, shard_key: str) -> str:
return self.owner[slot_for(shard_key)]
def add_shard(self, new_shard: str) -> int:
counts = Counter(self.owner.values())
target = SLOTS // (len(counts) + 1) # fair share for the new shard
moved = 0
for slot, shard in self.owner.items():
if moved < target and counts[shard] > target:
self.owner[slot] = new_shard # in production: copy the slot's rows, then flip
counts[shard] -= 1
moved += 1
return moved
tenants = [f"tenant-{i}" for i in range(10_000)]
# Naive: hash mod N. Going from 4 to 5 databases moves most of the data.
naive_moved = sum(stable_hash(t) % 4 != stable_hash(t) % 5 for t in tenants)
print(f"hash mod N, 4 -> 5 shards: {naive_moved / len(tenants):.0%} of tenants move")
shard_map = ShardMap(["db-0", "db-1", "db-2", "db-3"])
before = {t: shard_map.shard_for(t) for t in tenants}
slots_moved = shard_map.add_shard("db-4")
moved = sum(before[t] != shard_map.shard_for(t) for t in tenants)
print(f"slot map, 4 -> 5 shards: {slots_moved} of {SLOTS} slots, {moved / len(tenants):.0%} of tenants move")
print("tenants per shard:", dict(sorted(Counter(shard_map.shard_for(t) for t in tenants).items())))
print("tenant-42 lives on", shard_map.shard_for("tenant-42"))
hash mod N, 4 -> 5 shards: 80% of tenants move
slot map, 4 -> 5 shards: 204 of 1024 slots, 20% of tenants move
tenants per shard: {'db-0': 1955, 'db-1': 2020, 'db-2': 1995, 'db-3': 2028, 'db-4': 2002}
tenant-42 lives on db-4
That's the whole argument for the slot map: going from 4 to 5 shards with plain modulo moves 80% of tenants. With slots it moves 20%, which is the minimum, since the new shard has to end up with a fifth of the data.
C#
using System.Security.Cryptography;
using System.Text;
var tenants = Enumerable.Range(0, 10_000).Select(i => $"tenant-{i}").ToList();
var naiveMoved = tenants.Count(t => ShardMap.StableHash(t) % 4 != ShardMap.StableHash(t) % 5);
Console.WriteLine($"hash mod N, 4 -> 5 shards: {(double)naiveMoved / tenants.Count:P0} of tenants move");
var map = new ShardMap(["db-0", "db-1", "db-2", "db-3"]);
var before = tenants.ToDictionary(t => t, map.ShardFor);
var slotsMoved = map.AddShard("db-4");
var moved = tenants.Count(t => before[t] != map.ShardFor(t));
Console.WriteLine($"slot map, 4 -> 5 shards: {slotsMoved} of {ShardMap.Slots} slots, {(double)moved / tenants.Count:P0} of tenants move");
Console.WriteLine($"tenant-42 lives on {map.ShardFor("tenant-42")}");
sealed class ShardMap
{
public const int Slots = 1024; // fixed forever; shards own slots
private readonly string[] _owner = new string[Slots];
public ShardMap(string[] shards) { for (var s = 0; s < Slots; s++) _owner[s] = shards[s % shards.Length]; }
// string.GetHashCode() is randomized per process in .NET, so never route with it.
public static ulong StableHash(string key) => BitConverter.ToUInt64(SHA256.HashData(Encoding.UTF8.GetBytes(key)));
public string ShardFor(string shardKey) => _owner[StableHash(shardKey) % Slots];
public int AddShard(string newShard)
{
var counts = _owner.CountBy(s => s).ToDictionary();
var target = Slots / (counts.Count + 1);
var moved = 0;
for (var slot = 0; slot < Slots && moved < target; slot++)
{
if (counts[_owner[slot]] <= target) continue;
counts[_owner[slot]]--;
_owner[slot] = newShard; // in production: copy the slot's rows, then flip
moved++;
}
return moved;
}
}
hash mod N, 4 -> 5 shards: 80% of tenants move
slot map, 4 -> 5 shards: 204 of 1024 slots, 21% of tenants move
tenant-42 lives on db-3
The C# numbers differ slightly from Python's because the two versions read the SHA-256 bytes in a different order, so the same tenant lands in a different slot. Both use a stable hash on purpose. string.GetHashCode() in .NET and hash() in Python are randomized per process, so a router built on them would send the same tenant to a different shard after every restart.
Managed databases do this for you. Azure Cosmos DB maps logical partitions (your partition key) onto physical partitions and splits them as data grows. Citus, Vitess and MongoDB do similar work for PostgreSQL, MySQL and documents. The design work that stays with you is choosing the key.
The old idea underneath. The shard key function is a Strategy, and the router is a Proxy that forwards each call to the right real database. The slot table adds a level of indirection, the oldest trick in the book for making a mapping changeable.
When not to use it.
- Early. Sharding is very hard to undo, and it makes every cross-shard operation harder: joins, unique constraints, transactions, reports. Exhaust indexing, caching, replicas and a bigger machine first. The map post puts it at the end of the road for a reason.
- When most queries span all keys. If the main screen is "all orders across all tenants, sorted by date", every request fans out to every shard. That's a job for a separate read model (CQRS again) or an analytics store.
- With a key that creates hot spots. One huge tenant on one shard defeats the point. Big tenants may need their own shard, or a compound key.
Event sourcing
Event sourcing stores every change as an event and rebuilds current state by replaying them. It pairs naturally with CQRS: the events are the write model, and projections like the one above build the read models. It gives you a full audit history and the ability to answer "what did this look like last Tuesday?" It also costs more than anything else in this post: event schemas you can never really change, projections to rebuild, and a team that has to think in events.
I covered it in depth, including when it isn't worth it, in a five-part series in 2025:
- The Honest Truth
- Azure Building Blocks
- Saga Orchestration
- Implementing Sagas with Durable Functions
- Key Concepts and Patterns
Choosing between them
They solve different bottlenecks, so the question is which one you have:
- Reads are slow because the shape is wrong (too many joins, too much computing on read): CQRS, or start with a database view.
- Reads are slow because there are too many of them: cache first, then read replicas.
- Writes are the bottleneck, or the data doesn't fit: sharding, or a managed database that partitions for you.
And they combine. A large system often has a sharded write store, a CQRS projection into a read store built for the main screens, and replicas of that read store for volume.
Next in the series: changing live systems, where anti-corruption layers, expand and contract, and feature flags let you change all of this without downtime.
Check yourself: questions and answers
1. What's the difference between CQRS and CQS?
CQS (Command-Query Separation) is a rule for methods: a method either changes state or returns data. CQRS applies the same split to whole models: a write model for commands and a separate read model for queries, often with its own storage.
2. A user saves their profile and the reloaded page shows the old data. What's the likely cause and fix?
Reads are going to a replica that hasn't applied the write yet. Fix it with read-your-own-writes: route that user's reads to the primary until the replica has caught up to their write's position, or for a short window after they write.
3. Why don't read replicas help a write-heavy workload?
Every replica has to apply every write from the primary. Adding replicas adds read capacity, but the primary still takes all the writes, and each replica repeats them.
4. Why is hash(key) % N a poor way to assign shards?
Changing N changes the result for most keys, so adding a fifth shard to four moves about 80% of the data. A fixed set of slots mapped to shards (or consistent hashing) moves only the share the new shard should own.
5. What makes a good shard key?
It spreads load evenly, keeps the data that's queried together on one shard, and never changes. Tenant ID is the common choice for multi-tenant apps. Anything with a few huge values, like country, makes hot spots.
6. Is CQRS the same as event sourcing?
No. CQRS separates read and write models; the write side can be an ordinary table. Event sourcing stores state as a sequence of events. They work well together, but each is useful without the other.
Further reading
- Martin Fowler, CQRS and CommandQuerySeparation
- Azure Architecture Center, CQRS pattern and Materialized View pattern
- Microsoft Learn, Azure SQL read scale-out
- PostgreSQL docs, High availability, load balancing and replication
- Azure Architecture Center, Sharding pattern and Data partitioning guidance
- Microsoft Learn, Partitioning and horizontal scaling in Azure Cosmos DB
- Redis docs, Redis Cluster specification (the 16,384 hash slots)
- Azure Architecture Center, Event Sourcing pattern, and Martin Fowler, Event Sourcing
- In this blog: Cloud messaging patterns (the transactional outbox that feeds projections) and Cloud structure patterns (cache-aside)
- The previous post in this series: How services talk
Thoughts on this?
Tell me on X: @bobbyencoded · Share this post on X
Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.