Skip to content

Instantly share code, notes, and snippets.

@ericchen
Created April 19, 2024 06:06
Show Gist options
  • Save ericchen/d334e34012316de8bc572f0e5327ee07 to your computer and use it in GitHub Desktop.
Save ericchen/d334e34012316de8bc572f0e5327ee07 to your computer and use it in GitHub Desktop.
pg advisory locks
class LockManager
def self.with_transaction_lock(lock_name)
lock_id = Zlib.crc32(lock_name.to_s)
ActiveRecord::Base.transaction do
ActiveRecord::Base.connection.execute("SELECT pg_advisory_xact_lock(#{lock_id})")
yield
end
end
def self.with_session_lock(lock_name)
lock_id = Zlib.crc32(lock_name.to_s)
begin
ActiveRecord::Base.connection.execute("SELECT pg_advisory_lock(#{lock_id})")
yield
ensure
ActiveRecord::Base.connection.execute("SELECT pg_advisory_unlock(#{lock_id})")
end
end
end
LockManager.with_transaction_lock("subscription_usage_#{user_id}") do
user = User.find(user_id)
new_usage = user.current_subscription_usage
user.update_attributes!(subscription_usage: new_usage)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment