ruby 42 lines · 1 tab

Background job retry strategies

Alex Kumar Jan 2026
1 tab
class ProcessPaymentWorker
  include Sidekiq::Worker

  sidekiq_options queue: :critical, retry: 10

  sidekiq_retry_in do |count, exception|
    case exception
    when PaymentGatewayTimeoutError
      # Exponential backoff for transient errors
      (count ** 4) + 15
    when PaymentValidationError
      # Fast fail for validation errors
      :kill
    else
      # Default: exponential backoff
      (count ** 2) + 15
    end
  end

  def perform(payment_id)
    payment = Payment.find(payment_id)

    # Idempotency check
    return if payment.processed?

    gateway = PaymentGateway.new
    result = gateway.process(payment)

    payment.update!(
      status: 'processed',
      processed_at: Time.current,
      gateway_transaction_id: result.transaction_id
    )
  rescue PaymentGatewayTimeoutError => e
    Rails.logger.warn("Payment gateway timeout for payment #{payment_id}, will retry")
    raise e
  rescue StandardError => e
    Rails.logger.error("Payment processing failed for #{payment_id}: #{e.message}")
    payment.update(status: 'failed', error_message: e.message)
    raise e
  end
end
1 file · ruby Explain with highlit

Not all background job failures should be retried the same way. Transient failures like network timeouts benefit from exponential backoff, but bugs in code or invalid data should fail immediately after a few attempts. Sidekiq provides retry configuration per worker class, and I customize it based on the job's characteristics. For critical jobs like payment processing, I set high retry counts and notify engineers when retries are exhausted via exception tracking. For best-effort jobs like sending analytics events, I might disable retries entirely. The sidekiq_retry_in hook allows dynamic backoff calculations. I also implement idempotency checks so retries don't duplicate side effects if the job partially succeeded before failing.


Related snips

ruby
class CommentsController < ApplicationController
  before_action :set_post

  def create
    @comment = @post.comments.build(comment_params)

System test: asserting Turbo Stream responses

rails hotwire turbo
by codesnips 4 tabs
ruby
class Post < ApplicationRecord
  belongs_to :author, class_name: 'User'
  has_many :comments, dependent: :destroy

  scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
  scope :draft, -> { where(published_at: nil) }

ActiveRecord scopes for reusable query logic

rails activerecord patterns
by Alex Kumar 1 tab
ruby
module Api
  module V1
    class UsersController < BaseController
      def show
        user = User.includes(:profile).find(params[:id])

ETags for conditional requests and caching

rails caching http-caching
by Alex Kumar 1 tab
ruby
class PostsController < ApplicationController
  def index
    @posts = Post.includes(:author)
                 .order(created_at: :desc)
                 .page(params[:page])
                 .per(10)

Turbo Frames: infinite scroll with lazy-loading frame

rails turbo hotwire
by codesnips 4 tabs
ruby
require "csv"

class PeopleCsvStream
  include Enumerable

  HEADERS = %w[id full_name email signed_up_at plan].freeze

Resilient CSV Export as a Streamed Response

rails performance streaming
by codesnips 3 tabs
erb
<form data-controller="query-sync" data-action="change->query-sync#apply">
  <select name="status" class="rounded border p-2">
    <option value="">Any</option>
    <option value="open">Open</option>
    <option value="closed">Closed</option>
  </select>

Filter UI that syncs query params via Stimulus (no front-end router)

rails hotwire stimulus
by Henry Kim 2 tabs

Share this code

Here's the card — post it anywhere.

Background job retry strategies — share card
Link copied