Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Slashing API Order Latency upto 70%+ with HTTP Connection Pooling

5 min read

HTTP connection pooling keeps a small set of HTTPS connections to the broker open and reuses them, so each order skips the TCP handshake and TLS negotiation. In OpenAlgo, switching Angel One API calls from Python’s http.client to a shared httpx client cut order latency from 250-300ms to about 88-120ms, a reduction of up to 70%, even though the broker’s own API responded in about 78ms.

Key takeaways
  • Opening a new connection per request added 170-220ms: TCP handshake (14-45ms) plus TLS negotiation (50-100ms) and setup.
  • A single shared httpx.Client reuses connections, so only the first request pays the handshake cost.
  • Result: average order latency fell from 250-300ms to 88-120ms.
  • HTTP/2 in httpx needs the optional h2 package: pip install “httpx[http2]”.
  • OpenAlgo has since rolled the shared client out to all brokers, and it deliberately does not auto-retry order requests to avoid duplicate orders.

The Challenge: High Latency in Trading API Calls

In trading, every millisecond counts. Recently, we identified a significant performance bottleneck in our OpenAlgo Platform: API calls to openalgo supported broker (Angel One) were taking 250-300ms, despite the broker’s API itself responding in just ~78ms. This overhead was unacceptable for time-sensitive trading operations.

Identifying the Root Cause

After analyzing our network requests, we discovered that the culprit was our use of Python’s built-in http.client library. For each API call, our application was:

OpenAlgo Desktop: algo trading on your own computer

WINDOWS, MAC AND LINUX

OpenAlgo Desktop: algo trading on your own computer

Install, sign in, connect your broker and trade. No server to set up and no Python to install.

  • Same API and screens as OpenAlgo web
  • Strategy module, charting and scalping terminals
  • Keys stay encrypted on your machine
  1. Creating a new HTTP connection
  2. Performing a full TCP handshake (14-45ms)
  3. Completing TLS negotiation (50-100ms)
  4. Sending the request
  5. Receiving the response
  6. Closing the connection

This inefficient connection management was adding 170-220ms of unnecessary overhead to each request!

The Solution: HTTP Connection Pooling with httpx

To address this issue, we needed a library that supports connection pooling – the ability to maintain and reuse established connections. We chose httpx for several compelling reasons:

  1. Modern API: Clean, intuitive interface similar to the popular requests library
  2. Connection Pooling: Built-in support for connection reuse
  3. HTTP/2 Support: Enables multiplexing multiple requests over a single connection
  4. Resource Management: Fine-grained control over connection limits and timeouts
  5. Synchronous & Asynchronous Support: Flexibility to use either programming model

HTTP Connection Pooling Explained

What is HTTP Connection Pooling?

HTTP Connection Pooling is a technique that optimizes network performance by maintaining a pool of open, reusable HTTP connections. Instead of establishing a new connection for each HTTP request, the application reuses existing connections from the pool, significantly reducing the overhead associated with connection establishment.

How Connection Pooling Works

  1. Connection Establishment: When the first request is made, a connection is established to the target server, involving DNS resolution, TCP handshake, and TLS negotiation (for HTTPS).
  2. Connection Reuse: After the response is received, the connection is not closed but kept open and placed in a pool.
  3. Subsequent Requests: Future requests to the same server can reuse connections from the pool, bypassing the time-consuming connection establishment steps.
  4. Connection Management: The pool manages connection lifecycle, including:
    • Creating new connections when needed
    • Reusing existing connections when available
    • Validating connection health before reuse
    • Closing idle connections after a configured timeout
    • Enforcing maximum limits on concurrent connections

Implementation Details

1. Creating a Shared httpx Client

We created a central client module in utils/httpx_client.py:

import httpx

# Global httpx client for connection pooling
_httpx_client = None

def get_httpx_client():
    """Returns a global httpx client instance with connection pooling."""
    global _httpx_client
    if _httpx_client is None:
        _httpx_client = httpx.Client(
            http2=True,
            timeout=30.0,
            limits=httpx.Limits(
                max_keepalive_connections=10,
                max_connections=20,
                keepalive_expiry=60.0
            )
        )
    return _httpx_client

Note: http2=True only works when the optional HTTP/2 dependency is installed. Per the httpx HTTP/2 documentation, install it with pip install "httpx[http2]"; without it httpx raises an import error when the client is created.

2. Replacing http.client Across All API Files

We refactored all broker API functions to use our shared httpx client. For example:

Before (using http.client):

def get_api_response(endpoint, auth, method="GET", payload=''):
    AUTH_TOKEN = auth
    api_key = os.getenv('BROKER_API_KEY')
    
    conn = http.client.HTTPSConnection("apiconnect.angelbroking.com")
    headers = {
        'Authorization': f'Bearer {AUTH_TOKEN}',
        'Content-Type': 'application/json',
    }
    conn.request(method, endpoint, payload, headers)
    res = conn.getresponse()
    data = res.read()
    
    return json.loads(data.decode("utf-8"))

After (using httpx with connection pooling):

def get_api_response(endpoint, auth, method="GET", payload=''):
    AUTH_TOKEN = auth
    api_key = os.getenv('BROKER_API_KEY')
    
    client = get_httpx_client()
    
    headers = {
        'Authorization': f'Bearer {AUTH_TOKEN}',
        'Content-Type': 'application/json',
    }
    
    url = f"https://apiconnect.angelbroking.com{endpoint}"
   
    if method == "GET":
        response = client.get(url, headers=headers)
    elif method == "POST":
        response = client.post(url, headers=headers, content=payload)
    else:
        response = client.request(method, url, headers=headers, content=payload)
    
    response.status = response.status_code
    
    return json.loads(response.text)

