Rails World 2026: Sharding Is Hard: Let's Make It Easier! (Tess Griffin) Video: https://www.youtube.com/watch?v=yLoqg7UkryU Talk page: https://www.rubyevents.org/talks/sharding-is-hard-let-s-make-it-easier Unedited machine transcript, generated with Whisper. It contains recognition errors (names, technical terms). Check the video before quoting. ---- Hi, everyone. This is sharding is hard. Let's make it easier. My name is Tess Griffin, and I'm a senior developer at Thoughtbot. Now, let's say your app has had one database for years, and as you grew, you did the obvious thing. You made it bigger. And bigger. And bigger. And now, your infra bill is $500,000 a month. And it's not even keeping up. Queries that used to be instant now crawl. A light breeze, and it falls over. You get a spike in traffic, and suddenly your entire database is on fire, and you have no idea why. And you can't buy a bigger box. It doesn't exist, or it's too expensive. What now? The first thing you want to do is measure. You want to determine why the database is falling over. You can ask Postgres itself. Are we read heavy or write heavy? Which tables take the rights? Which tables got huge? If there are a few big tables taking most of those rights, which people want to target. If the reads are slow. If the reads are slow, there's a cheaper fix. Most read load can leave the database entirely. A replica is a live copy of your database that serves reads. Writes still go to one place, the primary. Writes scale by adding boxes. But every replica still holds every row. And the primary still takes every write. A single database has every write. SQL databases make this trade. SQL databases make this trade on purpose. They trade slower writes so reads can be fast. If it's the writes that are slow, there's nowhere else to send them with one database. A table can get so big that everything it touches slows down. Reads, writes, even indexes get slow. We already tried one fix. We already tried one fix. Vertical scaling. Vertical scaling. A bigger box until the next size up doesn't exist. The other direction is horizontal. The other direction is horizontal. More machines. Nothing has to be bigger. There are just more of them. Sharding is horizontal scaling applied to your database. It can fix both slow writes and giant tables. Every machine. Every machine takes a slice of the writes and holds a slice of the rows. To split, you have to decide which rows go to which machine. You pick one column and that column's value decides where each row lives. So that column is your shard key. A query that carries the shard key goes to one. A query that doesn't goes to all of them. One query that doesn't goes to all of them. One query becomes three. Every machine stops to answer and two of them had nothing. So each of those and sharding has bought you nothing. Meet Nopify. Any resemblance to other storefront platforms is coincidental. This is an ideal case for sharding. A storefront platform, every table hangs off the shop. It hangs off the shop. Draw a circle around one shop. Draw a circle around one shop and nothing sticks out. The shard key is shop ID. The shard key is shop ID. And the things outside of your box, admins, plans, feature flags, they don't belong to any shop. Those stay behind on your primary. And this is our app. It is currently on fire. It's not ideal. It's called their chart. It's called their chart. It's called their chart. It's called their chart. It's called their chart. Also completely original platform. Hundreds of clinics. One Postgres database. Nobody considered sharding before now. Visits and audit logs are the tables currently falling over. And audit logs are huge for us because we want to be HIPAA compliant. And so every access of data requires a log. This is the schema that we need to shard. We need to determine the shard key. We need to determine the shard key. The key has to split the biggest tables on fire. The key has to split the biggest tables on fire, which are visits and audit logs. And a table can only be split by a column it carries. A visit has four IDs on it. The patient, the practitioner, the clinic, and its own. Those are our candidates. For each one, we'll try to cut and see what breaks. The tempting shard key is the patient, the thing the whole app is about. But look at what breaks. Every red line is a query without the key, which visits every shard. The patients belong to more than one clinic, so half your queries wouldn't know which patient to route by, and the other half don't carry a patient at all. What about the practitioner? It's the same kind of problem. Practitioners work at more than one clinic, and almost nothing connects to a practitioner. If almost nothing connects to your key, almost no query knows which shard to go to. What if we shard on the burning table itself? Splitting by visit ID spreads the fire evenly. And some places do do this. But for our case, a visit owns almost nothing and it's everything. Everything for the visit lives somewhere else. Every query now crosses shards. You can split the burning table and still not pick the best shard key. Shard on the data that's easiest to separate. For their chart, that's the clinic. Every right a clinic makes stays inside the circle. One edge crosses. The one edge crosses. Treatments point at remedies. Remedies are the same for every clinic, so what you can do is copy the remedies to every shard, so that way your queries still stay local. Billing doesn't really have anything to do with the clinics, so that can stay on the primary. So the fire splits with this cut. So each shard only takes its own audit logs and visits carry clinic ID. So each shard only takes its own audit logs and visits, which spreads out the fire to our new shards. Everything a clinic does happens on one machine. Joins work. Transactions are plain, single database transactions. If a query misfires or a shard is compromised, damage stops at that shard's clinics, not all of them. So patients can belong to one clinic. So patients can belong to one clinic. So patients can belong to more than one clinic, but we want to keep their records separate. Each clinic is its own covered entity, so it keeps its own patient records. If you need true single-tenant isolation for somebody, you can give them a shard just themselves. So that's the shard as the shard key. Now we have a couple jobs left. Now we have a couple jobs left. We need to move the data onto the shards and we need to route every query to the correct shard. You can do this in Rails or you can use a proxy. A proxy is a box that sits between your app and the database and speaks plain SQL. So your app still talks to one thing while the proxy spreads the data across the shards. So in Postgres. In Postgres, there's an open source proxy. In Postgres, there's an open source proxy. In Postgres, there's an open source proxy. On MySQL, there's the test, and PlanetScale is the managed version. So your database.yaml and Rails points at it instead of at Postgres. So before any data moves, every clinic needs an assigned shard. There are two ways you can assign this. So in the shard, you can compute it or you can store it. So the first option is to compute it. So the first option is to compute it. You run the clinic ID through a hashing function. So this first example is simply clinic ID modulo n, n being the number of shards that you've spun up. Likely you don't actually want to use this one in production because if you change n, then every clinic will move to a different shard. Then every clinic will move to a different shard. Then every clinic will move to a different shard. But whatever you choose the hashing function to be, the mapping works the same way. The function decides where the clinic lives. Not you. You can't move just one clinic. The other option is to store it. A table with one row per clinic. A clinic goes in and the shard comes out. The mapping is data now. The mapping is data now. And that's the point. And that's the point. And that's the point. You choose the placements. Do you have a huge clinic dragging down its whole shard? Move it to a shard of its own with one update. The trade-off would be now every lookup goes through this one table. If for some reason this table is unreachable, then every shard behind it is also unreachable. But it's tiny. And it's tiny. And it's tiny. And it's tiny. And it's tiny. And it's tiny. And it's tiny. And it's tiny. And it's tiny. It's tiny. And it's tiny. And it's tiny. It's tiny. It's tiny. It's tiny. And it's tiny. And it's tiny. It's tiny. And it's tiny. And it's tiny. wires the shards together with connects to, a writer and a reading replica for each, and the tenant scoped models inherent it. Remedies are the same on every shard. Anything that isn't a clinics, like billing, stays on the primary. And this is the primitive. You ask shard map which shard the clinic lives on. And wrap your query and connect it to. Everything inside runs against that shard. That's how you reach one clinic's data. Rails answers exactly one question. Which shard do I talk to? Your shard key is one detail. But the moment you shard, every query needs it. That requires a clinic. It wants to spread. You want to keep it in one place. So, you need to reach a clinic's shard in the visits controller. So, you open it right here. Then again, in reminder job, so you also open it here. And eventually, it spreads everywhere. When you're setting up your data for sharding, you have to find where every clinic, where you find every clinic, where you find every clinic. And you, if you do it this way, you would have to add this logic to every place. And it's really easy to miss one. So, you want to contain it in one place. And luckily, Rails already gives you that. Rails already gives you that. Rails shifts configuration for shard support out of the box. This is the one place that knows how to find a shard. This is the only place. You can go one step further. You can go one step further and move routing out of the app completely onto the proxy. You can go one step further and move routing out of the app completely onto the proxy, hands it the shard key, and it does the routing. You no longer have the shard map to maintain. You don't have to write the resolver. Your app goes back to believing that there's one database while you get the benefits of sharding. What about background jobs? What about background jobs? What about background jobs? The same rule? The same rule. Handle it in one place. You put clinic ID in the jobs arguments. Then a single around perform in application job resolves the shards and wraps perform in connected to. One place decides. Individual jobs never mention shards. And if someone queues a job out of clinic, it'll raise instead of looking at the wrong shard. With the proxy. With the proxy. With the proxy, every process connects to the same endpoint. The same around perform, but instead of connected to, we pass it this SQL, set local, and we set the sharding key. This is inside of a transaction. So, solid queue is database-backed. You want to keep its tables on the primary or give them their own database. You don't want to shard. You don't want to shard this. The set local is the same as with side pick. Whether you use Rails or the proxy. Whether you use Rails or the proxy, the sharding logic should live in one place. What happens if you outgrow the shards that you spun up originally? In Rails, you need to handle that. If you use the hashing function, that will decide what moves. If you store it. If you store it. If you stored everything on your shard map. If you stored everything on your shard map, you can just move the clinics that you choose. If you stored everything on your shard map, you can just move the clinics that you choose. The table was more work to set up front, but it pays for itself the first time you need to add more shards because let's say you have a really big clinic that needs its own shard. You can simply spin up a new one, assign it the ID of the new shard, and you're done. The proxy can simply spin up a new shard. The proxy is the proxy. The proxy. The proxy is the proxy. The proxy is the proxy. The proxy can re-shard while the app keeps serving. There's no mapping to get wrong because you never wrote one if you use the proxy. Because the shard key keeps the clinic's data together, most joins will never have to cross a shard. The joins that do need to cross can't be done in one go. So you ask each shard and merge the answers yourself. This is called scatter. This is called scatter gather. You loop the shards. You loop the shards, run the same query on each, and add the numbers up. So a proxy will do this for you. It fans out. The cross shard reads. You write one query. It hits every shard and merges. A few writes do cross shards. So transactions on one database are atomic. The right is not atomic. The right is only ever seen as a single action. Can you keep a transaction atomic. Can you keep a transaction atomic across shards? That's actually not possible in a distributed system. Once your data lives on machines that talk over a network, you have a choice. You either wait for every machine to agree before anyone answers, or you answer now and have something that catches up to it later. You can't have both in a two-phase commit. In a two-phase commit, you ask every shard. In a two-phase commit, you ask every shard, "Hey, can you do this?" Each locks what it needs and promises yes. Only if everyone promises does anyone commit. This is the wait for everyone answer. It stays transactional, but everyone waits on the slowest shard. And if the shards and if the coordinator dies mid-handshake, the shards are left in doubt. Each has promised and can't take it back. Each has promised and can't take it back. And it sits holding its locks. A two-phase commit is a blocking protocol. So the protocol is the smallest part. Postgres gives you prepare transaction. And a prepared transaction survives crashes. So the hard part of hand rolling this yourself is the plumbing and everything around it. If your code crashes between the prepare and commit, every shard is stuck holding its locks. Postgres will not clean that up for you. Postgres will not clean that up for you. Postgres will not clean that up for you. Postgres will not clean that up for you. Postgres will not clean that up for you. Postgres will not clean that up for you. Postgres will not clean that up for you. Postgres will not clean that up for you. Postgres will not clean that up for you. Postgres will not clean that up for you. Postgres will not clean that up for you. Postgres will not clean that up for you. Postgres will write what does the plumbing, what notices that things are stuck. have to write the thing that goes and finishes that job. Or the proxy can do this for you. You write one plain transaction. It runs the two-phase commit. The same guarantee, the same costs, the locks are still real. You just didn't have to build the plumbing. So the proxy gives you all or nothing across shards. It runs it for you. What it can't give you is atomicity. That left when the data split. A good shard key means you only have to do this for a very small percent of your writes. A proxy can hide the hard parts. It doesn't remove them. A cross shard join is still slow. A two-phase commit is still fragile. The win was never making the hard parts easy. It's arranging things. So you rarely have to handle this. In Rails, you own all the pieces. The migration, the mapping, the routing, the joins, the transactions. Every piece is yours to keep correct and keep running. With a proxy, you can hand that work over and your app still thinks it's on one database. You get the benefits of sharding without all the plumbing. And that's pretty cool. You don't beat sharding. You don't beat sharding. You don't beat sharding. You don't beat sharding by working harder on the hard parts. You don't beat sharding by working harder on the hard parts. You don't beat sharding by working harder on the hard parts. You want to structure things in a way that you avoid them as much as possible. Arrange your data so each thing's work is in one place and the hard parts barely come up. Get that right and most of sharding's pain never happens. Shard on the data that's easiest to separate. So each thing's work is in a way that you don't have to do.