How to Distribute Postgres Geographically
xata.io
xata.io
We experimented with using partitioned tables and doing the fancy postgres_fdw thing when we sharded our tenant-clustered tables in 2020. Even with all the Postgres instances in the same region we found the approach unwieldy. Routing queries in the application gives you a lot more control versus needing to teach Postgres the exact logic to route a query, plus do a (dangerous? one-way? global?) schema migration whenever you want to change the routing logic.
We touched on this briefly in our sharding blog post here: https://www.notion.so/blog/sharding-postgres-at-notion
Another reason to avoid complex routing in Postgres is risk. If something goes wrong at 3am in a load-bearing cross-Postgres-instance query, how easily will it be to mitigate that if the routing is happening in Postgres (with whatever advanced clustering system Citus, pgzx, postgres_fdw) versus if the routing is happening in the application? For example if there’s a network partition between the “global” postgres instance and the us-east-2 cluster? Maybe you’re Postgres wizards and know how to handle this with a quick schema change or something in the psql CLI but I’d bet more on my team’s ability to write fault tolerance in the application versus in Postgres internal logic.
From what I understand you decided to do sharding in the application code, and given the current state I think that makes total sense and I'd have probably done the same.
Part of my point with the blog post is that there is a built-in horizontal sharding solution in vanilla Postgres (partitioning + FDW), but it's currently badly lacking when it comes to cluster management, schema changes, distributed transactions, and more. If we put work into it, perhaps we tip the balance and the next successful Notion clone could choose to do it at the DB level.
In 2019 when I was interviewing at companies for my next position I heard from a few places that the original Aurora for Postgres lost their data. It seems like the sentiment on mainline Aurora has improved a bit, but I would never bet my company’s future on an AWS preview technology. Better the devil you know (and everyone else knows).
It does give a "When all you have is a hammer..." vibe to me and begs the question: why not use a system that's designed for use-cases like this and do it reliably and securely ? i.e.: https://www.cockroachlabs.com/docs/stable/multiregion-overvi... (yes, I know full data domiciling requires something even more strict but I currently don't know of any system that can transparently span the globe and stay performant while not sharing any metadata or caching between regions)
(disclaimer: blog post author)
A reason would be that you want to stick to pure Postgres, for example because you want to use Postgres extensions, or prefer the liberal Postgres license.
It can also be a matter of performance, distributed transactions are necessarily slower so if almost all the time you can avoid them by connecting to a single node, which has all the data that the transaction needs, that's going to get you better performance.
I agree that the separation of storage and compute complements this nicely. In fact, we take advantage of it in the Xata platform which uses Aurora.
At my last job, in fintech, we used application-level shard routing with each aggregate root served by a particular RPC service (users, accounts, transactions, etc). When one of these aggregate services were asked to pull data, they would query a central routing service for the server and shard the requested data resided in.
Between them and the DB servers we had a cluster of pgbouncer instances to handle connection oversubscription and the routing of queries around DB instances in the face of failures or maintenance.
While this was pretty effective, the work to manage sharded Postgres, DDL updates, caching, locating, and balancing data was still very complicated and error prone, and was the root of many production outages.
I didn't design this system, but after a couple years leading a platform migration, which necessitated getting into all this at a deep level, I would do it differently. Instead of query routing and DB sharding, I would shard the aggregate root services themselves. Each "sharded" set of these instances would have a simple PG instance (with replica chain) behind it that knows nothing about any other set.
At this point, instead of routing being done by the aggregate root services locating and querying data from DB shards on huge vertically-scaled servers, each set only pulls data from their dedicated DB. A routing facade is placed in front of the set of sets that sends requests from consumers to the one holding the desired data.
With this architecture, the complexity of sharding and vertically scaling at the DB layer, and handling connection oversubscription with a query router like PGbouncer, just falls away.
I would keep these sets, and their DBs, rather small to also reap the benefits of small datasets. One of the biggest issues we had with huge DBs is the time it takes to do anything; as an example, restarting replication in a failed chain could take many hours because of the huge amount of data, and any hiccups in connectivity would quickly overrun our capability to "catch" replication up and we'd have to fall back to zfs-send to resnap.
A larger number of smaller DBs would not improve the total time needed to do something like backups or DDL mutations, but it would significantly reduce the time for any particular instance which reduces overall risk and blast radius of a DB failure.
Another thing I think small DBs can help with is data locality, DB automation, and possibly making the instances effectively ephemeral. When your dataset is small, bringing an instance up from a hot backup can take on the order of a few seconds, and could allow you to schedule the root services and their DB on the same host.
For geographical distribution, the routing facade can also send writes to the set serving that shard in some other region.
Counterpoint: the fewer round trips to the DB you have to do, the faster your app is.
My belief is that as DBAs more or less went away thanks to cloud providers and the rise of Full Stack Engineering, the quiet part that no one wanted to admit was that RDBMS are hideously complicated, and you really need SMEs to use them correctly. Thus, the use of stored procedures, triggers, advanced functions etc. went away in favor of just treating the DB as a dumb store, and doing everything in app logic.
As more and more companies are discovering that actually, you do need DB SMEs (I’m a DBRE; demand for this role has skyrocketed), my hope is we can push some of the logic back out to the DB. I am all for VCS, automated migrations, canary instances, and other careful patterns. I’d just like to see less of treating RDBMS as a document store, and embracing the advantages of the tech already in place.
I personally left in the era of ORMs exactly because it let me build systems in high-productivity languages and frameworks, but also because the cost benefit of RDBMS integration just wasn't there. The DB is absolutely the highest-risk place to put logic in any stack, if something goes wrong _everything_ breaks and it's the most difficult place to fix things.
I don't know what the future looks like for DBs, but I think we'll continue to see them become even more transparent. Devs just want to persist entities, and integrating at the RDBMS level is a slog.
To this end, “devs just want to persist entities” makes me both sad and frustrated. Everyone seems to default to “just use Postgres,” but then don’t want to actually use an RDBMS. If you want a KV store, then use one. If you want a document store, then use one. Don’t subject a relational database to storing giant JSON blobs with UUIDv4 keys, and then complain that it’s slow because you’ve filled the memory with bloated indices, and saturated the disk bandwidth with massive write amplification.