Skip to content

fix(lambda-runtime-api-client): enable TCP_NODELAY on the Runtime API connection - #1190

Open
jadchaar wants to merge 2 commits into
aws:mainfrom
jadchaar:fix/runtime-api-tcp-nodelay
Open

jadchaar wants to merge 2 commits into
aws:mainfrom
jadchaar:fix/runtime-api-tcp-nodelay

Conversation

@jadchaar

@jadchaar jadchaar commented Nov 24, 2026 •

Copy link
Copy Markdown

📬 Issue #, if available: N/A

✍️ Description of changes:

On main, a small streamed response can take 40 to 60 ms longer than a buffered response, even when the handler returns in microseconds. This occurs on the first invoke in each new execution environment. It also occurs on a warm invoke that arrives less than about 45 ms after the previous invoke finished. Warm invokes with more idle time between them do not stall.

lambda_runtime_api_client builds its connector with HttpConnector::new(), and hyper-util leaves TCP_NODELAY off by default. A streaming response goes out as several small writes: the request head and metadata prelude, the 8-NUL delimiter, and the body chunks. With Nagle's algorithm on, the kernel holds a small write until the Runtime API acknowledges the earlier data. On a reused keep-alive connection, the Runtime API delays that ACK. Thus a small streamed response often waits for the delayed-ACK timer.

This change enables TCP_NODELAY on the default connector of ClientBuilder and PooledClientBuilder. The fix applies to lambda_runtime, lambda_http, lambda-extension, and the SnapStart pool reset. A connector passed to with_connector is used as-is.

The other Lambda runtime clients already send to the Runtime API with Nagle off:

  • aws-lambda-cpp sets CURLOPT_TCP_NODELAY. The Node.js and Python runtime interface clients use a bundled copy of it. The Node.js client streams responses through Node's http agent, which enables noDelay by default since Node.js 18.
  • aws-lambda-go uses net/http. Go's net package enables TCP_NODELAY on every connection.

The AWS SDK for Rust made the same change in aws-smithy-http-client 1.1.13 (changelog). Before that release, the SDK's default HTTPS client left TCP_NODELAY off, and the changelog gives the same reason for the change: "this can add roughly one RTT plus delayed-ACK time". reqwest enables TCP_NODELAY by default since 0.10.5.

Results for a small StreamResponse (main compared with this branch). The AWS Lambda rows are two runs of 100 sequential invokes for each target on provided.al2023, and show the REPORT Duration. The Function URL rows and the API Gateway rows come from different deployments. For API Gateway, the requests to main and to this branch are interleaved. The other rows are back-to-back invokes on loopback with a 28-byte body:

Runtime API Mode main p50 This PR p50
AWS Lambda, Function URL in RESPONSE_STREAM mode Streaming 43.3 to 43.7 ms (billed 44 ms) 1.1 to 1.2 ms (billed 2 ms)
AWS Lambda, API Gateway REST API with response streaming Streaming 41.9 to 43.1 ms (billed 42 to 44 ms) 0.99 to 1.03 ms (billed 1 to 2 ms)
AWS Lambda, API Gateway REST API Buffered 1.01 to 1.03 ms 1.02 to 1.05 ms
Mock server (n=1500) Streaming 49.8 ms 0.14 ms
Mock server (n=1500) Buffered 0.08 ms 0.14 ms
RIE v1.36 (n=200) Streaming 59.8 ms 0.42 ms
RIE v1.36 (n=200) Buffered 0.81 ms 0.70 ms

In review, the first invoke in a new execution environment took 41.7 to 45.9 ms on main and 1.4 to 2.5 ms with this change (11 invokes each, us-west-2).

Not every warm streamed invoke on main stalls. The API Gateway benchmark sent 10 rounds, and each round sent 10 requests back-to-back to each target. The first request of a round came after about 1 s of idle time, and it never stalled (0 of 20). Of the back-to-back requests, 61 and 70 of 90 stalled for 41 to 49 ms, and the others took about 1 ms. On the local mock, an invoke stalls when the idle time before it is less than about 45 ms, and it does not stall when the idle time is 60 ms or more. A second API Gateway test confirms this: on main, back-to-back requests stalled 32 and 30 of 50 invokes, and requests 1 s apart stalled 0 of 50. Over all 100 invokes, the mean Duration dropped from 26.8 to 31.0 ms to 1.05 to 1.32 ms, a saving of 25 to 30 ms for each invoke. The client time to last byte (p50) of the streamed response dropped from 75.6 to 75.9 ms to 39.0 to 40.9 ms. That is the same as for the buffered route, within 2 ms. The buffered differences are in the run-to-run noise of a shared host. On main, a packet capture shows that the client holds the 52-byte tail (delimiter, body, terminator) until a pure ACK arrives 49 ms later. With this change, the segments go out about 15 µs apart.

