GOAT EngineerPreparing your learning space…

System Design · Concept Library · Free article

Application-Level Shard Routing: How a Query Finds Its One Shard

Once data is split across shards, compute which shard owns a row from its key and ask only that one. Broadcasting every query to every shard is a self-inflicted denial of service. The routing itself can live in your app, in a proxy like Vitess, or in the database engine.

When a query arrives at a sharded database, something has to decide which of the N shards owns the row — and there are two ways to answer. The cheap, correct one is to compute it: run the shard key through the same hash the data used, learn the one shard that owns it, and send exactly one targeted query. The tempting, expensive one is to ask everyone: broadcast the query to all N shards and take whoever answers (scatter-gather) — which multiplies every request N×, drains your connection pools, and turns a viral spike into a self-inflicted DoS. So the rule is simple: route to the one shard, never broadcast. The real design decision is where that routing lives — in your application (one hop, but every service is welded to the shard layout), in a dedicated proxy tier (Vitess, ProxySQL — the app stays dumb and the layout can change without redeploying anything, at the cost of an extra hop), or inside the database engine (Citus, Postgres FDW). Pick by how often your shard layout changes and how many services touch it.

A click arrives — which of the four shards has the link?

Hatch just split its billion-row link table across four shards, and the fire is out — each shard takes only its quarter of the writes. But now every single redirect has a new problem to solve. Someone clicks hatch.ly/abc123, and to send them onward Hatch needs the destination URL for that one link — a single row that now lives on exactly one of the four shards. Before sharding, there was one database; you just asked it. Now there are four, none of which can see the others, and the request has to figure out which one to ask. Get that answer cheaply and the redirect stays a crisp single query. Get it wrong and you can melt the very cluster you just built to save yourself.

Compute the shard, or ask them all?

There are exactly two ways to find the shard that owns abc123, and the gap between them is the whole lesson. The first is to compute it: the data was placed by running its key through a hash — hash("abc123") % 4 = 1 — so you run the very same hash on the incoming request, get 1, and send your query to shard 1 and nowhere else. One targeted query, straight to the owner. The second is to ask everyone: fire the query at all four shards at once, and whichever one actually has the row answers (the other three shrug and return nothing). This is called scatter-gather, and it works — you always find the row — which is exactly what makes it a trap. It looks harmless at low traffic and quietly turns catastrophic under load.

Why catastrophic? Count the queries. With computed routing, one click is one database query. With broadcast, one click is four — one per shard. That 4× multiplier is invisible when Hatch is quiet and lethal when MegaDrop goes viral: at 85,000 clicks a second, computed routing is 85,000 queries a second spread neatly one-per-shard, while broadcast is 340,000 queries a second, every shard doing four times the work, all of it redundant. The math only gets worse as you add shards — broadcast to 10 shards and every request costs 10 queries. You did not run out of database capacity; you manufactured the shortage by asking four machines a question only one of them could answer.

Application-level routing: hash first, then ask once

The fix is the thing this page is named for. Application-level shard routing means your application computes the destination shard itself, before it opens a single connection: it holds a small shard map (which shard numbers exist, and how to reach each one), runs the shard key through the hash to get the shard number, and sends the query to exactly that one shard. The router in the middle of the redirect acts like a concierge who already knows every guest’s table number — it walks the request straight to shard 1 rather than knocking on all four doors. Each click becomes exactly one targeted, single-shard query, and the cluster hums along at a healthy utilisation instead of drowning in its own redundant work.

It is worth being precise about what the app computes, because it is not magic: it is the same one line the data placement used. Store the row with shard = hash(key) % N, and route the read with the identical shard = hash(key) % N. As long as the routing hash and the placement hash agree, the query lands on the owner every time. (The catch hiding in that % N — that changing N moves the data — is the resharding story the flagship tells; here we only care that routing and placement use the same rule.)

The interactive version of this example is available when JavaScript loads.

Why broadcasting is a self-inflicted DoS

