[{"data":1,"prerenderedAt":36},["ShallowReactive",2],{"blog:post:en:running-rotating-proxies-in-aws-lambda":3,"blog:related:en:running-rotating-proxies-in-aws-lambda":23},{"slug":4,"lang":5,"title":6,"summary":7,"date":8,"tags":9,"tag_slugs":15,"thumbnail_url":16,"translations":17,"body":18,"asset_base":19,"checksum":20,"published_at":21,"content_updated_at":22},"running-rotating-proxies-in-aws-lambda","en","Running Rotating Proxies in AWS Lambda Functions","Learn how to configure rotating HTTP and SOCKS5 proxies inside AWS Lambda, handle cold starts, concurrency limits, and securely rotate IPs on demand.","2026-12-02",[10,11,12,13,14],"proxy","proxy-rotation","python","nodejs","automation",[10,11,12,13,14],"https://blog-api.ro-proxy.com/api/blog/posts/running-rotating-proxies-in-aws-lambda/thumbnail.svg?lang=en",[5],"## Why Serverless Needs Rotating Proxies\n\nServerless 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.\n\n## Prerequisites\n\n* An AWS account with permission to create Lambda functions and IAM roles.\n* 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.\n* Basic familiarity with Python 3.11+ or Node.js 20+ runtimes.\n\n## Configuring the Proxy in Lambda Environment Variables\n\nStore proxy credentials outside the code. In the Lambda console (or via IaC) add the following environment variables:\n\n```text\nPROXY_GATEWAY_HOST=GATEWAY_HOST\nPROXY_HTTP_PORT=HTTP_PORT\nPROXY_SOCKS5_PORT=SOCKS5_PORT\nPROXY_USERNAME=USERNAME\nPROXY_PASSWORD=PASSWORD\n```\n\nAt runtime, build the proxy URL:\n\n* **HTTP/HTTPS** – `http://USERNAME:PASSWORD@GATEWAY_HOST:HTTP_PORT`\n* **SOCKS5** – `socks5://USERNAME:PASSWORD@GATEWAY_HOST:SOCKS5_PORT`\n\nUsing environment variables keeps secrets out of source control and lets you swap proxies without redeploying code.\n\n## Python Example: Scraping with a Rotating Proxy\n\n```python\nimport os\nimport json\nimport requests\nfrom requests.auth import HTTPProxyAuth\n\ndef lambda_handler(event, context):\n    # Build proxy URL from env vars\n    gateway = os.getenv('PROXY_GATEWAY_HOST')\n    http_port = os.getenv('PROXY_HTTP_PORT')\n    username = os.getenv('PROXY_USERNAME')\n    password = os.getenv('PROXY_PASSWORD')\n    proxy_url = f'http://{username}:{password}@{gateway}:{http_port}'\n    proxies = {'http': proxy_url, 'https': proxy_url}\n\n    # Target endpoint – replace with your own\n    target = 'https://httpbin.org/ip'\n    try:\n        resp = requests.get(target, proxies=proxies, timeout=10)\n        resp.raise_for_status()\n        exit_ip = resp.json().get('origin')\n        return {\n            'statusCode': 200,\n            'body': json.dumps({'exit_ip': exit_ip})\n        }\n    except Exception as exc:\n        return {\n            'statusCode': 500,\n            'body': json.dumps({'error': str(exc)})\n        }\n```\n\nThe 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.\n\n## Node.js Example: Fetch with a Rotating Proxy\n\nNode’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.\n\n```javascript\n// package.json must include \"https-proxy-agent\"\nimport { createRequire } from 'module';\nconst require = createRequire(import.meta.url);\nconst { HttpsProxyAgent } = require('https-proxy-agent');\n\nexport const handler = async (event) => {\n  const gateway = process.env.PROXY_GATEWAY_HOST;\n  const httpPort = process.env.PROXY_HTTP_PORT;\n  const username = process.env.PROXY_USERNAME;\n  const password = process.env.PROXY_PASSWORD;\n  const proxyUrl = `http://${username}:${password}@${gateway}:${httpPort}`;\n  const agent = new HttpsProxyAgent(proxyUrl);\n\n  try {\n    const resp = await fetch('https://httpbin.org/ip', { agent });\n    if (!resp.ok) throw new Error(`HTTP ${resp.status}`);\n    const data = await resp.json();\n    return {\n      statusCode: 200,\n      body: JSON.stringify({ exit_ip: data.origin })\n    };\n  } catch (err) {\n    return {\n      statusCode: 500,\n      body: JSON.stringify({ error: err.message })\n    };\n  }\n};\n```\n\nThe agent tunnels the HTTPS request through the HTTP proxy. For SOCKS5 you would use `socks-proxy-agent` instead and build a `socks5://` URL.\n\n## Handling Cold Starts and Concurrency\n\n* **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.\n* **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.\n* **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:\n  * Request a higher proxy count on the Pro/Business plan.\n  * Use **sticky** mode for a proxy and rotate only after a configurable number of requests (tracked in a DynamoDB counter).\n  * Implement a simple semaphore (e.g., Redis‑based) to limit concurrent uses per proxy.\n\n## On‑Demand IP Rotation via API\n\nWhen 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`.\n\n```python\nimport os\nimport requests\n\ndef rotate_proxy_ip(session_id: str) -> bool:\n    api_key = os.getenv('ROPROXY_API_KEY')  # store securely\n    url = f'https://backend-api.ro-proxy.com/api/session/{session_id}/rotate'\n    headers = {'Authorization': f'Bearer {api_key}'}\n    resp = requests.post(url, headers=headers, timeout=5)\n    return resp.status_code == 200\n```\n\nInvoke 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.\n\n## Verifying the Exit IP\n\nAfter each request (or after a rotation) confirm the new IP:\n\n```python\nverify = requests.get('https://api.ipify.org?format=json', proxies=proxies, timeout=5)\nprint('Exit IP:', verify.json()['ip'])\n```\n\nOr in Node:\n\n```javascript\nconst check = await fetch('https://api.ipify.org?format=json', { agent });\nconst { ip } = await check.json();\nconsole.log('Exit IP:', ip);\n```\n\nLogging the exit IP helps you correlate blocks with specific proxies and tune rotation frequency.\n\n## Best Practices and Pitfalls\n\n* **Never hard‑code credentials** – Use environment variables or AWS Secrets Manager.\n* **Set reasonable timeouts** – Proxy latency adds to Lambda’s execution time; a 10‑second total timeout is a good starting point.\n* **Handle 407 Proxy Authentication Required** – Indicates bad username/password; fail fast and alert.\n* **Avoid DNS leaks** – Use the proxy for both HTTP and HTTPS; do not resolve hostnames locally before connecting.\n* **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.\n* **Respect target site policies** – Rotate IPs to stay under rate limits, not to evade legal restrictions.\n\n## Conclusion\n\nRunning 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.\n","https://blog-api.ro-proxy.com/api/blog/posts/running-rotating-proxies-in-aws-lambda/assets","58c1d17fba36be125c78b5707de73889a45e992d5f5dad9ac78cb107e8861377","2026-12-02T01:05:23.733029Z","2026-12-02T01:05:23.734545Z",[24,28,32],{"slug":25,"title":26,"summary":27},"using-proxies-with-playwright-for-headless-browser-automation","Using Proxies with Playwright for Headless Browser Automation","Learn how to configure rotating and sticky proxies in Playwright to run reliable headless browsers for scraping, testing, and automation while avoiding blocks and detection.",{"slug":29,"title":30,"summary":31},"configuring-rotating-proxies-nextjs-ssr-fetching","Configuring Rotating Proxies for Next.js SSR Fetching","Learn how to route Next.js server‑side data fetching through rotating proxies, handle authentication, and rotate IPs on demand using the RoProxy API.",{"slug":33,"title":34,"summary":35},"keep-proxy-credentials-out-of-logs-and-urls","Keep Proxy Credentials Out of Logs and URLs","Proxy credentials leak through URLs, debug logs, and shell history. Learn concrete patterns to keep them out of Python, Node.js, cURL, and CI.",1796251608931]