
Receiving Webhooks in Rails Without Losing Any
Payment providers send the same webhook more than once, everybody warns about it, so we wanted to see our endpoint losing this fight, Rails 8.1, Postgres, and 20 threads which deliver the same event in the same moment.
The first version is the one which we saw many times, if not exists then create. We ran five rounds. First round we got 1 row and almost started to be happy, but it was only threads warming up, because the next four rounds gave 20 rows from 20 deliveries, every single one passed the check before somebody saved. Imagine 20 receipts to one customer.
Then unique index on provider with external id, and create_or_find_by! instead. Five rounds again, every time 1 row, only one thread got previously_new_record as true, zero errors in the others, they just received the existing row. This is the whole trick and the database does it, not our if. Funny, the ids went till 162 and rows only 86, lost inserts eat numbers.
add_index :webhook_events, [:provider, :external_id], unique: true
Signature was our second test. We took a body with a price 10.50 and an escaped letter, calculated HMAC, then parsed the JSON and dumped it back like some code does before checking. The new text had 10.5 and the real letter and no spaces, and the signature did not match anymore, although for a human it is the same JSON, therefore we always check request.raw_post, before anything touches it.
Under the post is our version, check signature, save, answer 200 quick, heavy things in a job with lock, and one more small job which is sweeping, because imagine the process dies right between insert and perform_later, the event is lying there, provider sends again, we see the row and skip, nobody will ever process him without the sweeper.
class WebhooksController < ActionController::API
def create
body = request.raw_post
return head :unauthorized unless valid_signature?(body)
payload = JSON.parse(body)
event = WebhookEvent.create_or_find_by!(
provider: "acme", external_id: payload.fetch("id")
) do |e|
e.event_type = payload.fetch("type")
e.payload = payload
end
ProcessWebhookJob.perform_later(event.id) if event.previously_new_record?
head :ok
rescue JSON::ParserError, KeyError
head :bad_request
end
private
def valid_signature?(body)
secret = Rails.application.credentials.dig(:acme, :webhook_secret)
expected = OpenSSL::HMAC.hexdigest("SHA256", secret, body)
given = request.headers["X-Acme-Signature"].to_s
ActiveSupport::SecurityUtils.secure_compare(expected, given)
end
end
class ProcessWebhookJob < ApplicationJob
retry_on StandardError, wait: :polynomially_longer, attempts: 8
def perform(event_id)
event = WebhookEvent.find(event_id)
event.with_lock do
return if event.processed_at?
Webhooks::Apply.call(event)
event.update!(processed_at: Time.current)
end
end
end
class SweepWebhooksJob < ApplicationJob
def perform
WebhookEvent.where(processed_at: nil, created_at: ..10.minutes.ago)
.find_each { |event| ProcessWebhookJob.perform_later(event.id) }
end
end
See also: recurring jobs and JSONB.