# Static IP for AWS Lambda

Source: https://prontaro.com/docs/integrations/aws-lambda/

Leave AWS Lambda outside a VPC and still call allowlisted partner APIs from one fixed IPv4, with no hourly NAT Gateway bill.

Lambda exits through rotating AWS IP ranges by default, while the native Elastic IP setup requires private subnets, route tables, hourly NAT Gateway fees, and per-GB processing charges. With Prontaro, you route only selected calls using `undici`, Python `httpx`, or a Relay URL — see [Prontaro vs AWS NAT Gateway](https://prontaro.com/docs/compare/aws-nat-gateway.md) for a full architecture and cost breakdown.

## Which method to choose

| Use case | Prontaro method | Best for |
| --- | --- | --- |
| **Partner REST/GraphQL APIs (Node.js / Python)** | HTTPS proxy (`undici` / `httpx`) | End-to-end TLS and mTLS via HTTP CONNECT; any target host |
| **Single-host REST API without proxy packages** | Relay URL | Standard `fetch` or `urllib` — swap the base URL |
| **External databases (MongoDB, Postgres)** | SOCKS5 (`socks5h://`) | Forwards database TCP connections ([MongoDB Atlas guide](https://prontaro.com/docs/integrations/mongodb-atlas.md)) |

A Relay URL decrypts TLS on the Prontaro server and opens a new HTTPS connection to the target API. Use HTTPS proxy when a partner requires end-to-end TLS or mTLS — see [Relay URLs](https://prontaro.com/docs/outbound/relay.md).

## Prerequisites

- A Prontaro account on Dedicated or Pro ([plans](https://prontaro.com/docs/billing/plans.md)). Open [my.prontaro.com/ips](https://my.prontaro.com/ips), pick the location closest to your Lambda region, and click **Add IP**.
- An AWS Lambda function on Node.js 20+ or Python 3.11+ with normal outbound internet access (not inside an isolated private VPC subnet with no route out).
- You do not need `prontaro CLI` — proxy credentials and Relay URLs can be created directly in the dashboard.

## Step 1. Create credentials and allowlist your IP

Add your dedicated IPv4 (`/32`) to the partner API allowlist, then create credentials for your Lambda function in the dashboard.

1. Open **IP addresses** in [my.prontaro.com](https://my.prontaro.com/ips), select your IP, and click **Create proxy credentials** (for example, `lambda-prod`).
2. Copy the `HTTPS` URL (`https://u_lambda:s3cr3t@<entry>.prontaro.io:443`).
3. If you prefer a Relay URL for a single REST API, click **Add relay address** and enter `api.example.com`.

IP addresses Proxy credentials [Open in dashboard](https://my.prontaro.com/ips)

Wait until Step 5 before restricting allowed destinations so the `api.ipify.org` check in Step 4 succeeds.

## Step 2. Store secrets and raise the Lambda timeout

Never hardcode credentials in your function bundle. For the fastest setup, add them as Lambda environment variables (encrypted at rest with KMS automatically):

**Lambda → Function → Configuration → Environment variables**

- `PRONTARO_PROXY_URL`: `https://u_lambda:s3cr3t@<entry>.prontaro.io:443`
- `PARTNER_API_TOKEN`: `your-partner-token`

For multi-function stacks or centralized rotation, store the URL in AWS Secrets Manager or SSM Parameter Store (`SecureString`), fetch it once during module init, and cache it in memory.

> **Raise the default 3-second Lambda timeout**
>
> New Lambda functions default to a 3-second timeout. Even with a 10-second HTTP client timeout, a cold start or slow API will fail with `Task timed out after 3.00 seconds`.
>
> Open **Configuration → General configuration → Timeout** and set it to at least 15 seconds.

## Step 3. Configure your Lambda handler

### Node.js 20+ with `undici`

Package `undici` with your function or in a Lambda layer (`npm install undici`). Instantiate `ProxyAgent` at module scope — outside `handler` — so reused containers keep TCP/TLS connections open:

```js
// index.mjs
import { fetch, ProxyAgent } from 'undici';

const proxyUrl = process.env.PRONTARO_PROXY_URL;
if (!proxyUrl) {
  throw new Error('PRONTARO_PROXY_URL is required');
}

const agent = new ProxyAgent({
  uri: proxyUrl,
  connections: 10,
});

export const handler = async (event) => {
  const path = event?.path ?? '/v1/status';
  const response = await fetch(`https://api.example.com${path}`, {
    method: 'GET',
    dispatcher: agent,
    headers: {
      Authorization: `Bearer ${process.env.PARTNER_API_TOKEN}`,
    },
    signal: AbortSignal.timeout(10_000),
  });

  return {
    statusCode: response.status,
    headers: { 'content-type': response.headers.get('content-type') ?? 'application/json' },
    body: await response.text(),
  };
};
```

### Python 3.11+ with `httpx`

Bundle `httpx` in your deployment package or layer (`pip install httpx -t package/`). Keep `httpx.Client` at module scope:

```python
# lambda_function.py
import os
import httpx

PROXY_URL = os.environ["PRONTARO_PROXY_URL"]

client = httpx.Client(
    proxy=PROXY_URL,
    timeout=httpx.Timeout(10.0, connect=5.0),
    limits=httpx.Limits(max_connections=10, max_keepalive_connections=5),
)

def lambda_handler(event, context):
    path = (event or {}).get("path", "/v1/status")
    response = client.get(
        f"https://api.example.com{path}",
        headers={"Authorization": f"Bearer {os.environ['PARTNER_API_TOKEN']}"},
    )
    return {
        "statusCode": response.status_code,
        "headers": {"content-type": response.headers.get("content-type", "application/json")},
        "body": response.text,
    }
```

### REST API via Relay URL (zero extra dependencies)

Set `PRONTARO_RELAY_URL` and use the standard library directly with no proxy package at all:

```js
// index.mjs (Node.js 20+)
const relayBase = process.env.PRONTARO_RELAY_URL;

export const handler = async () => {
  const response = await fetch(new URL('/v1/status', relayBase), {
    headers: { Authorization: `Bearer ${process.env.PARTNER_API_TOKEN}` },
    signal: AbortSignal.timeout(10_000),
  });
  return { statusCode: response.status, body: await response.text() };
};
```

```python
# lambda_function.py (Python 3.11+)
import os
import urllib.request

RELAY_BASE = os.environ["PRONTARO_RELAY_URL"].rstrip("/")

def lambda_handler(event, context):
    req = urllib.request.Request(
        f"{RELAY_BASE}/v1/status",
        headers={"Authorization": f"Bearer {os.environ['PARTNER_API_TOKEN']}"},
    )
    with urllib.request.urlopen(req, timeout=10) as resp:
        return {"statusCode": resp.status, "body": resp.read().decode()}
```

## Step 4. Verify the outbound IP

Deploy a temporary `egress-check` function (or temporarily point your handler at `https://api.ipify.org` using the same `ProxyAgent` / `httpx.Client`):

```js
// egress-check: index.mjs
import { fetch, ProxyAgent } from 'undici';

const agent = new ProxyAgent(process.env.PRONTARO_PROXY_URL);

export const handler = async () => {
  const res = await fetch('https://api.ipify.org', {
    dispatcher: agent,
    signal: AbortSignal.timeout(10_000),
  });
  return { statusCode: res.status, body: (await res.text()).trim() };
};
```

Invoke it with AWS CLI v2 (the `--cli-binary-format raw-in-base64-out` flag is required so AWS CLI accepts raw JSON `{}` instead of base64):

```
 aws lambda invoke --function-name egress-check --cli-binary-format raw-in-base64-out --payload '{}'
{"statusCode":200,"body":"203.0.113.10"}
```

Confirm the body matches your dedicated Prontaro IPv4, then delete the temporary function.

## Step 5. Lock down allowed targets (recommended)

Once verified, restrict your proxy credentials to the exact destination host and port:

1. Open **IP addresses → Proxy credentials** in [my.prontaro.com](https://my.prontaro.com/ips), select `lambda-prod`, and switch to **Access**.
2. Add `api.example.com:443` under **To** and save.

IP addresses Proxy credentials Access [Open in dashboard](https://my.prontaro.com/ips)

## AWS Lambda notes and limits

- **Reuse the client across invocations.** Creating a new `ProxyAgent` or `httpx.Client` inside the handler opens a new TCP/TLS connection on every request and quickly exhausts sockets under load.
- **Size pools for concurrency.** 50 concurrent containers × `10` connections = `500` open sockets. Keep `connections` / `max_connections` around `5–10` to stay within your [plan limit](https://prontaro.com/docs/billing/limits.md).
- **Avoid global `HTTPS_PROXY` with AWS SDKs.** S3, DynamoDB, SQS, and Secrets Manager honor `HTTPS_PROXY` by default. Pass `PRONTARO_PROXY_URL` only to your external API client to save Prontaro traffic.
- **VPC-attached Lambdas still need internet egress.** A function inside an isolated private subnet with no route out cannot reach the Prontaro server.

## Common errors

| Error | Cause | Fix |
| --- | --- | --- |
| `Task timed out after 3.00 seconds` | Function still uses the default 3-second Lambda timeout. | Raise **Configuration → General configuration → Timeout** to at least 15 seconds. |
| Timeout reaching proxy host | Lambda is attached to a private VPC subnet without an internet route. | Detach Lambda from the VPC if private VPC resources are unneeded, or fix subnet routing. |
| Unexpected traffic in Prontaro dashboard | Global `HTTPS_PROXY` routed AWS SDK calls through Prontaro. | Unset `HTTPS_PROXY` and configure `PRONTARO_PROXY_URL` only on the external API client. |

For `407`, `403`, and general proxy issues, see [error codes](https://prontaro.com/docs/cli/errors.md) and [HTTP & SOCKS5 proxy](https://prontaro.com/docs/outbound/proxy.md).

## Next steps

- [Prontaro vs AWS NAT Gateway](https://prontaro.com/docs/compare/aws-nat-gateway.md) — architecture and cost comparison against VPC and NAT Gateway.
- [Connect to MongoDB Atlas](https://prontaro.com/docs/integrations/mongodb-atlas.md) — reach MongoDB Atlas from Lambda over SOCKS5.
- [HTTP & SOCKS5 proxy](https://prontaro.com/docs/outbound/proxy.md) — proxy credentials, protocols, and allowed destination rules.
- [Static IP for Cloud Run and Cloud Functions](https://prontaro.com/docs/integrations/google-cloud-run.md) — the same pattern on Google Cloud without Cloud NAT.
- [Reliability, zero-downtime updates, and BGP failover](https://prontaro.com/docs/outbound/failover.md) — how your `/32` stays intact during server failover.