This allowed us to refactor the HTTP client implementation without changing the calling code.

The Results: Dramatic Latency Reduction

After implementing these changes, we observed remarkable improvements:

MetricBeforeAfterImprovement
Average order latency250-300ms88-120ms~52-70% reduction
Connection overhead170-220ms~0ms for subsequent requests~100% reduction

Key benefits achieved:

  1. Eliminated TCP Handshake: Saved 14-45ms per request
  2. Eliminated TLS Negotiation: Saved 50-100ms per request
  3. HTTP/2 Multiplexing: Improved concurrent request handling
  4. Better Resource Utilization: More efficient use of system resources

How to measure HTTP connection pooling gains yourself

Before changing production code, measure the difference on your own network. This small script times the same request with a new connection every time and with a shared client:

import time
import httpx

URL = "https://example.com/"  # replace with an endpoint you call often


def avg_ms(fn, n=10):
    times = []
    for _ in range(n):
        t0 = time.perf_counter()
        fn()
        times.append((time.perf_counter() - t0) * 1000)
    return sum(times) / len(times)


def new_connection_each_time():
    with httpx.Client() as c:  # handshake on every call
        c.get(URL)


shared = httpx.Client()  # one client, connections reused


def pooled():
    shared.get(URL)


print(f"new connection: {avg_ms(new_connection_each_time):.1f} ms")
print(f"pooled:         {avg_ms(pooled):.1f} ms")
shared.close()

Run it from the same machine and region as your trading server. The first pooled call still pays for the handshake, so look at the average over several calls. On a server far from the broker’s data center the gap will be larger, because each handshake round trip costs more.

Same idea with the requests library

If your code uses requests rather than httpx, a Session gives you the same connection reuse:

import requests
from requests.adapters import HTTPAdapter

session = requests.Session()
session.mount("https://", HTTPAdapter(pool_connections=10, pool_maxsize=20))

# every call through the same session reuses kept-alive connections
resp = session.get("https://example.com/", timeout=10)
print(resp.status_code)

Common mistakes with connection pooling in trading code

  • Creating a client inside the function. with httpx.Client() as c: inside an order function closes the pool after every call, which brings the handshake back.
  • Auto-retrying order requests. Retrying a GET is safe. Retrying a POST that may already have reached the broker can place a duplicate order. Check the order book first.
  • Keep-alive longer than the server allows. Brokers and load balancers close idle connections. A shorter keepalive expiry recycles stale connections before they fail.
  • Pool too small for many strategies. If many strategies fire at once, requests wait for a free connection. Size max_connections for your peak concurrency.
  • Forgetting to close on shutdown. Call client.close() when the application exits so sockets are released cleanly.

Future Plans

Right now, this implementation is done only for Angel One. Very soon, it will be extended to all the brokers supported by OpenAlgo.

2026 update: what OpenAlgo uses today

That plan has been completed. The current OpenAlgo httpx_client module describes itself as a shared client with connection pooling “for all broker APIs”. A few details have changed since this post was first written:

  • Limits were raised for multi-strategy setups: 40 keep-alive connections, 100 maximum connections and a 30 second keepalive expiry.
  • HTTP/2 is negotiated automatically with a fallback to HTTP/1.1, and it is disabled in standalone mode.
  • Read requests (GET, HEAD, OPTIONS) are retried once on network errors, but order writes are not retried. If a connection drops after an order is sent, OpenAlgo asks you to check the order book before placing it again.
  • The Angel One integration now calls apiconnect.angelone.in instead of the older apiconnect.angelbroking.com host used in the code above.

Latency also depends on the broker side. For a broker’s view of the same problem, read how Dhan’s DEXT engine achieved sub-20ms order execution latency. If you are choosing a web framework for your own trading backend, see Flask vs FastAPI: sync and async in fintech applications, and for streaming data rather than request-response calls, SSE vs WebSockets for stock market applications.

Wrap-up

By switching from http.client to httpx with connection pooling, we reduced our API latency by more than 60% – from 250-300ms down to just 110ms. This dramatically enhances the responsiveness of our trading application and proves how small infrastructure changes can lead to significant performance gains.

For trading systems, connection pooling is an essential feature, one that can mean the difference between executing a profitable trade or missing an opportunity.

Frequently Asked Questions

What is HTTP connection pooling in Python?

It is the reuse of open HTTP connections across requests. In Python, a shared httpx.Client or requests.Session keeps connections alive in a pool so later requests to the same host skip the TCP and TLS handshakes.

Is httpx faster than requests?

For simple synchronous calls, both are similar once you reuse a client or session. httpx adds HTTP/2 and async support, which help when many requests go to the same host concurrently.

How many connections should the pool have?

Start with enough to cover your peak number of simultaneous requests. OpenAlgo uses 40 keep-alive and 100 maximum connections for multi-strategy setups; a single strategy needs far fewer.

Does connection pooling help WebSocket market data?

No. A WebSocket is already one long-lived connection. Connection pooling helps REST calls such as placing orders, fetching positions and quotes.


This blog post describes performance optimizations implemented in OpenAlgo Platform, a Python-based algorithmic trading platform.

Python Elite membership

MEMBERSHIP

Python Elite membership

15 Python, AI and algo trading programs in one plan, including QuantFlow and AI Bootcamp live mentorship.

  • Python from fundamentals to trading apps
  • Backtesting, broker APIs and OpenAlgo
  • Live QuantFlow and AI Bootcamp sessions
View Python Elite →by Marketcalls

Learn by watching: free videos every week

Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More