The interactive above hides a second, nastier failure inside that 4× multiplier — one that does not just make things slow, it makes them fall over. Every one of those queries needs a database connection, and connections are a hard, finite resource: each shard has a pool of maybe a few hundred, and each open connection costs real memory on the database. Under computed routing, 85,000 clicks draw from the pools one query at a time. Under broadcast, the same 85,000 clicks demand four times the connections at once — and when a pool runs dry, new queries don’t slow down, they queue and then fail. The network cards saturate, the pools exhaust, and the database spends its last healthy moments doing quadruple work to answer questions three-quarters of which were pointless. That is a self-inflicted denial of service: no attacker required, just a routing choice.

Where should the routing live?

So you route to one shard — the open question is who does the routing. "Application-level" is the most common answer, but it is one of three, and they trade the same thing against each other: how simple the request path is versus how tightly your application is welded to the shard layout. Meet all three, because "where does routing live?" is a staff-level design question.

The three places the routing decision can live

  • In the application (app-side). Your service holds the shard map and computes the shard itself, then connects straight to it. The upside is speed and simplicity — one network hop, no extra moving parts. The downside is coupling: every service that touches the database must embed the same shard map and the same hash, so changing the layout means changing and redeploying all of them, and a polyglot fleet has to reimplement routing identically in every language.
  • In a proxy / coordinator tier. A dedicated middle tier (Vitess’s VTGate, ProxySQL) speaks the database’s own protocol, so your app connects to it as if it were a single ordinary database and stays blissfully unaware that sharding exists. The proxy parses each query, routes it to the right shard, and even merges cross-shard results. The upside is decoupling: the shard map lives in one place, so the layout can change without touching a single application, and the proxy can buffer queries during a reshard cutover. The cost is an extra network hop and a whole tier you must run, scale, and keep highly available.
  • Inside the database engine. Some systems make the database itself distributed: you talk to a coordinator node (Citus for Postgres) or a router process (MongoDB’s mongos) that transparently routes to the workers, or use foreign-data wrappers (Postgres FDW) so some tables secretly live on other servers. The app just writes normal SQL. The upside is that routing is invisible; the downside is you are married to that engine, and its query push-down has limits.

The interactive version of this example is available when JavaScript loads.

The shard map — and why changing it is the whole argument

Every routing model, wherever it lives, needs the same thing: an authoritative shard map — the source of truth for which shards exist and which key goes where. And the entire case for a proxy tier comes down to what happens the day that map changes. Add a fifth shard, and the map is now wrong everywhere it lives. If it lives app-side, it lives inside every service — so you must ship a new build to all of them, roughly in lockstep, and for the window where some services have the new map and some have the old one, they disagree about where a key lives (one writes it to shard 4, another looks for it on shard 1). If it lives in a proxy, you update it in exactly one place, and every app sees the change at once without a single redeploy.

The interactive version of this example is available when JavaScript loads.

Who routes, and how

You rarely write a router from scratch — you pick one of these and configure it. The map, from thinnest to most transparent:

Where shard routing lives in real stacks — from an app-side library to a fully transparent engine.
ToolModelHow your app sees it
App-side libraryIn the applicationThe app holds the shard map and picks the shard before connecting
Vitess (VTGate)Proxy tier (MySQL)The app connects to VTGate as if it were one MySQL; it routes + merges, and can buffer during reshards
ProxySQLProxy tier (MySQL)A rule-based proxy routes queries by pattern; the app is unaware of shards
CitusIn-engine (Postgres)The app talks to a coordinator node that transparently routes to worker shards
MongoDB mongosRouter processA mongos router uses the config servers’ map to send each query to the owning shard
Postgres FDWIn-engineForeign tables live on other servers; the engine routes with no app awareness

