influitive / apartment

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

Making a request to an ActiveStorage resource fails occasionally #666

Open febincloudyuga opened 3 years ago

febincloudyuga commented 3 years ago

Use-case

We're using Apartment alongside ActiveStorage. In our S3 server, we have created a bucket for every tenant in our application. Since ActiveStorage can hold only one bucket globally, we're switching the ActiveStorage bucket for every request.

The problem

When a request from one tenant is being served and a new request from another tenant comes in, the bucket held by ActiveStorage gets switched to that of the new tenant. Now if the first tenant request is trying to access a resource in ActiveStorage, it results in a failure since request is being made with incorrect bucket name

Current workaround

A fallback mechanism to check if the generated ActiveStorage URL is valid. If it's invalid, change the bucket name held by ActiveStorage to that of the current tenant and make a new request

Pictorial representation attached.

Apartment

Kindly let us know if there's a better way of solving this problem