Skip to content

Add Net HTTP persistent adapter compatibility - #509

Open
madwork wants to merge 3 commits into
alexrudall:mainfrom
reedsy:improvements/connection-reuse
Open

Add Net HTTP persistent adapter compatibility#509
madwork wants to merge 3 commits into
alexrudall:mainfrom
reedsy:improvements/connection-reuse

Conversation

@madwork

@madwork madwork commented Aug 7, 2024

Copy link
Copy Markdown

Explanation

The idea is to allow connection reuse with net http persistent adapter. It should also improve memory footprint by lowering the number of Faraday::Connection objects and quoting net http persistent project description:

Using persistent HTTP connections can dramatically increase the speed of HTTP. Creating a new HTTP connection for every request involves an extra TCP round-trip and causes TCP congestion avoidance negotiation to start over.

Benchmark

The graph below display usage of the gem with the latest version (before) versus this branch (after) for the exact same job. It illustrates that it drastically reduces the number of open connections and port usage.

openai

Usage example

gem "faraday", "~> 2.7", ">= 2.7.11"
gem "faraday-net_http_persistent", "~> 2.1"
openai_client ||= OpenAI::Client.new do |faraday|
  faraday.adapter :net_http_persistent, pool_size: 5 do |http|
    http.idle_timeout = 30
  end
end
thread = openai_client.threads.create
openai_client.messages.create(
  thread_id: thread["id"],
  parameters: {
    role: "user",
    content: "content"
  }
)
run = openai_client.runs.create(
  thread_id: thread["id"],
  parameters: {
    assistant_id: "assistant_id"
  }
)
loop do
  response = openai_client.runs.retrieve(
    id: run["id"],
    thread_id: thread["id"]
  )

  # Begin polling
  case response["status"]
  when "queued", "in_progress"
    sleep 1 # Wait 1s and poll again
  when "completed"
    # TODO
  else
    raise
  end
end

All Submissions:

  • Have you followed the guidelines in our Contributing document?
  • Have you checked to ensure there aren't other open Pull Requests for the same update/change?
  • Have you added an explanation of what your changes do and why you'd like us to include them?

@madwork
madwork force-pushed the improvements/connection-reuse branch from a32cee1 to 9f065c2 Compare August 7, 2024 16:45
madwork added 2 commits August 7, 2024 18:53
The current implementation is breaking any attempt of connection pool usage.
@madwork
madwork force-pushed the improvements/connection-reuse branch from 9f065c2 to 475b25e Compare August 7, 2024 16:54

@alexrudall alexrudall left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this @madwork -- apologies for the delay in review. This is an important PR and I appreciate your work on this. The code is readable and carefully written which I really appreciate.

Questions

  • Does this work universally for all endpoints?
  • Does this work with streaming? I believe users use streaming much more than they poll.
  • What affects the optimal pool size?
  • Is there any reason this can't be the default? Happy to make a breaking change if it provides an significant improvement to all users.

Requests

  • Could you add the given example to the README?
  • I believe changing from conn to connection is a breaking change - happy to do this in a separate PR but if it's possible to make this PR not breaking that would be great.
  • Could you share instructions for generating that graph? That will really help me & others in future testing.

atesgoral added a commit to Shopify/ruby-openai that referenced this pull request Aug 25, 2026
* [x] Followed the guidelines in the [Contributing
document](../blob/main/CONTRIBUTING.md)
* [x] There is no other open pull request in this fork for the same
change

## Summary

- cache one normal and one multipart Faraday connection per client
- serialize first construction and fully build the middleware/adapter
stack before concurrent requests can race Faraday's lazy builder
- give duplicated `beta` and `admin` clients fresh connections and
endpoint delegates
- keep cached connection internals out of `Client#inspect`

## Reason for Change

`ShopifAi::Client` is cached by Agent Server, but `ShopifAi::HTTP#conn`
currently creates a new Faraday connection and middleware stack for
every API call. That means a configured persistent adapter cannot retain
its socket pool across requests.

This is the transport-policy-neutral foundation for
[shop/issues-sidekick#6707](shop/issues-sidekick#6707).
It does not change the default Faraday adapter or add a dependency; a
separate Agent Server PR can opt selected AI Proxy clients into
`net_http_persistent` with bounded pool policy and rollout controls.

The base connection-reuse pattern is adapted from
[alexrudall#636](alexrudall#636),
with concurrency, duplicated-helper, and inspect-safety hardening.
[alexrudall#509](alexrudall#509)
provides the persistent-adapter precedent.

## Compatibility

- the default `net_http` request behavior is unchanged apart from
avoiding repeated connection-object and middleware-stack construction
- configured persistent adapters can now retain their pools on a cached
client
- `beta` and `admin` duplicates remain isolated and cannot retain
helpers bound to the original credentials
- `Usage`'s per-call admin-client lifetime is unchanged; Agent Server
does not use that API

## Validation

- `BUNDLE_FROZEN=true bundle _2.4.5_ exec rake` — 166 examples, 0
failures; 56 files, 0 RuboCop offenses
- Faraday 1.10.4 compatibility smoke — normal/multipart reuse, eager
stack construction, and duplicate isolation passed
- live `proxy.shopify.ai/ping` proof with `net_http_persistent` — 176.4
ms cold, then 22.0–31.9 ms warm across four repeated calls on the same
cached connection

---
*PR authored by Qlaw*

Co-authored-by: Chris Hasiński <krzysztof.hasinski@gmail.com>
Co-authored-by: Qlaw <noreply@qlaw.quick.shopify.io>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants