Add this line to your Gemfile:
gem 'idempotency'
Idempotency.configure do |config|
# Required configurations
config.redis_pool = ConnectionPool.new(size: 5) { Redis.new }
config.logger = Logger.new # Use Rails.logger or Hanami.logger based on your framework
# Optional configurations
# Handles concurrent request locks. If a request with the same idempotency key is made before the first one finishes,
# it will be blocked with a 409 status until the lock expires. Ensure this value is greater than the maximum response time.
config.default_lock_expiry = 60
# Match this config to your application's error format
config.response_body.concurrent_error = {
errors: [{ message: 'Concurrent requests occurred' }]
}
config.idempotent_methods = %w[POST PUT PATCH]
config.idempotent_statuses = (200..299).to_a
end
Add this to your controller:
require 'idempotency/rails'
class UserController < ApplicationController
include Idempotency::Rails
around_action :use_cache, except: %i[create]
# Configure lock_duration for specific actions
around_action :idempotency_cache, only: %i[update]
private
def idempotency_cache
use_cache(lock_duration: 360) do # Lock for 6 minutes
yield
end
end
end
Add this to your controller:
require 'idempotency/hanami'
class Api::Controllers::Users::Create
include Hanami::Action
include Idempotency::Hanami
around do |params, block|
use_cache(request_ids, lock_duration: 360) do
block.call
end
end
end
For custom implementations or if not using Rails or Hanami:
status, headers, body = Idempotency.use_cache(request, request_identifiers, lock_duration: 60) do
yield
end
# Render your response