Ruby on Rails API Integration

Reliable Third-Party API Integrations in Rails: Handling Retries, Webhooks and Failures

Sidekiq’s documentation says it plainly: Sidekiq will execute your job at least once, not exactly once. Every Ruby on Rails API integration that runs through a background queue inherits that rule, and most integration bugs are what happens when the code assumes the opposite.

This guide follows one invented scenario from the first API call to the first outage, and shows where each decision about retries, duplicates and webhooks comes from. The framework details refer to the Rails 8.1 documentation.

The scenario: a subscription product with a payment provider and a courier

This is a made-up example, used for illustration only. A SaaS company bills customers through a payment provider and ships hardware kits through a courier’s API. A customer upgrades their plan. The app has to charge the card, mark the subscription as active and book a shipment.

The first version makes all three calls inside the controller action. It works for months. Then the courier’s API starts answering in twelve seconds instead of one, the web workers fill up waiting, and the whole product slows down because of a supplier’s problem.

Outbound calls belong in a job, with their own timeouts

A request that waits on someone else’s server is borrowing that server’s reliability. Move the call into a background job so the user gets a response straight away and the slow dependency can only hold up a queue, not the site. Set explicit open and read timeouts in whichever HTTP client you use, so a stalled connection fails in seconds rather than waiting on the default.

One caution on timing. If the job is enqueued inside a database transaction, it can start before the transaction commits and look for a record that isn’t there yet. Rails 8.1 has enqueue_after_transaction_commit, which defers enqueuing until the surrounding transaction has committed.

Retry only the failures that time can fix

Active Job doesn’t retry on its own. The Active Job guide says retries must be configured explicitly with retry_on, and a job that raises without it counts as failed. The API documentation gives the defaults: a 3 second wait and 5 attempts, where the count includes the original run. The polynomially_longer option stretches the gaps to roughly 3, 18 and 83 seconds, and jitter adds a random spread of 15 percent by default.

A courier timeout deserves a retry. A 422 saying the postcode is invalid doesn’t, because the thousandth attempt will fail the same way as the first. Retry network errors, timeouts and 5xx responses. Discard, or route to a person, anything the provider rejected on its merits. Here is the shape in code, written for Rails 8.1 and not executed against a live provider:

class BookShipmentJob < ApplicationJob
  retry_on Net::OpenTimeout, Net::ReadTimeout,
          wait: :polynomially_longer, attempts: 6, report: true
  discard_on ActiveJob::DeserializationError

  def perform(shipment_id)
    # call the courier, store its reference
  end
end

The report option sends each failure to Rails.error before the retry, which gives your error tracker a record while the job is still trying. When attempts run out, the documentation says the exception bubbles up to the underlying queue system unless you pass a block to handle it. If your queue is Sidekiq, remember that it has its own retry policy: 25 retries over roughly 20 days by default, per the Sidekiq error handling page. Check which layer is retrying, because running both can turn one failed booking into a long tail of surprise attempts.

A retry that creates a second charge is worse than the outage

Back in the scenario, the payment call times out. Did the provider charge the card or not? The job can’t know, and retrying blindly may bill the customer twice.

The fix is an idempotency key. For Stripe, you send an Idempotency-Key header of up to 255 characters, and a retry with the same key returns the saved result instead of repeating the operation. Generate the key once, store it on your own record before the first attempt, and reuse it on every retry. A new random key per attempt defeats the purpose.

Not every provider offers this. When one doesn’t, store the provider’s reference as soon as you get it, and make the job check for that reference before it calls again. The courier job above should start by asking: do I already hold a tracking number for this shipment?

Webhooks arrive late, twice and out of order

The payment provider confirms the charge through a webhook, and this is where assumptions break. Stripe’s webhook documentation states that endpoints might receive the same event more than once, that delivery order isn’t guaranteed, and that failed deliveries are retried for up to three days with exponential backoff in live mode.

That shapes the endpoint. Verify the signature against the raw request body, because any change to the body makes verification fail, and reject events whose timestamp falls outside the tolerance window. Return a 2xx status quickly, then hand the real work to a job. Record each event ID in a table with a unique index, and skip any event you’ve already processed. Don’t use the event’s created time to decide which event is newer, since the documentation warns against it. Fetch the current object from the API when order matters.

Rails needs one more step: a webhook endpoint can’t carry a CSRF token, so it must be excluded from forgery protection. Stripe’s own Rails example does this with protect_from_forgery except: :webhook, and the signature check takes over the job of proving the request is genuine.

Someone has to find out when retries run out

Return to the courier outage. Six attempts fail, the job gives up, and the customer’s kit is never booked. Without an alert, the first sign is a support email a week later.

Decide in advance what happens at the end of the retry path. Sidekiq moves exhausted jobs to a Dead set, with hooks such as sidekiq_retries_exhausted for custom handling. In Active Job, the block form of retry_on lets you mark the shipment as needing attention and notify a person. Either way, the record should show a clear state, such as “courier booking failed”, so a support agent or an admin screen can retry it by hand once the provider recovers.

Also decide what the customer sees while the supplier is down. “Your kit is on its way, we’ll send tracking shortly” is accurate, and it keeps the upgrade itself from failing for a reason the customer can’t control.

What the finished design looks like

Put together, the upgrade now commits the subscription change and returns immediately. A payment job uses a stored idempotency key. A shipment job checks for an existing tracking number, retries timeouts and server errors with growing gaps, and reports each failure. A webhook endpoint verifies, records the event ID, returns 200 and queues the processing. An alert fires when a shipment job runs out of attempts, and the record shows its state.

None of this needs a new gem or a service rewrite. It needs each integration to answer the same five questions: what happens on a timeout, a duplicate, an out-of-order event, an exhausted retry and a rejected request.

Where an outside review helps

Integrations tend to be written one at a time, by different people, and nobody owns the pattern across them. If your application has grown that way, a review of the retry, idempotency and alerting setup is a contained piece of work. RailsCarma offers Ruby on Rails consulting, lists API-driven development among its services, and provides application support and maintenance for keeping integrations monitored after the fixes ship.

Decide the failure path before the success path

Any developer can make an API call work on a good day. The integration is finished when you can say what happens to the customer, the record and the on-call engineer on a bad one.

Speak with RailsCarma’s team to review how your Rails application handles failed API calls and duplicate webhooks.

Related Posts

About Post Author

Leave a Comment

Your email address will not be published. Required fields are marked *


en_USEnglish