---
title: "Algo Trading on Serverless With a Static IP"
description: "Run a trading strategy on AWS Lambda, Cloud Run, or Railway and still pass the broker's IP whitelist: latency from Mumbai, cold starts, tokens, order routing."
canonical: https://fixedmark.com/blog/algo-trading-on-serverless-with-a-static-ip
updated: 2026-11-10
source: Fixedmark (https://fixedmark.com), BitMask LLP
---

Algo trading · 11 min read

# Algo Trading on Serverless With a Static IP

Indian brokers check the source IP on order placement, and serverless platforms do not give you a fixed one by default. Run the strategy in Mumbai, send the order calls (and any session call the broker ties to an IP) through a fixed egress IP you registered, and keep market data and cloud API calls on the direct path.

## What the broker actually checks

This post is general technical information, not legal, regulatory, or investment advice. Confirm your broker's current rules before you register an IP or change how you trade.

Under the retail algo framework, Indian brokers with retail APIs now check where your orders come from. The rules behind it are in [what SEBI's static IP rules require](https://fixedmark.com/blog/sebi-algo-trading-static-ip-rules). This post is about the engineering side, which is running the strategy on Lambda, Cloud Run, Railway, or a cron container without tripping that check.

The first thing to know is that the check is narrow. Brokers apply it to order placement, not to every API call. That shapes the whole design, because it tells you which traffic needs the fixed IP and which does not.

_What each broker's own documentation says the IP check covers_

| Broker               | IP-checked                         | Not IP-checked                               | Token note                                            |
| -------------------- | ---------------------------------- | -------------------------------------------- | ----------------------------------------------------- |
| Zerodha Kite Connect | API order placement                | WebSocket market data, order book, positions | Access token expires at 6 AM the next day             |
| Upstox               | Order placement                    | Not stated                                   | Changing the IP invalidates the access token          |
| Dhan                 | Orders, Super Order, Forever Order | Order and trade details                      | Token valid 24 hours                                  |
| Kotak Neo            | Place, modify, cancel order        | Login, reports, portfolio, data, WebSocket   | Session must be created from the IP that sends orders |

Sources for each row are [Zerodha](https://support.zerodha.com/category/trading-and-markets/general-kite/kite-api/articles/static-ip), [Upstox](https://upstox.com/developer/api-documentation/appendix/my-apps-support-for-algo-trading-circular/), [Dhan](https://dhanhq.co/docs/v2/authentication/), and [Kotak Neo](https://www.kotakneo.com/platform/kotak-neo-trade-api/static-ip-details/). Each broker takes a primary IP and an optional secondary, and limits changes to about once a week. Zerodha also asks you to confirm the IP is used only by you or your immediate family, which rules out the shared pools most platforms hand out.

## Why serverless egress fails the whitelist

A Lambda function outside a VPC, a Cloud Run service on default networking, and a Railway service all leave the internet from addresses the platform picks. Those addresses are shared with other tenants and change as instances come and go. The details per platform are in [why serverless egress IPs change](https://fixedmark.com/blog/why-serverless-egress-ips-change). For a broker, a changing IP means rejected orders, and a weekly change limit means you cannot chase it.

Each platform has a native way to pin the address, and each has a catch for this use case.

- AWS Lambda. Attach the function to private subnets and route `0.0.0.0/0` to a NAT gateway with an Elastic IP. The NAT gateway bills by the hour in every Availability Zone you cover, before any traffic. See [the hidden costs of a NAT gateway](https://fixedmark.com/blog/nat-gateway-hidden-costs).
- Google Cloud Run. Reserve a static address, create a Cloud Router and Cloud NAT, then deploy with Direct VPC egress and `--vpc-egress=all-traffic`, per [Google's guide](https://docs.cloud.google.com/run/docs/configuring/static-outbound-ip). It works, and Cloud NAT bills separately.
- Railway. Static Outbound IPs are on the Pro plan, but [Railway's docs](https://docs.railway.com/reference/static-outbound-ips) say there is no guarantee the addresses are dedicated, and they change if you move regions. A broker that asks for an IP used only by you is a poor match for an address that may be shared.
- A cron container on a VM. A VM with a reserved public IP is the simplest fix of all, but then you are running a server, not serverless. The tradeoffs are in [home static IP vs VPS vs proxy](https://fixedmark.com/blog/home-static-ip-vs-vps-vs-proxy-for-algo-trading).

The option that works the same on every platform is a static IP proxy. Your code sends selected requests through an HTTP CONNECT or SOCKS5 proxy, and the broker sees the proxy's address. Nothing about the platform's networking changes.

## The latency budget from Mumbai

Retail strategies under the framework can send up to 10 orders per second per exchange segment without exchange registration, per [Zerodha's summary of the NSE circular](https://zerodha.com/z-connect/general/a-comprehensive-overview-of-nses-circular-on-the-new-retail-algo-trading-framework). Kite Connect itself caps order placement at 10 requests per second and 400 orders a minute, per [its rate limit table](https://kite.trade/docs/connect/v3/exceptions/). At that pace you are not racing colocated firms. You are trying to avoid adding hundreds of milliseconds you did not plan for.

The biggest number in the budget is distance. Put the code in Mumbai. Lambda has `ap-south-1` and Cloud Run has `asia-south1`. Railway has no India region, and its [nearest region](https://docs.railway.com/reference/deployment-regions) is Singapore. A third-party benchmark puts AWS Singapore to Mumbai at about [63 ms](https://www.economize.cloud/resources/aws/latency/ap-southeast-1-vs-ap-south-1/) of inter-region latency, and every order pays that if your code runs in Singapore.

The second number is connection setup. A request over a new HTTPS connection through a TLS-wrapped CONNECT proxy pays several round trips before the order leaves.

1. TCP handshake to the proxy. One round trip to the proxy.
2. TLS handshake to the proxy, when the proxy URL is `https://`. One round trip with TLS 1.3.
3. The `CONNECT` request and the proxy's `200` reply. One round trip to the proxy, plus the proxy's own TCP connect to the broker.
4. TLS handshake to the broker inside the tunnel. One full round trip from your code to the broker.
5. The order request and response. One more full round trip.

On a kept-alive connection only the last step repeats. If the code and the proxy sit in the same city, steps 1 to 3 are short. If the code is in Singapore and the proxy in Mumbai, each of them crosses the sea. The mechanics are in [how an HTTP CONNECT proxy works](https://fixedmark.com/blog/http-connect-proxy-explained). The practical rules are to keep code, proxy, and broker in one city, and to reuse one client across invocations so warm calls pay only step 5.

## Cold starts and where the strategy runs

A strategy has two shapes. One reacts to events, such as a scheduled entry at 9:20 or a signal from your own scanner. The other runs a loop through the session and reads ticks from a WebSocket. Pick the platform by the shape.

_Matching the strategy shape to the platform_

| Platform          | Fits                                             | Limit to plan around                                              |
| ----------------- | ------------------------------------------------ | ----------------------------------------------------------------- |
| AWS Lambda        | Event-driven orders, scheduled entries and exits | 15-minute maximum per invocation                                  |
| Cloud Run service | An HTTP endpoint that receives signals           | Scales to zero unless you set minimum instances                   |
| Cloud Run job     | A loop that runs the whole session               | Task timeout up to 168 hours, 10 minutes by default               |
| Railway cron      | Short scheduled runs                             | UTC schedules, 5 minutes apart at least, overlapping runs skipped |

The limits come from [Lambda quotas](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html), [Cloud Run minimum instances](https://docs.cloud.google.com/run/docs/configuring/min-instances), [Cloud Run task timeout](https://docs.cloud.google.com/run/docs/configuring/task-timeout), and [Railway cron jobs](https://docs.railway.com/reference/cron-jobs). A tick loop does not belong on Lambda. A Cloud Run job started before the open, with its timeout set past 15:30, holds a WebSocket and a warm proxy connection for the whole session.

### Keeping the first order fast

A cold start adds runtime and package load time before your handler runs. For an order at a fixed time, schedule a warm-up call a few minutes earlier that loads the token and opens the proxy connection. On Lambda, [SnapStart](https://docs.aws.amazon.com/lambda/latest/dg/snapstart.html) supports Python 3.12 and later, Java, and .NET, but not Node.js, and provisioned concurrency keeps environments initialized for a fee. SnapStart has one catch here. AWS says connections opened during initialization are not guaranteed after a restore, so check or reopen the proxy connection in the handler. On Cloud Run, set `--min-instances 1` on the service for market hours.

India has no daylight saving time, so IST is always UTC+5:30. That makes UTC-only schedulers easy. 09:10 IST is 03:40 UTC every day of the year.

**EventBridge Scheduler**

```bash
# 09:10 IST, Monday to Friday, evaluated in Asia/Kolkata.
# MaximumRetryAttempts 0: a failed order run must not be replayed.
aws scheduler create-schedule \
  --name entry-0910 \
  --schedule-expression "cron(10 9 ? * MON-FRI *)" \
  --schedule-expression-timezone "Asia/Kolkata" \
  --flexible-time-window '{"Mode": "OFF"}' \
  --target '{
    "Arn": "arn:aws:lambda:ap-south-1:123456789012:function:entry",
    "RoleArn": "arn:aws:iam::123456789012:role/scheduler-invoke",
    "RetryPolicy": {"MaximumRetryAttempts": 0, "MaximumEventAgeInSeconds": 60}
  }'

# Lambda's own async retries: off for the order function.
aws lambda put-function-event-invoke-config \
  --function-name entry \
  --maximum-retry-attempts 0
```

**Railway cron**

```
# Railway schedules run in UTC. 03:40 UTC is 09:10 IST.
40 3 * * 1-5
```

Retries are the serverless trap for trading. EventBridge Scheduler [invokes Lambda asynchronously](https://docs.aws.amazon.com/lambda/latest/dg/with-eventbridge-scheduler.html), and by default [Lambda retries a failed async invocation twice](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async-error-handling.html). AWS also warns that the same event can arrive more than once. An order call that timed out may still have reached the exchange. Turn retries off for order functions, tag each order, and check the order book for that tag before you place it again.

The [schedule types page](https://docs.aws.amazon.com/scheduler/latest/UserGuide/schedule-types.html) documents the six-field cron format and the `--schedule-expression-timezone` parameter used above.

## Token refresh on a stateless platform

Broker tokens are short-lived by rule, and a function has nowhere to keep state between invocations. So the token lives in a secret store, a separate step refreshes it each morning, and the trading function reads it.

- Zerodha. The access token is valid until 6 AM the next day, per the [Kite Connect user docs](https://kite.trade/docs/connect/v3/user/). Getting a new one needs the user to log in. Your backend then exchanges the `request_token` with a SHA-256 checksum at `/session/token`. An answer on the [Kite Connect forum](https://kite.trade/forum/discussion/8976/automate-kiteconnect-login-process) says the exchange requires a manual login at least once a day and does not recommend automating it.
- Upstox. The token lasts until 3:30 AM the next day. The [access token request flow](https://upstox.com/developer/api-documentation/access-token-request/) fits serverless well. Your code sends the request, the user approves it in the Upstox app or on WhatsApp, and Upstox posts the token to the notifier webhook you set on the app. That webhook can be a small function that writes the token to your secret store.
- Dhan. A token from Dhan Web lasts 24 hours and can be renewed while it is still active, per the [DhanHQ authentication docs](https://dhanhq.co/docs/v2/authentication/). The API key flow uses a browser login with 2FA to produce a token.

Two IP details matter here. Kotak Neo validates the session against the IP that sends orders, so the login call must go through the same fixed egress as the orders. Upstox invalidates tokens when you change the registered IP, and [Dhan says](https://dhan.co/support/platforms/dhanhq-api/i-have-added-my-static-ip-s-on-dhan-web-but-my-orders-are-getting-rejected-stating-dh-905-invalid-ip-while-placing-them-through-the-api-what-should-i-do/) to regenerate the token if you added the IP after creating it. When a broker ties sessions to IPs, route the session call through the proxy too.

On AWS, SSM Parameter Store with a `SecureString` or Secrets Manager both work. Cache the value in memory for a few minutes and re-read it on an auth error. On Cloud Run, mount the token from Secret Manager as a volume, not an environment variable. Per [Google's docs](https://docs.cloud.google.com/run/docs/configuring/services/secrets), Cloud Run fetches a secret env var once before the instance starts, but fetches a mounted secret from Secret Manager on every read. A token refreshed at 8:45 then reaches a job that started at 8:30.

## Send only the order calls through the fixed IP

The tempting shortcut is `HTTPS_PROXY` on the whole function. Avoid it. Python's requests and boto3 read it, so your SSM and S3 calls would leave through the proxy too. Market data WebSockets can carry far more bytes than orders, and they do not need the fixed address at Zerodha, Kotak Neo, or Dhan. Give the proxy to the client that places orders and nothing else. [How NO_PROXY and per-client agents behave](https://fixedmark.com/blog/selective-proxying-no-proxy-and-per-client-agents) covers the env var surprises in each language.

The Python client for Kite Connect takes a `proxies` dict in its constructor and passes it on every request, per [its source](https://github.com/zerodha/pykiteconnect/blob/master/kiteconnect/connect.py). Create two clients at module scope, one proxied for orders and one direct for data, so warm invocations reuse their connections.

**Python (Lambda)**

```python
# requirements.txt: kiteconnect
import os
import time

import boto3
from kiteconnect import KiteConnect
from kiteconnect.exceptions import TokenException

PROXY = os.environ["FIXEDMARK_PROXY_URL"]  # not HTTPS_PROXY: boto3 reads that
API_KEY = os.environ["KITE_API_KEY"]
TOKEN_PARAM = os.environ["KITE_TOKEN_PARAM"]  # SSM SecureString

ssm = boto3.client("ssm")  # direct, no proxy

# Orders leave through the registered IP. Data goes direct.
orders = KiteConnect(api_key=API_KEY, timeout=5,
                     proxies={"http": PROXY, "https": PROXY})
data = KiteConnect(api_key=API_KEY, timeout=5)

_token = {"value": None, "read_at": 0.0}

def load_token(force=False):
    if not force and _token["value"] and time.time() - _token["read_at"] < 300:
        return
    value = ssm.get_parameter(Name=TOKEN_PARAM, WithDecryption=True)["Parameter"]["Value"]
    orders.set_access_token(value)
    data.set_access_token(value)
    _token.update(value=value, read_at=time.time())

def tick_round(price, tick=0.05):
    return round(round(price / tick) * tick, 2)

def handler(event, context):
    load_token()
    tag = event["tag"]  # unique per intended order, 20 chars max

    # Never place twice: an earlier attempt may have reached the exchange.
    if any(o.get("tag") == tag for o in orders.orders()):
        return {"skipped": tag}

    ltp = data.ltp(["NSE:INFY"])["NSE:INFY"]["last_price"]
    try:
        order_id = orders.place_order(
            variety=orders.VARIETY_REGULAR,
            exchange=orders.EXCHANGE_NSE,
            tradingsymbol="INFY",
            transaction_type=orders.TRANSACTION_TYPE_BUY,
            quantity=1,
            product=orders.PRODUCT_CNC,
            order_type=orders.ORDER_TYPE_LIMIT,
            price=tick_round(ltp * 0.995),
            tag=tag,
        )
    except TokenException:
        load_token(force=True)  # someone may have refreshed it; alert, do not retry blindly
        raise
    return {"order_id": order_id}
```

**Node.js (undici)**

```javascript
// npm install undici  (undici 8 needs Node.js 22.19+)
import { fetch, ProxyAgent } from "undici";

// One agent at module scope, reused by warm invocations.
const viaFixedIp = new ProxyAgent(process.env.FIXEDMARK_PROXY_URL);
const KITE = "https://api.kite.trade";

function headers(accessToken) {
  return {
    "X-Kite-Version": "3",
    Authorization: `token ${process.env.KITE_API_KEY}:${accessToken}`,
  };
}

// Data: direct, no dispatcher.
export async function lastPrice(accessToken, key) {
  const url = `${KITE}/quote/ltp?i=${encodeURIComponent(key)}`;
  const res = await fetch(url, { headers: headers(accessToken) });
  const body = await res.json();
  return body.data[key].last_price;
}

// Orders: through the registered IP.
export async function placeLimit(accessToken, order) {
  const res = await fetch(`${KITE}/orders/regular`, {
    method: "POST",
    dispatcher: viaFixedIp,
    headers: headers(accessToken),
    body: new URLSearchParams({
      exchange: "NSE",
      tradingsymbol: order.symbol,
      transaction_type: order.side,
      quantity: String(order.quantity),
      product: "CNC",
      order_type: "LIMIT",
      price: order.price.toFixed(2),
      validity: "DAY",
      tag: order.tag,
    }),
  });
  const body = await res.json();
  if (body.status !== "success") {
    throw new Error(`${res.status} ${body.error_type}: ${body.message}`);
  }
  return body.data.order_id;
}
```

The Python sketch reads the order book through the proxied client before placing, because that client holds the same token and the call is cheap. Kite rejects an expired session with a `403` and a `TokenException`, per [its exception docs](https://kite.trade/docs/connect/v3/exceptions/), so that error means a token problem, not an IP problem. When the IP is the problem, the message differs per broker. [Fixing IP not whitelisted errors](https://fixedmark.com/blog/fixing-ip-not-whitelisted-errors-on-broker-apis) lists them.

### Prove the egress before market hours

Deploy a one-off check that calls an IP echo service through the same proxy config as the order client, and compare the result with the IPs registered at the broker. Run it from the real platform, not your laptop, because the platform is what the broker sees.

**check_egress.py**

```python
import os

import requests

proxy = os.environ["FIXEDMARK_PROXY_URL"]
print("via proxy:", requests.get("https://fixedmark.com/api/ip",
                                 proxies={"http": proxy, "https": proxy},
                                 timeout=10).text)
print("direct:   ", requests.get("https://fixedmark.com/api/ip", timeout=10).text)
```

## Doing this with Fixedmark

Fixedmark is a static IP proxy built for this pattern. It is in early access, and the prices below are planned launch prices that may change.

- A dedicated pair of IPv4 addresses in Mumbai, near the brokers and the Lambda and Cloud Run regions you would use anyway. Register one as the primary IP and one as the secondary. [Why brokers ask for primary and secondary IPs](https://fixedmark.com/blog/why-brokers-ask-for-primary-and-secondary-ip) explains the slots.
- One proxy URL in `FIXEDMARK_PROXY_URL`, passed only to the order client, exactly as in the code above. Per-language setup is in the [Python](https://fixedmark.com/docs/python) and [Node.js](https://fixedmark.com/docs/node) docs.
- On Business and larger plans, a [destination allowlist](https://fixedmark.com/docs/allowlists) on the token, such as `api.kite.trade` on port 443, so a leaked proxy token cannot reach anything else.
- [Connection logs](https://fixedmark.com/docs/logs) that show the destination, egress IP, and result of each connection, which helps when an order is rejected at 9:15.
- TLS passes through end to end. Fixedmark never sees your API key, access token, or orders.

The planned India Trader plan includes 5 GB of bandwidth a month in Mumbai. Order traffic fits easily in that, which is one more reason to keep market data on the direct path. See [planned India pricing](https://fixedmark.com/india/algo-trading-static-ip). The trial and Starter run on a shared pair, so do not register their addresses with a broker. Broker-by-broker steps are in the [broker guides](https://fixedmark.com/docs/brokers).

Each new connection through a Fixedmark pair can leave from either IP, so register both with the broker. Kotak Neo needs the session created from the IP that sends the orders, so ask [Fixedmark support](https://fixedmark.com/docs/support) before you rely on the pair with Kotak Neo.

## Sources

Checked November 2026. Confirm current details on the vendor's site before you decide. Prices and limits change.

- [Zerodha support: static IP for Kite Connect](https://support.zerodha.com/category/trading-and-markets/general-kite/kite-api/articles/static-ip)
- [Kite Connect docs: user and session](https://kite.trade/docs/connect/v3/user/)
- [Kite Connect docs: exceptions and rate limits](https://kite.trade/docs/connect/v3/exceptions/)
- [pykiteconnect: connect.py source](https://github.com/zerodha/pykiteconnect/blob/master/kiteconnect/connect.py)
- [Upstox docs: My Apps support for the algo trading circular](https://upstox.com/developer/api-documentation/appendix/my-apps-support-for-algo-trading-circular/)
- [Upstox docs: access token request](https://upstox.com/developer/api-documentation/access-token-request/)
- [DhanHQ docs: authentication](https://dhanhq.co/docs/v2/authentication/)
- [Dhan support: DH-905 invalid IP on API orders](https://dhan.co/support/platforms/dhanhq-api/i-have-added-my-static-ip-s-on-dhan-web-but-my-orders-are-getting-rejected-stating-dh-905-invalid-ip-while-placing-them-through-the-api-what-should-i-do/)
- [Kite Connect forum: automating the Kite Connect login](https://kite.trade/forum/discussion/8976/automate-kiteconnect-login-process)
- [Google Cloud docs: Cloud Run secrets](https://docs.cloud.google.com/run/docs/configuring/services/secrets)
- [Kotak Neo: static IP details](https://www.kotakneo.com/platform/kotak-neo-trade-api/static-ip-details/)
- [Zerodha Z-Connect: overview of NSE's retail algo framework](https://zerodha.com/z-connect/general/a-comprehensive-overview-of-nses-circular-on-the-new-retail-algo-trading-framework)
- [AWS docs: Lambda quotas](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html)
- [AWS docs: Lambda async error handling and retries](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async-error-handling.html)
- [AWS docs: invoke a Lambda function on a schedule](https://docs.aws.amazon.com/lambda/latest/dg/with-eventbridge-scheduler.html)
- [AWS docs: EventBridge Scheduler schedule types](https://docs.aws.amazon.com/scheduler/latest/UserGuide/schedule-types.html)
- [AWS docs: Lambda SnapStart](https://docs.aws.amazon.com/lambda/latest/dg/snapstart.html)
- [Google Cloud docs: Cloud Run static outbound IP](https://docs.cloud.google.com/run/docs/configuring/static-outbound-ip)
- [Google Cloud docs: Cloud Run minimum instances](https://docs.cloud.google.com/run/docs/configuring/min-instances)
- [Google Cloud docs: Cloud Run task timeout](https://docs.cloud.google.com/run/docs/configuring/task-timeout)
- [Railway docs: deployment regions](https://docs.railway.com/reference/deployment-regions)
- [Railway docs: static outbound IPs](https://docs.railway.com/reference/static-outbound-ips)
- [Railway docs: cron jobs](https://docs.railway.com/reference/cron-jobs)
- [Economize: AWS latency, ap-southeast-1 to ap-south-1](https://www.economize.cloud/resources/aws/latency/ap-southeast-1-vs-ap-south-1/)

Keep reading

## Related guides

- [Guide Static IP for algo trading A dedicated Mumbai IP pair for broker whitelisting, priced in INR.](https://fixedmark.com/india/algo-trading-static-ip)
- [Integration AWS Lambda A fixed IP for Lambda without VPC, subnets, and two NAT Gateways.](https://fixedmark.com/integrations/aws-lambda)
- [Integration Google Cloud Run A fixed outbound IP for Cloud Run services and jobs without a VPC and Cloud NAT.](https://fixedmark.com/integrations/google-cloud-run)
- [Integration Railway A dedicated IP pair for Railway services when shared static IPs are not enough.](https://fixedmark.com/integrations/railway)
- [Guide Regions Mumbai, Singapore, Newark, and Ashburn.](https://fixedmark.com/regions)

## Frequently asked questions

### Can I run an algo trading bot on AWS Lambda in India?

Yes, for event-driven strategies. Run it in ap-south-1 (Mumbai), send order calls through a fixed IP you registered with the broker, and turn off async retries for any function that places orders. A tick-by-tick loop does not fit Lambda's 15-minute limit.

### Do market data calls need the static IP?

Not at most brokers. Zerodha, Kotak Neo, and Dhan apply the IP check to order placement. Zerodha and Kotak Neo say WebSocket data works from any IP. Check your broker's page, since rules differ.

### Is Railway's static outbound IP enough for a broker?

Railway's docs say its static IPs are not guaranteed to be dedicated. Brokers such as Zerodha ask you to confirm the IP is used only by you or your family, so a possibly shared address is a risk.

### Should I set HTTPS_PROXY on my function?

No. Python requests and boto3 read it, so cloud API calls would go through the proxy too. Use a dedicated variable such as FIXEDMARK_PROXY_URL and pass it only to the order client.

### Can I automate the daily broker login?

It depends on the broker. Upstox has an access token request flow that delivers the token to a webhook after the user approves it. Zerodha's moderators say a manual login once a day is an exchange requirement and do not recommend automating it.
