Skip to content

Commit

Permalink
Round petition cache key
Browse files Browse the repository at this point in the history
When the site it busy the cache key for the petition is being constantly
expired due to rapid changes to updated_at. By rounding the timestamp
down to the nearest 5 seconds it means that the cache won't be invalidated
at a rate more than 12 times per minute.
  • Loading branch information
pixeltrix committed Jun 28, 2016
1 parent b744768 commit c9b481c
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
18 changes: 18 additions & 0 deletions app/models/petition.rb
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,24 @@ def set_petition_on_creator_signature
creator_signature.update_attribute(:petition_id, id)
end

def cache_key(*timestamp_names)
case
when new_record?
"petitions/new"
when timestamp_names.any?
timestamp = max_updated_column_timestamp(timestamp_names)
timestamp = timestamp.change(sec: (timestamp.sec.div(5) * 5))
timestamp = timestamp.utc.to_s(cache_timestamp_format)
"petitions/#{id}-#{timestamp}"
when timestamp = max_updated_column_timestamp
timestamp = timestamp.change(sec: (timestamp.sec.div(5) * 5))
timestamp = timestamp.utc.to_s(cache_timestamp_format)
"petitions/#{id}-#{timestamp}"
else
"petitions/#{id}"
end
end

def update_last_petition_created_at
Site.touch(:last_petition_created_at)
end
Expand Down
17 changes: 17 additions & 0 deletions spec/models/petition_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1727,5 +1727,22 @@
expect(petition.signatures_to_email_for('government_response')).to match_array [creator_signature, other_signature]
end
end

describe "#cache_key" do
let(:petition) { FactoryGirl.create(:petition, last_signed_at: "2016-06-28 00:00:17 UTC", open_at: "2016-06-28 00:00:07 UTC") }
let(:now) { "2016-06-29 00:00:07 UTC".in_time_zone }

around do |example|
travel_to(now) { example.run }
end

it "rounds down to the nearest 5 seconds" do
expect(petition.cache_key).to eq("petitions/#{petition.id}-20160629000005000000000")
end

it "can use other columns" do
expect(petition.cache_key(:open_at, :last_signed_at)).to eq("petitions/#{petition.id}-20160628000015000000000")
end
end
end
end

0 comments on commit c9b481c

Please sign in to comment.