How to receive webhooks in Ruby minimal receiver → production-ready processing
Start with a minimal “native” receiver, but don’t stop there.
In production, reliable webhook handling means verification, retries, idempotency, and backpressure — which is where Hooque simplifies everything.
Building for a specific provider? Browse provider webhook APIs.
TL;DR
- Treat “receive webhooks in Ruby” as an ops problem, not just a route handler.
- Verify the request before parsing/side effects (use a verifySignature(...) stub, then implement provider verification).
- Return 2xx quickly; move work to a worker/queue to avoid timeouts and retries.
- Assume retries and design idempotency (dedupe by event id + unique constraints).
- Log + store raw payloads for replayable debugging.
- If you need one workflow across many providers, centralize ingest + standardize consumption.
Deep dives: security, retries, queue migration.
Anti-patterns
- Doing business logic inline in the Ruby request handler.
- Parsing/transforming the body before verification (breaks signing inputs).
- Returning 2xx before authenticity is proven.
- Skipping idempotency (retries become double side effects).
If you’re triaging a live incident, use the debugging playbook .
Table of contents
Framework shortcuts
If you’re already using a framework, jump straight to the minimal framework receiver, then reuse the same production guidance and Hooque consumer loops.
Why it's hard in production
A route handler is the easy part. Supporting multiple senders means multiple security models, spikes, and retry semantics.
Verify authenticity + stop replays
Use a verifySignature(...) stub here, then implement real verification + replay defense for each provider.
Assume retries (duplicates are optional)
Treat every delivery as at-least-once and make side effects idempotent (DB constraints, dedupe keys).
Don’t do work in the request path
Ack fast, process async. Otherwise timeouts, deploys, and spikes turn into missed webhooks.
Debug with real payloads
Save the exact body + headers so you can replay deterministically after a fix.
Add monitoring + alerts early
Track delivered vs rejected, processing latency, queue depth, and error rates.
Iterate locally without losing events
Tunnels help, but durable capture + replay removes the “my laptop was asleep” problem.
Minimal standard-library receiver (Ruby)
This is a minimal starting point. Keep verifySignature(...) as a stub here, then implement provider-specific verification and replay defense in the
security guide
.
# Ruby 3+ (WEBrick)
# Run: ruby server.rb
require "webrick"
def verify_signature(headers, body)
# don't compromise on security
# TODO: implement provider-specific signature verification
end
def process_data(body)
# TODO: your business logic (DB writes, external API calls, etc.)
body
end
server = WEBrick::HTTPServer.new(Port: 3000)
server.mount_proc "/webhooks" do |req, res|
if req.request_method != "POST"
res.status = 405
next
end
body = req.body || ""
verify_signature(req.header, body)
# What happens if it fails or times out?
# Most providers retry -> duplicates unless you designed idempotency.
process_data(body)
# IMPORTANT: ack fast; do not do real work inline.
res.status = 200
res["Content-Type"] = "text/plain"
res.body = "ok"
puts "received webhook bytes=#{body.bytesize}"
end
trap("INT") { server.shutdown }
server.start Hooque turns any webhook into a reliable queue.
Non-obvious scenario: you can’t expose a port
In real deployments, the hardest part is often “where does this endpoint run?” (NAT, corporate networks, locked-down environments, short-lived preview deployments). Hooque decouples inbound receiving from processing so your Ruby app doesn’t need to be the public receiver.
The easy path: receive with Hooque + consume forever
Hooque turns inbound webhooks into a durable queue. Your code becomes a run-forever worker that pulls or streams events and acks/nacks/rejects explicitly.
- No need to run a public webhook endpoint in every environment (especially for local dev).
- Durable capture + replay/inspection so “we missed the webhook” becomes debuggable.
- Explicit Ack / Nack / Reject lifecycle so retries are under your control.
- Backpressure and spike absorption: buffer now, process at your pace.
- One consumption pattern across many senders (even if their security/retry rules differ).
Flow
- Provider delivers → Hooque ingest endpoint
- Hooque persists payload immediately
- Your worker pulls (REST) or streams (SSE)
- Your worker ack/nack/rejects explicitly
Next steps
- Security: verification + replay defense
- Reliability: retries + idempotency
- Ops: metrics + alerting
Hooque REST polling loop (runs forever)
Polling is a good default when you want a simple worker loop. It also works in environments where long-lived connections are unreliable.
# Ruby 3+ (Net::HTTP)
# Runs forever: poll /next, ack/nack/reject explicitly.
require "json"
require "net/http"
require "uri"
NEXT_URL = ENV.fetch("HOOQUE_QUEUE_NEXT_URL", "https://app.hooque.io/queues/<consumerId>/next")
TOKEN = ENV.fetch("HOOQUE_TOKEN", "hq_tok_replace_me")
def main
uri = URI(NEXT_URL)
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") do |http|
loop do
msg = get_next_message(http, uri, TOKEN)
unless msg
sleep 1
next
end
begin
process_data(msg[:payload], msg[:meta])
ack(msg, TOKEN)
rescue => e
nack(msg, TOKEN, e)
end
end
end
end
def get_next_message(http, uri, token)
begin
req = Net::HTTP::Get.new(uri)
req["Authorization"] = "Bearer #{token}"
resp = http.request(req)
if resp.code.to_i == 204
return nil
end
if resp.code.to_i >= 400
warn "next() failed: #{resp.code} #{resp.body}"
sleep 2
return nil
end
meta = JSON.parse(resp["X-Hooque-Meta"] || "{}")
{ payload: resp.body, meta: meta }
rescue => net_e
warn "Worker connection err: #{net_e.message}"
sleep 2
nil
end
end
def process_data(payload, meta)
# Example real-life task: run a script on webhook events.
puts "event: #{meta["messageId"] || meta["deliveryId"]}"
end
def ack(msg, token)
post_url(msg[:meta]["ackUrl"], token, nil)
end
def nack(msg, token, err)
err_url = msg[:meta]["nackUrl"] || msg[:meta]["rejectUrl"]
post_url(err_url, token, { reason: err.message }) if err_url
end
def post_url(url, token, json)
return unless url
uri = URI(url)
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer #{token}"
if json
req["Content-Type"] = "application/json"
req.body = JSON.generate(json)
end
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") { |h| h.request(req) }
rescue => e
warn "Post err: #{e.message}"
end
main Hooque SSE stream consumer (runs forever)
SSE is great for low-latency processing: keep a connection open, process events as they arrive, and reconnect on disconnects.
# Ruby 3+ — SSE consumer (Net::HTTP)
# Runs forever: connect to /stream, handle "message" events, ack/nack/reject explicitly.
require "json"
require "net/http"
require "uri"
STREAM_URL = ENV.fetch("HOOQUE_QUEUE_STREAM_URL", "https://app.hooque.io/queues/<consumerId>/stream")
TOKEN = ENV.fetch("HOOQUE_TOKEN", "hq_tok_replace_me")
def main
loop do
get_message_stream do |msg|
begin
process_data(msg[:payload], msg[:meta])
ack(msg, TOKEN)
rescue => e
nack(msg, TOKEN, e)
end
end
warn "Stream dropped, reconnecting..."
sleep 2
end
end
def get_message_stream
begin
uri = URI(STREAM_URL)
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") do |http|
req = Net::HTTP::Get.new(uri)
req["Authorization"] = "Bearer #{TOKEN}"
req["Accept"] = "text/event-stream"
http.request(req) do |resp|
event = nil
data_lines = []
buffer = ""
resp.read_body do |chunk|
buffer += chunk
while index = buffer.index("\n")
line = buffer.slice!(0..index)
line = line.delete_suffix("\n").delete_suffix("\r")
next if line.start_with?(":")
if line == ""
if event == "message" && data_lines.any?
begin
raw_msg = JSON.parse(data_lines.join("\n"))
yield({ payload: raw_msg["payload"], meta: raw_msg["meta"] || {} })
rescue JSON::ParserError
end
end
event = nil
data_lines = []
next
end
event = line.split(":", 2)[1].strip if line.start_with?("event:")
data_lines << line.split(":", 2)[1].lstrip if line.start_with?("data:")
end
end
end
end
rescue => e
warn "stream error: #{e.message}"
end
end
def process_data(payload, meta)
puts "event: #{meta["messageId"] || meta["deliveryId"]}"
end
def ack(msg, token)
post_url(msg[:meta]["ackUrl"], token, nil)
end
def nack(msg, token, err)
err_url = msg[:meta]["nackUrl"] || msg[:meta]["rejectUrl"]
post_url(err_url, token, { reason: err.message }) if err_url
end
def post_url(url, token, json)
return unless url
uri = URI(url)
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer #{token}"
if json
req["Content-Type"] = "application/json"
req.body = JSON.generate(json)
end
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") { |h| h.request(req) }
rescue => e
warn "Post err: #{e.message}"
end
main FAQ
Quick answers for the questions that come up right before you ship.
What status code should I return for webhooks in Ruby?
General: Usually return a fast 2xx after validating authenticity and basic schema. Timeouts and 5xx commonly trigger retries.
How Hooque helps: Hooque acknowledges ingest immediately and persists the payload. Your worker acks/nacks/rejects explicitly after processing.
Do I need signature verification in Ruby?
General: Yes, unless the sender is fully trusted and on a private network. A public endpoint without verification is easy to forge and easy to replay.
How Hooque helps: Hooque can verify at ingest for supported providers or using generic strategies. Either way, your worker receives a normalized meta object and can stay focused on processing.
Why do I see duplicate webhook events in Ruby?
General: Retries are normal: timeouts, transient network failures, and 5xx responses all produce duplicates. Design idempotency around event ids and side-effect boundaries.
How Hooque helps: Hooque makes delivery outcomes explicit (ack/nack/reject) and provides replay/inspection so you can fix issues without guessing what was received.
How do I test webhooks locally in Ruby?
General: You can use a tunnel, but local dev still breaks on sleep, VPNs, clock skew, and signature-byte mismatches.
How Hooque helps: With Hooque you can avoid inbound locally: receive events into a durable queue and pull/stream to your laptop, then replay from the UI after changes.
Should I use REST polling or SSE streaming for webhook processing?
General: Use REST polling for simple batch workers and environments without long-lived connections. Use SSE for low-latency “process as it arrives” flows.
How Hooque helps: Hooque supports both: `GET /next` for polling and `GET /stream` for streaming. Both include meta with ready-to-call ack/nack/reject URLs.
Start processing webhooks reliably
Create a webhook endpoint, receive events, then run your worker forever using REST polling or SSE streaming — with explicit ack/nack/reject control.
No credit card required