Show me the code

  1. Hold the shard map as connection pools, one per shard: shards = [pool0, pool1, pool2, pool3].
  2. On every request, compute the shard from the key with the same hash the data was placed by: i = hash(shardKey) % shards.length.
  3. Send the query to that one pool and no other: shards[i].query(sql, params) — one targeted, single-shard query.
  4. Never write Promise.all(shards.map(...)) for a query that names the shard key — that is the broadcast self-DoS. Reserve fan-out strictly for queries that cannot name the key, and bound it.
  5. Keep the shard map in one authoritative place (a config service, or the proxy’s config) rather than compiled into each service — so a topology change is one update, not a fleet-wide redeploy.
  6. Or skip all of the above: connect to a proxy (VTGate) or coordinator (Citus) as if it were one database, and let it route.

Pitfalls that bite in production

  • Broadcasting a query you could have routed. The headline mistake: you know the shard key but spray all N shards anyway, multiplying every request by the shard count and self-DoSing under load.
  • Inconsistent shard maps across services. Two services with different maps route the same key to different shards — silent data loss and phantom reads. One authoritative map, everywhere.
  • Compiling the map into every service. If the map is baked into code, every topology change is a coordinated, risky, fleet-wide redeploy with a window where services disagree.
  • Treating the routing tier as free. A proxy is a real dependency on the hot path — it needs to be scaled and made highly available, or it becomes a single point of failure in front of your whole database.
  • Unbounded fan-out. Even the honest, unavoidable scatter-gather must be bounded and, ideally, served from replicas or a separate analytics store — not left to hammer the primary shards.
  • A routing hash that drifts from the placement hash. If the router and the data placement ever use different hashes, queries look for rows on the wrong shard. They must be the same rule, forever.

Best practices

  • Route to the one shard whenever the query names the shard key — compute the shard, send one targeted query, and never broadcast by default.
  • Fan out only when the query cannot name the key, and bound it — serve those from replicas or an analytics store so they do not tax the primaries.
  • Keep one authoritative shard map and give every router the same view; never let two services disagree about where a key lives.
  • Put routing where your rate of change demands it — app-side for a single service that rarely reshards; a proxy tier for a fleet that reshards as it grows.
  • Make the routing tier highly available if you use one — it is on the hot path in front of the whole database.
  • Use the same hash for routing and placement, and change it only through the deliberate resharding process.

The interview deck — intern to principal

Your data is sharded. How does a query find the right shard? (intern)
Compute it: run the shard key through the same hash the data was placed with (hash(key) % N) to get the one shard that owns the row, and send a single targeted query there. You never have to guess or search.
Why not just query all the shards and take whoever answers? (intern → SDE2)
That is scatter-gather, and it multiplies every request by the shard count — broadcast to 4 shards and one click becomes four queries. Under load it exhausts connection pools and saturates NICs, a self-inflicted DoS. Only fan out when the query genuinely cannot name the shard key.
Where should the routing logic live? (SDE2 → senior)
Three options: app-side (the app computes the shard — one hop, but every service is coupled to the layout), a proxy tier like Vitess/ProxySQL (the app talks to it as one database; the layout can change centrally, at the cost of a hop), or in-engine (Citus/mongos route transparently). Choose by how often you reshard and how many services touch the data.
Why would you add a proxy tier instead of routing in the app? (senior → staff)
The shard map. App-side, the map lives in every service, so changing the layout means redeploying all of them in lockstep — with a window where services disagree about where a key lives. A proxy holds the map in one place, so topology changes without app redeploys, and it can buffer queries during a reshard cutover.
A query has to hit every shard anyway. Where does that happen, and how do you keep it sane? (staff)
The routing tier fans out and merges (VTGate does this). Keep it rare — it is only for queries that cannot name the shard key — bound the fan-out, and serve it from read replicas or a separate analytics store so it does not tax the primary shards. It is the tail-latency cost the sharding page covers.

The one thing to carry

Sharding split your data; routing finds it again — and the whole discipline is one sentence: send each query to the one shard that owns its key, and never ask the others. Compute the shard from the key, send a single targeted query, and treat broadcasting as the self-DoS it is — a 4× (or N×) multiplier that drains your pools for answers three-quarters of your shards never had. Then make the one real design choice: where the routing lives — in your app for simplicity, in a proxy for a fleet that changes shape, in the engine to forget about it entirely — decided by how often your shard layout changes.

By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.