Rails Shopify app: Background jobs losing API connection when processing webhooks

I’m working on a Shopify application built with Rails and running into an issue when trying to use background job processing with webhook handlers.

Currently my webhook controller has a filter that establishes the Shopify connection:

def order_created
  payload = JSON.parse(request.body.read)
  order_id = payload["id"]
  
  Order.create_from_shopify(@store, order_id)
  
  render json: { status: 'ok' }
end

private

def establish_connection
  store_domain = request.headers['HTTP_X_SHOPIFY_SHOP_DOMAIN']
  store_url = "https://#{store_domain}"
  
  @store = Store.find_by_domain(store_url)
  
  api_session = ShopifyAPI::Session.new(@store.domain, @store.token)
  api_session.valid?
  ShopifyAPI::Base.activate_session(api_session)
end

My Order model can access the API connection like this:

def self.create_from_shopify(store, order_id)
  shopify_order = ShopifyAPI::Order.find(order_id)
  
  new_order = Order.new
  new_order.shopify_id = shopify_order.id
  new_order.total = shopify_order.total_price
  new_order.store = store
  new_order.save
end

The issue happens when I try to move this to a background job using Order.delay.create_from_shopify(@store, order_id). The delayed job loses the API connection and fails.

What’s the recommended approach for handling this scenario?

Background jobs run in completely isolated environments, so they can’t access instance variables or session state from your web requests. I hit this exact issue building a Shopify inventory sync app last year. You need to make your delayed job self-contained. Don’t pass the @store instance variable - instead, pass the store ID and rebuild the API session inside the background job. Create a wrapper method that handles the connection setup internally, like Order.delay.create_from_shopify_with_auth(store.id, order_id). This keeps your background jobs stateless, and they’ll connect to Shopify reliably no matter when they run.

totally feel u on that! i had the same probs. just pass the store obj into the job and make sure to establish session again in ur bg job with store.domain and store.token for it to work. good luck!

Your background jobs are running in separate processes, so they don’t have access to the API session from your controller. I hit this same problem about six months ago on a Rails Shopify app. Here’s what fixed it for me: let your background job handle its own API connection. Don’t rely on the controller’s session - modify your Order model method to take the store object and set up the connection inside the job. You’ll need to call ShopifyAPI::Base.activate_session again in the delayed method using the store’s domain and token. That way each job gets its own valid API session no matter when it runs.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.