Jack
Jack

Reputation: 2344

Rails multi-shard: how to have a job hit a specific shard

I'm using the Rails 6.1 feature of horizontal sharding, and it works great.

I'm using the notion of having the subdomain route to the right shard, so my multi_db.rb config looks like:

Rails.application.configure do
  config.active_record.shard_selector = { lock: true }
  config.active_record.shard_resolver = ->(request) {
# I only have 2 shards, primary (english) and one in spanish:
    return request.subdomain == "es" ? "spanish": "primary"
  }
end

If I hit some URL such as: es.mycompany.com, the code will correctly route to the "spanish" shard. If I hit mycompany.com, it'll just go to the primary.

But now I have a job that wants to run in a particular shard. As far as I can tell the above code doesn't get called when a job is run, and it makes sense given the "request" arg; it looks like it's only invoked per request to some controller.

But with jobs, there is no controller involved, so how does one "hook in" shard selection for a job?

Upvotes: 0

Views: 215

Answers (1)

Jack
Jack

Reputation: 2344

This turned out to be fairly straightforward:

def perform(shard)
  ActiveRecord::Base.connected_to(shard: shard) do
    # Job code
  end
end

This assumes you know the shard when you kick off the job (which is my case).

Upvotes: 0

Related Questions