influitive / apartment

Database multi-tenancy for Rack (and Rails) applications
2.67k stars 461 forks source link

Tenant creation w/ background job #552

Closed pkallberg closed 6 years ago

pkallberg commented 6 years ago

This is more of a question than an issue, hope that's okay. We're using the Apartment gem and creating a tenant for each sign up we get on our site.

The issue we have is that the tenant is created in the same thread as the sign up, meaning that if the user quits within that process, their tenant isn't created properly. This leads to ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: and similar issues which have become a problem.

In order to avoid this, I'm looking into running the tenant creation with a background job. Do you guys have any best practices/tips around doing this? Current approach would likely be to send the job to Sidekiq and poll for completion, at which point redirect the user to their subdomain.

Any pointers would be greatly appreciated!

mikecmpbll commented 6 years ago

sounds perfectly reasonable. sidekiq is commonly used in conjunction with Apartment. might be a reasonable approach to add a status column somewhere and update it from your sidekiq job once finished. you can poll for that.

obviously not an issue so i'm closing but don't let that discourage the discussion.

pkallberg commented 6 years ago

Thanks @mikecmpbll, I appreciate your input! In case anyone else stumbles on this, I ended up using sidekiq-status to check for completion of tenant creation job before redirecting the user to their subdomain:

job_id = CreateTenant.perform_async(subdomain)

until Sidekiq::Status::complete?(job_id) do
  ...
end

redirect_to ...