This PR also adds an integration test for response streaming. Before, the integration tests covered only buffered responses. The test calls a new /stream route (ResponseTransferMode: RESPONSE_STREAM) on the existing test API through the existing token authorizer. It makes sure that API Gateway returns the status, the headers, and the body that the function streams. The test checks behavior, not latency, so it also passes on main. The unit tests guard TCP_NODELAY.

  • The authorizer policy now allows every route in the stage of the calling API (<api-id>/<stage>/*/*, from methodArn). Before, the policy allowed only the called method, and API Gateway caches the policy by token for 300 seconds. Thus the /stream request reused the /hello policy and got 403.
  • run-integration-test.yml passes the new StreamApiEndpoint stack output to the test step. The test needs no region and no new secrets.
  • The new route uses the same resource types as the hello route. I expect that the CI role needs no new permissions. I cannot run the workflow, because it does not run on forks or on pull requests.

Testing:

  • New unit tests open a TCP connection through the connector of each builder and examine TcpStream::nodelay(). The default-connector test fails without the fix.
  • cargo +nightly fmt --all -- --check and cargo clippy --workspace --all-features -- -D warnings pass.
  • cargo test --all-features passes for lambda_runtime_api_client, lambda_runtime, lambda_http, and lambda-extension on stable and on MSRV 1.84.0.
  • cargo semver-checks reports that no semver update is required.
  • make test-rie, make test-dockerized, make test-dockerized-concurrent, and examples/check-examples.sh pass.
  • I deployed the full integration test template to a test account with sam build --beta-features and sam deploy, then ran cargo test as the workflow does: 3 passed, 0 failed, in two runs in a row. The authorizer cache had the default TTL, and the cache was empty before the first run. After the change to the authorizer (methodArn), I deployed again: 3 passed, 0 failed, on a stack with the client from main and on a stack with this branch.
  • Requests without a token return 401 on both routes.
  • A unit test covers the methodArn split in the authorizer.
  • sam validate --lint and cargo clippy -p lambda-integration-tests --all-targets -- -D warnings (with and without --all-features) pass.

Note: on Rust 1.100.0, the Cargo clippy job fails with unreachable_code at lambda-runtime/src/diagnostic.rs:89. The same failure occurs on main, and this change does not cause it.

🔏 By submitting this pull request

  • I confirm that I've ran cargo +nightly fmt.
  • I confirm that I've ran cargo clippy --fix.
  • I confirm that I've made a best effort attempt to update all relevant documentation.
  • I confirm that my contribution is made under the terms of the Apache 2.0 license.

… connection

hyper-util's HttpConnector leaves TCP_NODELAY off. With Nagle's algorithm
on, the kernel holds the small tail of a streamed response until the
Runtime API sends its delayed ACK. This adds about 40 ms to a small
streamed response.

Enable TCP_NODELAY on the default connector of ClientBuilder and
PooledClientBuilder. A connector passed to with_connector is used as-is.

Also add an integration test for response streaming through API Gateway.
@jadchaar
jadchaar marked this pull request as ready for review November 24, 2026 00:45

@bnusunny bnusunny left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. I reproduced the stall and the fix removes it.

Results. On a local mock Runtime API, streamed invokes on main took about 50 ms, and about 0.04 ms with this PR. A packet capture shows the client holding the rest of the response until a delayed ACK arrives, as described. On AWS (us-west-2, this PR's template, main client vs this PR):

main client This PR
First invoke in a new sandbox (11 each) 41.7–45.9 ms 1.4–2.5 ms
Warm invokes over 20 ms (615 each) 1 0

Question. I couldn't reproduce the 61–70% warm stalls through API Gateway, at 128 or 1024 MB. How did you measure them? The first-invoke case reproduces every time, so it may be worth leading with it in the description.

Suggestion (non-blocking). Instead of the wildcard API ID in ALLOWED_RESOURCE, build the policy from method_arn (<apiId>/<stage>/*/*). That keeps it scoped to the calling API and drops the new env var. (lambda-integration-tests/src/authorizer.rs)

CI note. run-integration-test.yml doesn't run on PRs, so the new route first runs after merge. Running it with workflow_dispatch beforehand would catch a missing role permission.

@bnusunny

Copy link
Copy Markdown
Collaborator

No action needed on the Cargo clippy failure. It is not caused by this PR.

