How does Rails know when to respond with 304 status?
Asked Answered
H

2

11

Given I have rails controller which accesses DB to retrieve data and render JSON response using serializer, what conditions must be met to make rails respond with 304?

If it has to compare previous response to currently retrieved, what kind of comparison is it?

Halfpenny answered 24/3, 2017 at 13:26 Comment(1)
Clarifying the question. I am interested in understanding how rails determines that data (body) to be rendered didnt change since last request?Halfpenny
G
5

The magic happens in Rack::ETag and Rack::ConditionalGet. (Mine are located at $GEM_HOME/rack-1.5.5/lib/rack/conditionalget.rb and $GEM_HOME/rack-1.5.5/lib/rack/etag.rb.)

These are middlewares.

Rack::ETag makes a digest out of the body (the very same body which gets returned by the rack function @app.call) and sets the response ETag header to this value. For Rails 4.0, at least, it's an MD5 hex digest.

Rack::ConditionalGet compares the request's If-None-Match header against the response's ETag header. If they match, then it returns a 304.

Gifferd answered 7/10, 2020 at 23:5 Comment(0)
T
-1

Server look for Cache-Control, Content-Location, Date, ETag, Expires, and Vary http header values in previous and current request from same requester.

If everything is same it return 304 response otherwise change content and return 200.

You can look https://httpstatuses.com/304 for more information.

Tallbott answered 24/3, 2017 at 14:23 Comment(2)
The question I still have is how does Rails know that JSON data to respond with didnt change since last request? Especially if I serialize data sensitive to current time.Halfpenny
Rails server look into request object and compare with previous object. Especially cache control. If you set cache false in your request it will return refreshed data each time. More find here about refreshed data #5502502Tallbott

© 2022 - 2024 — McMap. All rights reserved.