11

Add automatic shard swapping middleware by eileencodes · Pull Request #43665 · r...

 2 years ago
source link: https://github.com/rails/rails/pull/43665
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Copy link

Member

eileencodes commented 10 days ago

This PR adds a middleware that can be used for automatic shard swapping.
The design is similar to the database selector middleware in that the
resolver is provided by the application to determine which shard to
switch to. The selector also takes options to change the default
behavior of the middleware.

The only supported option is lock at the moment which will allow shard
swapping in a request, otherwise it defaults to true and prevents shard
swapping. This will help protect mistakenly switching shards inside of
application code in a multi-tenant application.

The resolver can be designed however the application wants but the basic
idea is that the resolver accesses the request headers and uses that
to lookup the subdomain which then looks up the tenant shard name stored
in that table. The tenant table is the "router" for the entire
application and an example resolver looks like this:

config.active_record.shard_resolver = ->(request) {
  subdomain = request.subdomain
  tenant = Tenant.find_by_subdomain!(subdomain)
  tenant.shard
}

The Tenant table in this example would have subdomain and shard
attributes that are inserted into the database. These are used to route
to the shard in connected_to. Ie if we had a Tenant with the
subdomain github and the shard name github_shard we'd lookup the
connection with ActiveRecord::Base.connected_to(shard: :github_shard) {} and all queries within that block (request) would be scoped to
the github shard.

Co-authored-by: John Crepezzi [email protected]

cc/ @seejohnrun @mtodd


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK