Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveStorage : Why not using service_url instead of blob/variant/preview url (302 redirect)?

In Rails 5.2, Active Storage gives us the ability to generate permanent urls that are redirecting to an asset, via unique signed urls at each call.

html: <img src='/rails/active_storage/blobs/ey...' />

server:

Started GET "/rails/active_storage/blobs/eyJfcmFpbH...
302 Redirected to https://bucket.amazon/image.jpg?X-Amz-Algorithm=AWS4-HMA...

I am wondering about the number of HTTP requests Active Storage is adding to the monolith, one blob_url in the web page = one additional request to the monolith, in order to get the final asset url via 302 redirect. So One page with 20 images => 20 additional requests. (but they are pretty fast)

So my question is : why using this system instead of using the final URL directly (.service_url) :

<img src='https://bucket.amazon/image.jpg?X-Amz-Algo...'> ?

I am thinking of these arguments : (but is there any other?)

  • blob_url can be cached server-side because it is permanent (example : fragment caching)
  • blob_url can be protected by authentication, it means the unique url could be shared but someone would need authentication in order to see the asset for example (by modifying the rails blob controller)
  • Maybe a third one? Better Caching browser-side? Is the browser able to cache the image data with the permanent url? even if the amazon url have a 5-minute expiration?
like image 456
Nicolas Maloeuvre Avatar asked Sep 06 '18 12:09

Nicolas Maloeuvre


1 Answers

Active Storage adds a layer of abstraction to files by default

The out-of-the-box behavior of Active Storage is to generate URLs which point back to the Rails application. When accessed, these URLs redirect to the actual service endpoint for the file.

This does increase the number of requests to the Rails app server since all file access needs to go through there.

Indirection has advantages

Having the Rails app in between the user and the files provides several benefits (some of which are mentioned in the OP):

  • Files can be protected by authentication
  • Caching
  • Mirroring

From the Active Storage guide:

This indirection decouples the public URL from the actual one, and allows, for example, mirroring attachments in different services for high-availability.

Debate over direct access to files

For more discussion about the pros/cons of abstracting away file access through the Active Storage Service API, check out this thread:

https://github.com/rails/rails/issues/31419

like image 137
Carlos Ramirez III Avatar answered Oct 12 '22 21:10

Carlos Ramirez III