The job fails with unreachable call at lambda-runtime/src/diagnostic.rs:89, a file this PR does not touch. It comes from the newer stable toolchain the job installs (rustc 1.100.0). Running the job's command (cargo clippy --workspace --all-features -- -D warnings) on main at 7f89224 with rustc 1.100.0 fails with the same error. It needs a separate fix on main.

@jadchaar

Copy link
Copy Markdown
Author

Thanks for digging in and reproducing it!

Warm stalls: It comes down to idle time between invokes. My script sent 10 back-to-back requests per target per round, so each function saw one invoke after ~1 s idle, then 9 in quick succession. The first one in each round never stalled (0/20), and the back-to-back ones stalled 61/90 and 70/90.

Here's a small script that shows it through API Gateway (this PR's template, us-west-2, 128 MB, 50 invokes per gap, two runs per stack):

Gap between requests main This PR
0 ms (back-to-back) 32/50, 30/50 stalled 0/50, 0/50
1000 ms 0/50, 0/50 1/50, 1/50 (20.5 and 20.7 ms, not a delayed-ACK stall)
idle_gap_stalls.py
"""Count streamed invokes that stall, for back-to-back requests and for spaced requests.

usage: TOKEN=... python3 idle_gap_stalls.py STREAM_URL FUNCTION_NAME [--gaps-ms 0,1000] [-n 50]

Sends N GET requests to a RESPONSE_STREAM API Gateway route for each client-side gap,
then reads the REPORT Duration of each invoke from CloudWatch Logs. An invoke over 20 ms
counts as a stall. Uses the default AWS credentials and region (boto3).
"""
import argparse
import os
import re
import statistics
import time

import boto3
import requests

DURATION = re.compile(r"Duration: ([\d.]+) ms")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("url")
    parser.add_argument("function")
    parser.add_argument("--gaps-ms", default="0,1000")
    parser.add_argument("-n", type=int, default=50)
    args = parser.parse_args()
    http = requests.Session()
    headers = {"Authorization": os.environ["TOKEN"]}

    for _ in range(5):  # Warm up the sandbox, the authorizer cache, and the connection.
        http.get(args.url, headers=headers).raise_for_status()

    windows = []
    for gap_ms in [int(g) for g in args.gaps_ms.split(",")]:
        time.sleep(2)
        start = int(time.time() * 1000)
        for _ in range(args.n):
            http.get(args.url, headers=headers).raise_for_status()
            time.sleep(gap_ms / 1000)
        windows.append((gap_ms, start, int(time.time() * 1000) + 1000))

    logs = boto3.client("logs")
    for gap_ms, start, end in windows:
        durations, deadline = [], time.time() + 120
        while len(durations) < args.n and time.time() < deadline:
            time.sleep(5)
            durations, kwargs = [], {}
            while True:
                page = logs.filter_log_events(logGroupName=f"/aws/lambda/{args.function}", startTime=start,
                                              endTime=end, filterPattern="REPORT", **kwargs)
                durations += [float(DURATION.search(e["message"]).group(1)) for e in page["events"]
                              if "Init Duration" not in e["message"]]
                if "nextToken" not in page:
                    break
                kwargs = {"nextToken": page["nextToken"]}
        stalls = sum(d > 20 for d in durations)
        print(f"gap {gap_ms:>4} ms: {stalls}/{len(durations)} stalled, p50 Duration {statistics.median(durations):.2f} ms")


if __name__ == "__main__":
    main()

On the local mock, the cutoff is about 45 to 50 ms of idle time before the next event.

My read: when the Runtime API answers GET /next right away, Linux treats the socket as interactive and delays the ACK on the response head, so Nagle holds the rest. A new sandbox always hits this because the event is already waiting. So warm stalls only show up on busy functions, which fits your 1 in 615. I updated the description to lead with the first-invoke case.

method_arn: Good call, done. The policy is now <api-id>/<stage>/*/* from methodArn, ALLOWED_RESOURCE is gone, and there's a unit test for the split. I deployed it, and the integration tests pass (3/3).

CI: I don't have write access, so I can't kick off workflow_dispatch. Could you push the branch here? The push trigger has no branch filter, so that alone starts a run, and each run gets its own stack:

gh pr checkout 1190
git push origin HEAD:refs/heads/pr-1190-integ

…odArn

Allow every route in the stage of the calling API (<api-id>/<stage>/*/*)
instead of reading a wildcard resource from ALLOWED_RESOURCE. This keeps
the policy scoped to the calling API and removes the environment variable.
@jadchaar

Copy link
Copy Markdown
Author

Updated based on your feedback @bnusunny, thanks for the review!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants