Why your first query on a client's database gets revenue wrong
The table may be one shard, customers may live in another database, or a copied region column may never have been updated.
In brief
- Federation splits by function; sharding splits one table into several parts that share a schema. Once a single table grows too large, federation stops helping and sharding is the option left.
- The shard key is the most important design decision and very expensive to change, so it tells you the axis along which the client usually queries its data.
- A cross-shard query is only as fast as the slowest shard, and both ways of splitting make JOINs harder, so map the data before you write a SELECT.
Picture your first week at a retail client. You have read-only access and have to build an agent that answers “revenue last month by region”. You write SELECT ... JOIN customers ... GROUP BY region, run it, and get a number so far below the finance report that it makes no sense.
The query has no syntax error and the database isn’t broken. The orders table you are reading may be just one shard. customers may live in a different database altogether, or the region column in orders may be a copy made long ago and never updated.
To work out what is going on, you need to tell apart two ways of splitting a database. Federation splits databases by function: users in one place, orders in another. Sharding divides the data of a single table across several databases with the same schema, each holding its own subset.
When one function or one table grows too large, federation stops working, and that is when sharding becomes the option. But for an FDE, the practical question is rarely “which should we choose”. It is what the client has already chosen, and how that changes your query.
Federation vs sharding: how do they differ?
The table below is the quickest way to recognise each technique when you open a client’s system.
| Criterion | Federation | Sharding |
|---|---|---|
| What it splits by | Business function | Rows of data, each shard holding a subset |
| Schema | Each database has its own schema | Every shard has the same schema |
| Typical traces | Each database is named after a domain: users, products, orders | Several databases with the same structure, numbered names |
| JOIN | Joining data across two databases is more complex | A cross-shard query is as slow as the slowest shard |
| When it stops working | When one function or one table becomes too large | When data piles up on a few shards |
| What your query must do | Join in the application layer or a warehouse | Fan out, merge with SUM and COUNT |
Both require changes to application logic, according to the system-design-primer. Federation is also described as a way of making several physical databases look like one logical database, so don’t be surprised if a client’s data access layer hides the fact that the data lives in several places.
Why is the client’s database no longer a single block?
MongoDB points out that SQL databases have traditionally been scaled vertically: adding CPU, storage or memory to a single server. When one server can no longer cope, the client has to split the data across several places, and federation and sharding are both ways of doing that.
A third technique often comes along with them: denormalization, a strategy applied to an already normalised database to improve performance. It makes reads faster at the cost of some write performance.
The three often appear together. Azure itself advises sharded designs to denormalize so that entities that are often queried together, such as customers and their orders, sit on the same shard. So when you find one technique, go looking for the other two.
The shard key tells you the axis along which the client queries its data
Azure calls the shard key the most important design decision. To change it later, a client usually has to move all its data into a new shard layout, which is costly and risky on a live system. The shard key therefore shows which axis the client’s engineering team bet most queries would follow.
If the client shards by customer_id, a question such as “orders for customer X” lands on exactly one shard. Your question, revenue by region across all customers, has to go through every shard. Azure notes that even when the queries run in parallel, overall latency is set by the slowest shard.
The sharding strategy is also worth asking about. Azure lists four: lookup (also called directory-based, which uses a map to route requests to the shard holding the data), range, hash and geographic. In the lookup strategy, the shard map is usually the first document you should ask for.
If the client splits with hash(key) mod N, you can work out the cost of adding a shard yourself. Going from 4 to 5 shards, a key stays put only if h mod 4 equals h mod 5.
Since 20 is the least common multiple of 4 and 5, you only need to check the 20 possible values of h mod 20: four of them, 0, 1, 2 and 3, satisfy the condition, and the other 16 do not.
If the hash is evenly distributed, only about 4/20 of keys stay put, so about 80% of keys have to move. This number matters because while data is being moved, an order may temporarily sit on the old shard, the new shard, or both. Ask whether a migration is under way before you trust a total.
A worked example: revenue by region
Back to the hypothetical retail client. After a session reading connection strings and talking to the DBA, you can draw the picture: orders is sharded by customer_id across 3 shards. customers and products sit in two separate databases, federation-style. orders has a customer_region column, copied from customers when the order is created.
Thanks to this duplicated column, you don’t need to JOIN across to the customer database, which is exactly why people denormalize. What is left is to fan out to each shard and merge the results:
from collections import defaultdict
SHARDS = ["orders_shard_0", "orders_shard_1", "orders_shard_2"]
SQL = """
SELECT customer_region AS region,
SUM(total) AS revenue,
COUNT(*) AS n_orders
FROM orders
WHERE order_date >= %s AND order_date < %s
GROUP BY customer_region
"""
def revenue_by_region(start, end):
agg = defaultdict(lambda: {"revenue": 0, "n_orders": 0})
for dsn in SHARDS:
for region, revenue, n in run_query(dsn, SQL, [start, end]):
agg[region]["revenue"] += revenue
agg[region]["n_orders"] += n
for r in agg.values():
r["avg_order"] = r["revenue"] / r["n_orders"]
return dict(agg)
The detail to notice is the line that computes avg_order. Each shard returns only SUM and COUNT, and the average is calculated after merging.
Suppose shard 0 has 10 orders averaging 100, and shard 1 has 1,000 orders averaging 50. The average of the two averages is 75, while the correct figure is (1,000 + 50,000) / 1,010, roughly 50.5.
Now the denormalized column. customer_region is the customer’s region at the time of the order. If a customer moves from the North region to the South, their old orders still carry the North label. This is a business question: does finance want revenue by region at the time of purchase, or by current region? Ask before the agent answers on their behalf.
Suppose they also need revenue by product category, and categories exist only in the products database. This is where federation makes life hard, because JOINs across two databases are more complex. A practical approach is to pull the product_id → category mapping table (usually small) into memory or a warehouse, then merge in the application layer.
Five steps before your first query
Step one is to draw the map: how many databases there are, which function each holds, and which tables are sharded. Connection strings, ORM configuration files and names like orders_shard_07 are the fastest clues. Step two is to find the shard key and the sharding strategy, then ask whether any data migration is running.
Step three is to list the duplicated columns and trace where each one comes from: when it is updated, by which job, and whether it lags.
Step four is to put each business question into one of three groups: touches a single shard, needs a fan-out, or needs data joined from several functional databases.
The last step is to agree with the client on data freshness: how far behind the source systems a figure aggregated from several places is allowed to be. This is an agreement worth having in writing before the agent answers its first question.
Common FDE mistakes
The most common mistake is believing you are reading all the data when you are reading only one shard. The second is averaging the averages, or running COUNT(DISTINCT) on each shard and adding the results, when the same value can appear on several shards.
The third is harder to spot: running a heavy fan-out against production at peak hours. Data may be unevenly distributed, so one “hot” shard can slow down both your query and the client’s system. Ask whether there is a read replica before you run it.
The last is proposing to “consolidate everything into one database to keep it tidy”, or the opposite, “add more shards to speed things up”, in your first week. Azure says sharding brings significant and permanent complexity, and lists cases where it is not a good fit, including when the bottleneck is on the read side. A client’s system is the result of real trade-offs.
Is federation a kind of sharding?
Not exactly, but don’t argue terminology with the client. A 2007 post on High Scalability classed federation and sharding as two specific cases of partitioning, so clients may use the three words interchangeably. Ask them whether the data is split by function or by row, then write it down correctly yourself.
And is denormalization a sign of poor design? Usually not. A duplicated column tells you the system is optimised for reads, and your job is to find the source column.
On a CV, a line such as “built a fan-out query layer across 3 shards and agreed with the client how to handle duplicated columns and data latency” says far more than “knows sharding”.
The next time you are given access to a client’s database, don’t write a SELECT straight away. Spend an hour drawing a map of the shards, the functional databases and the duplicated columns, because most of the right answers are there.
Was this article useful?
Thanks for the feedback!
6 sources
- Sharding Pattern - Azure Architecture Center | Microsoft Learn · 2026-04-02
- System Design: Database Federation · 2022-09-12
- GitHub - donnemartin/system-design-primer: Learn how to design large-scale systems.
- Denormalization - Wikipedia
- NoSQL Vs SQL Databases | MongoDB
- Is there a difference between partitioning and federation and sharding? · 2007-09-10