Back to all posts
Running Rotating Proxies in AWS Lambda Functions

Running Rotating Proxies in AWS Lambda Functions

December 2, 2026

Why Serverless Needs Rotating Proxies

Serverless functions such as AWS Lambda are ideal for short‑lived scraping or API‑testing tasks because they scale automatically and you only pay for execution time. However, each invocation shares a small pool of outbound IP addresses. Target sites quickly flag repeated requests from the same IP, leading to blocks, CAPTCHAs, or throttling. Rotating proxies solve this by giving every invocation (or a small batch of invocations) a fresh exit IP, while keeping the function code simple.

Prerequisites

  • An AWS account with permission to create Lambda functions and IAM roles.
  • A proxy service that provides a gateway host, HTTP port, optional SOCKS5 port, username, and password. When you obtain a proxy from RoProxy, you receive these values for each proxy you purchase.
  • Basic familiarity with Python 3.11+ or Node.js 20+ runtimes.

Configuring the Proxy in Lambda Environment Variables

Store proxy credentials outside the code. In the Lambda console (or via IaC) add the following environment variables:

PROXY_GATEWAY_HOST=GATEWAY_HOST
PROXY_HTTP_PORT=HTTP_PORT
PROXY_SOCKS5_PORT=SOCKS5_PORT
PROXY_USERNAME=USERNAME
PROXY_PASSWORD=PASSWORD

At runtime, build the proxy URL:

  • HTTP/HTTPS – http://USERNAME:PASSWORD@GATEWAY_HOST:HTTP_PORT
  • SOCKS5 – socks5://USERNAME:PASSWORD@GATEWAY_HOST:SOCKS5_PORT

Using environment variables keeps secrets out of source control and lets you swap proxies without redeploying code.

Python Example: Scraping with a Rotating Proxy

import os
import json
import requests
from requests.auth import HTTPProxyAuth

def lambda_handler(event, context):
    # Build proxy URL from env vars
    gateway = os.getenv('PROXY_GATEWAY_HOST')
    http_port = os.getenv('PROXY_HTTP_PORT')
    username = os.getenv('PROXY_USERNAME')
    password = os.getenv('PROXY_PASSWORD')
    proxy_url = f'http://{username}:{password}@{gateway}:{http_port}'
    proxies = {'http': proxy_url, 'https': proxy_url}

    # Target endpoint – replace with your own
    target = 'https://httpbin.org/ip'
    try:
        resp = requests.get(target, proxies=proxies, timeout=10)
        resp.raise_for_status()
        exit_ip = resp.json().get('origin')
        return {
            'statusCode': 200,
            'body': json.dumps({'exit_ip': exit_ip})
        }
    except Exception as exc:
        return {
            'statusCode': 500,
            'body': json.dumps({'error': str(exc)})
        }

The handler reads the proxy details from the environment, creates a proxies dict, and calls https://httpbin.org/ip (or https://api.ipify.org?format=json) to verify the exit IP. The same pattern works for any HTTP/HTTPS target.

Node.js Example: Fetch with a Rotating Proxy

Node’s native fetch (available from v18) can use an http.Agent or https.Agent created by the https-proxy-agent package. Install the package as a layer or include it in your deployment package.

// package.json must include "https-proxy-agent"
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const { HttpsProxyAgent } = require('https-proxy-agent');

export const handler = async (event) => {
  const gateway = process.env.PROXY_GATEWAY_HOST;
  const httpPort = process.env.PROXY_HTTP_PORT;
  const username = process.env.PROXY_USERNAME;
  const password = process.env.PROXY_PASSWORD;
  const proxyUrl = `http://${username}:${password}@${gateway}:${httpPort}`;
  const agent = new HttpsProxyAgent(proxyUrl);

  try {
    const resp = await fetch('https://httpbin.org/ip', { agent });
    if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
    const data = await resp.json();
    return {
      statusCode: 200,
      body: JSON.stringify({ exit_ip: data.origin })
    };
  } catch (err) {
    return {
      statusCode: 500,
      body: JSON.stringify({ error: err.message })
    };
  }
};

The agent tunnels the HTTPS request through the HTTP proxy. For SOCKS5 you would use socks-proxy-agent instead and build a socks5:// URL.

Handling Cold Starts and Concurrency

  • Cold start penalty – The first invocation after a pause incurs initialization latency. Keep the proxy URL construction outside the handler (in the global scope) so it runs once per container reuse.
  • Connection reuse – Both requests.Session (Python) and fetch with a shared Agent (Node) keep TCP connections alive across invocations in the same container, reducing handshake overhead.
  • Concurrency limits – Lambda’s default concurrency quota (1000) may exceed the number of proxies you own. If you have fewer proxies than concurrent executions, multiple functions will share the same exit IP, increasing block risk. Solutions:
    • Request a higher proxy count on the Pro/Business plan.
    • Use sticky mode for a proxy and rotate only after a configurable number of requests (tracked in a DynamoDB counter).
    • Implement a simple semaphore (e.g., Redis‑based) to limit concurrent uses per proxy.

On‑Demand IP Rotation via API

When you need a fresh IP immediately (e.g., after a 429 or CAPTCHA), call the rotation endpoint. The API requires an Authorization: Bearer API_KEY header and the proxy’s SESSION_ID.

import os
import requests

def rotate_proxy_ip(session_id: str) -> bool:
    api_key = os.getenv('ROPROXY_API_KEY')  # store securely
    url = f'https://backend-api.ro-proxy.com/api/session/{session_id}/rotate'
    headers = {'Authorization': f'Bearer {api_key}'}
    resp = requests.post(url, headers=headers, timeout=5)
    return resp.status_code == 200

Invoke this from your handler when you detect a block. Remember the plan‑defined minimum interval between two rotate calls; respect it to avoid 429 errors from the API itself.

Verifying the Exit IP

After each request (or after a rotation) confirm the new IP:

verify = requests.get('https://api.ipify.org?format=json', proxies=proxies, timeout=5)
print('Exit IP:', verify.json()['ip'])

Or in Node:

const check = await fetch('https://api.ipify.org?format=json', { agent });
const { ip } = await check.json();
console.log('Exit IP:', ip);

Logging the exit IP helps you correlate blocks with specific proxies and tune rotation frequency.

Best Practices and Pitfalls

  • Never hard‑code credentials – Use environment variables or AWS Secrets Manager.
  • Set reasonable timeouts – Proxy latency adds to Lambda’s execution time; a 10‑second total timeout is a good starting point.
  • Handle 407 Proxy Authentication Required – Indicates bad username/password; fail fast and alert.
  • Avoid DNS leaks – Use the proxy for both HTTP and HTTPS; do not resolve hostnames locally before connecting.
  • Monitor proxy health – Periodically call the rotation endpoint with a dry‑run (if supported) or fetch a known endpoint to ensure the proxy is alive.
  • Respect target site policies – Rotate IPs to stay under rate limits, not to evade legal restrictions.

Conclusion

Running rotating proxies inside AWS Lambda gives you a scalable, pay‑per‑use scraping platform without managing servers. By injecting proxy configuration through environment variables, reusing connections across warm containers, and rotating IPs on demand via the provider’s API, you can keep each invocation on a clean exit address. RoProxy makes it easy to get rotating proxies for serverless workloads.