DEV Community

Cover image for Lambda timeout budget: from API Gateway to SDK
Sascha Mirow-Stanitzok
Sascha Mirow-Stanitzok

Posted on Originally published at sascha-ms.de

Lambda timeout budget: from API Gateway to SDK

Most teams set their Lambda timeout once and never touch it again. Three seconds by default in the console, six seconds in the Serverless Framework, and when something stalls, someone simply bumps it to 30 or 60 seconds. That feels like a fix. In reality it only moves the problem: somewhere in the chain somebody now waits longer than necessary, and in the end the wrong layer gives up.

This topic keeps me busy because timeouts in Serverless applications almost never fail on their own. They fail as a chain. A client waits, API Gateway waits, Lambda waits, the SDK call waits – and since nobody tells the next one how much time is left, luck decides. In this article I show you how to turn a handful of numbers into a deliberate time budget that reaches from API Gateway down to the last HTTP call.

In short

A Lambda timeout is only the emergency brake; it becomes useful together with a time budget in your code that limits every downstream call with an AbortSignal. Every layer has to give up before its caller, otherwise the client gets an error while your function is still working. The biggest pitfall: without configuration, the AWS SDK for JavaScript has no request timeout at all.

What you will learn in this article

  • Why the Lambda timeout alone does not protect your requests
  • How to stagger a timeout chain cleanly from the client down to the SDK
  • A reusable time budget in TypeScript with AbortSignal
  • How to build SQS workers that do not get killed mid-work
  • The typical timeout mistakes and how to catch them in tests

Why the Lambda timeout alone is not enough

The timeout of a Lambda function is the maximum run time of one invocation. According to the AWS documentation the default is 3 seconds, adjustable in one-second steps up to 900 seconds, which is 15 minutes. The Serverless Framework uses 6 seconds if you do not set anything. When the time is up, Lambda stops the invocation hard. Your code gets no chance to clean up, send an understandable error or log what actually happened. All you see in the log is “Task timed out after 10.01 seconds”.

The real problem sits one level deeper. Your function calls other services: DynamoDB, a partner API, maybe a language model. Any of these calls can hang. And the AWS SDK for JavaScript v3 uses 0 as the default requestTimeout, which means no timeout at all. A single hanging call therefore eats the entire time budget of your function, even if a second attempt after one second would have succeeded long ago.

Then there is API Gateway. An HTTP API waits at most 30 seconds for the integration; a REST API waits 29 seconds by default (for Regional and private REST APIs you can raise that with a quota increase, possibly at the cost of your throttle limit). If your Lambda timeout is higher than what API Gateway tolerates, something ugly happens: the client receives a 503 or 504 while your function keeps running happily in the background, maybe even successfully. The Serverless Framework documentation warns about exactly this.

What a hanging call really costs

Lambda bills by run time in milliseconds. An invocation that runs into its timeout is billed for the full duration. If your partner system hangs and every request waits 30 seconds instead of giving up after 1.5 seconds, you pay up to twenty times as much, and your concurrency limit fills up with functions that do nothing but wait. On top of that, many clients retry automatically after an error. One slow request quickly turns into three.

The timeout chain: every layer shorter than its caller

The basic rule is simple: every layer has to give up earlier than the layer that calls it. Only then does the caller still have time to do something sensible with the error, for example return a partial answer, use a fallback or show the user a clear message. That is why you plan the values from the outside in.

Bar chart of the timeout chain: API Gateway 30 s, client 12 s, Lambda timeout 10 s, budget 8 s, DynamoDB 2 s, partner 1.5 s

The timeout chain in the example: every layer gives up earlier than its caller.

Layer Value in the example Why?
API Gateway (HTTP API) 30 s (fixed) Hard upper limit, you cannot go beyond it.
Client (frontend) 12 s Nobody waits longer for an availability display.
Lambda timeout 10 s Emergency brake, below the client and well below API Gateway.
Time budget in code 8 s Reserve so your code answers itself before Lambda pulls the plug.
DynamoDB per call ≤ 2 s A few milliseconds are normal; anything above is a problem.
Partner API per attempt ≤ 1.5 s Two attempts plus a pause fit easily into the budget.

The most important value in this table is the time budget in your code. Through context.getRemainingTimeInMillis() Lambda tells you at any time how many milliseconds are left. From that you derive how long each step may take at most. For example, the partner API never gets more than 1.5 seconds, but also never more than what is left overall.

Retries belong in the budget

As soon as you retry, the times multiply. Two attempts of 1.5 seconds each plus a 200 millisecond pause add up to 3.2 seconds. Three attempts with exponential backoff with jitter can quickly reach 8 seconds. So always do the math: attempts × timeout per attempt + pauses ≤ remaining budget. By the way, the SDK counts the first attempt in maxAttempts. If you want to control globally how many retries your system can afford at all, a retry budget helps as well.

The example: availability at a bike rental

As an example I use a fictional bike rental. The app calls GET /bikes/{bikeId}/availability. The Lambda function reads the bike record from DynamoDB and then asks an external workshop API whether the bike is currently being repaired. That workshop API is the shaky part: usually fast, sometimes it simply hangs.

In addition there is a worker that sends return reminders from an SQS queue. The timeout matters there too, just differently: here the goal is not to lose a message halfway through processing.

🎬 Flow: a request with a time budget – this animated diagram only runs on my site: watch it on sascha-ms.de

The goal: when the workshop API hangs, the app should still get an answer after roughly 4 seconds at the latest, then with degraded: true and the maintenance status unknown. An honest partial answer beats a 503 from API Gateway.

Step by step: building a Lambda timeout budget

Prerequisites

  • Node.js 22 and npm
  • An AWS account with permissions for Lambda, API Gateway, DynamoDB and SQS (only for deployment)
  • The Serverless Framework v4 (npm i -g serverless)
  • Basic knowledge of TypeScript and Lambda

Step 1: Create the project

Create an empty project and install the dependencies. For the tests I use Vitest.

mkdir bike-rental-timeouts && cd bike-rental-timeouts
npm init -y
npm i @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb @smithy/node-http-handler
npm i -D typescript vitest @types/node @types/aws-lambda
mkdir src test
Enter fullscreen mode Exit fullscreen mode

Step 2: The time budget as a small class

The heart of it is a class called Deadline. It remembers when the budget ends and hands each step an AbortSignal. An AbortSignal is a standard object from Node.js and the browser that lets you cancel running operations such as fetch. AbortSignal.timeout(ms) creates one that fires by itself after the given time.

// src/deadline.ts
export interface RemainingTimeSource {
  getRemainingTimeInMillis(): number;
}

export class DeadlineExceededError extends Error {
  constructor(public readonly step: string) {
    super(`Time budget exhausted before step "${step}"`);
    this.name = 'DeadlineExceededError';
  }
}

export interface DeadlineOptions {
  /** Reserve for logging, the response and cleanup (ms) */
  reserveMs?: number;
  /** Upper limit, e.g. because API Gateway gives up before Lambda (ms) */
  capMs?: number;
  /** Clock, replaceable in tests */
  now?: () => number;
}

export class Deadline {
  private readonly endsAt: number;
  private readonly now: () => number;

  constructor(totalMs: number, now: () => number = Date.now) {
    this.now = now;
    this.endsAt = now() + Math.max(0, totalMs);
  }

  static fromLambdaContext(ctx: RemainingTimeSource, opts: DeadlineOptions = {}): Deadline {
    const { reserveMs = 500, capMs = Number.POSITIVE_INFINITY, now = Date.now } = opts;
    const total = Math.min(ctx.getRemainingTimeInMillis() - reserveMs, capMs);
    return new Deadline(total, now);
  }

  remainingMs(): number {
    return Math.max(0, this.endsAt - this.now());
  }

  /** Budget for one step: at most maxMs and never more than what is left. */
  budgetFor(step: string, maxMs: number, minMs = 50): number {
    const ms = Math.min(maxMs, this.remainingMs());
    if (ms < minMs) throw new DeadlineExceededError(step);
    return ms;
  }

  /** AbortSignal that fires at the latest when the step budget runs out. */
  signalFor(step: string, maxMs: number): AbortSignal {
    return AbortSignal.timeout(this.budgetFor(step, maxMs));
  }
}

export function isTimeoutError(err: unknown): boolean {
  if (err instanceof DeadlineExceededError) return true;
  const name = (err as { name?: string } | null)?.name;
  return name === 'TimeoutError' || name === 'AbortError';
}
Enter fullscreen mode Exit fullscreen mode

Two details matter. First, the reserve: 300 to 1,000 milliseconds so your code can still log and respond after an abort. Second, the upper limit capMs. It makes sure the budget never grows beyond what your client or API Gateway can tolerate, even if somebody raises the Lambda timeout later.

Step 3: Configure the SDK client with timeouts

Now comes the part that is missing in many projects. The NodeHttpHandler from @smithy/node-http-handler has three values: connectionTimeout for establishing the connection, requestTimeout for request and response, and socketTimeout for idle time on the socket. All of them default to 0, which means unlimited.

Watch out: in current versions an exceeded requestTimeout only emits a warning unless you also set throwOnRequestTimeout: true. According to the API reference, this is because the value was wrongly treated as a socket idle timeout for a long time. Without this option your code keeps waiting even though you configured a timeout. I checked this in the example project against a deliberately hanging local server: with the option, the call aborts after 400 milliseconds with a TimeoutError.

// Excerpt from src/handler.ts
const ddb = DynamoDBDocumentClient.from(
  new DynamoDBClient({
    maxAttempts: 2,
    requestHandler: new NodeHttpHandler({
      connectionTimeout: 500,
      requestTimeout: 1500,
      throwOnRequestTimeout: true,
    }),
  }),
);
Enter fullscreen mode Exit fullscreen mode

In addition, you pass each individual call a signal from the budget via send(command, { abortSignal }). The client timeout protects every single attempt, the signal protects the call as a whole, including the SDK’s own retries.

Step 4: Call the partner API within the budget

For the workshop API I use the built-in fetch of Node.js. Every attempt takes its own signal from the deadline. If the budget is already too tight, budgetFor immediately throws a DeadlineExceededError instead of starting an attempt that could not finish anyway. fetchFn is replaceable so you can test the behavior later without a network.

// src/partner-client.ts
import { Deadline, DeadlineExceededError } from './deadline';

export interface MaintenanceStatus {
  state: 'ok' | 'in_repair' | 'unknown';
}

export interface PartnerOptions {
  baseUrl: string;
  attempts?: number;
  perAttemptMs?: number;
  fetchFn?: typeof fetch;
}

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

export async function getMaintenanceStatus(
  bikeId: string,
  deadline: Deadline,
  { baseUrl, attempts = 2, perAttemptMs = 1500, fetchFn = fetch }: PartnerOptions,
): Promise<MaintenanceStatus> {
  let lastError: unknown;
  for (let attempt = 1; attempt <= attempts; attempt++) {
    // Each attempt only gets what is left of the overall budget
    const signal = deadline.signalFor(`maintenance-attempt-${attempt}`, perAttemptMs);
    try {
      const res = await fetchFn(`${baseUrl}/bikes/${encodeURIComponent(bikeId)}/maintenance`, { signal });
      if (res.status >= 500) throw new Error(`Partner API responded with ${res.status}`);
      if (!res.ok) return { state: 'unknown' };
      return (await res.json()) as MaintenanceStatus;
    } catch (err) {
      if (err instanceof DeadlineExceededError) throw err;
      lastError = err;
      if (attempt < attempts) {
        // Short pause, but at most a quarter of the remaining budget
        await sleep(Math.min(200, deadline.remainingMs() / 4));
      }
    }
  }
  throw lastError;
}
Enter fullscreen mode Exit fullscreen mode

Step 5: The availability handler

The handler puts everything together. The budget starts with a 300 millisecond reserve and is capped at 8 seconds. If the workshop API fails, there is a partial answer. If DynamoDB itself becomes too slow, the function answers on its own with a 503 and a retry-after header before Lambda or API Gateway give up.

// src/handler.ts
import type { APIGatewayProxyEventV2, APIGatewayProxyResultV2, Context } from 'aws-lambda';
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient, GetCommand } from '@aws-sdk/lib-dynamodb';
import { NodeHttpHandler } from '@smithy/node-http-handler';
import { Deadline, isTimeoutError } from './deadline';
import { getMaintenanceStatus, type MaintenanceStatus } from './partner-client';

const TABLE_NAME = process.env.TABLE_NAME ?? 'bikes';
const PARTNER_BASE_URL = process.env.PARTNER_BASE_URL ?? 'https://maintenance.example.com';
const API_BUDGET_MS = Number(process.env.API_BUDGET_MS ?? '8000');

// Client outside the handler: reused across invocations
const ddb = DynamoDBDocumentClient.from(
  new DynamoDBClient({
    maxAttempts: 2,
    requestHandler: new NodeHttpHandler({
      connectionTimeout: 500,
      requestTimeout: 1500,
      throwOnRequestTimeout: true,
    }),
  }),
);

const json = (statusCode: number, body: unknown, headers: Record<string, string> = {}): APIGatewayProxyResultV2 => ({
  statusCode,
  headers: { 'content-type': 'application/json', ...headers },
  body: JSON.stringify(body),
});

export const handler = async (
  event: APIGatewayProxyEventV2,
  context: Context,
): Promise<APIGatewayProxyResultV2> => {
  const deadline = Deadline.fromLambdaContext(context, { reserveMs: 300, capMs: API_BUDGET_MS });
  const bikeId = event.pathParameters?.bikeId;
  if (!bikeId) return json(400, { message: 'bikeId is missing' });

  try {
    const { Item } = await ddb.send(
      new GetCommand({ TableName: TABLE_NAME, Key: { pk: `BIKE#${bikeId}` } }),
      { abortSignal: deadline.signalFor('dynamodb', 2000) },
    );
    if (!Item) return json(404, { message: 'Bike not found' });

    let maintenance: MaintenanceStatus = { state: 'unknown' };
    let degraded = false;
    try {
      maintenance = await getMaintenanceStatus(bikeId, deadline, { baseUrl: PARTNER_BASE_URL });
    } catch (err) {
      // Partner too slow or broken: an honest partial answer beats a 503 from API Gateway
      degraded = true;
      console.warn(JSON.stringify({ msg: 'maintenance_status_missing', bikeId, error: (err as Error).name, remainingMs: deadline.remainingMs() }));
    }

    return json(200, {
      bikeId,
      station: Item.station,
      available: Boolean(Item.available) && maintenance.state !== 'in_repair',
      maintenance: maintenance.state,
      degraded,
    });
  } catch (err) {
    if (isTimeoutError(err)) {
      console.warn(JSON.stringify({ msg: 'time_budget_exhausted', bikeId, remainingMs: deadline.remainingMs() }));
      return json(503, { message: 'Too slow right now, please try again in a moment' }, { 'retry-after': '2' });
    }
    throw err;
  }
};
Enter fullscreen mode Exit fullscreen mode

Step 6: Build an SQS worker that stops in time

With SQS the logic is reversed. The visibility timeout is the time during which a received message stays invisible to other consumers. AWS recommends setting it to at least six times the Lambda timeout so Lambda still has room for retries when it gets throttled. If the function timeout is larger than the visibility timeout, Lambda even rejects the event source mapping right away.

Inside the function the time budget still helps: the worker does not start a new message when there is not enough time left and reports the remaining ones back through batchItemFailures. That way nothing disappears half-processed. You switch on the partial batch response in serverless.yml with functionResponseType: ReportBatchItemFailures.

// src/worker.ts
import type { Context, SQSBatchResponse, SQSEvent } from 'aws-lambda';
import { Deadline } from './deadline';

// Estimated maximum duration per message (ms); below that we do not start a new one
const PER_MESSAGE_MS = 5000;

export async function sendReturnReminder(body: { rentalId: string }, signal: AbortSignal): Promise<void> {
  // Placeholder for the real delivery (email, push …); respects the signal
  await new Promise<void>((resolve, reject) => {
    const timer = setTimeout(resolve, 100);
    signal.addEventListener('abort', () => {
      clearTimeout(timer);
      reject(signal.reason);
    });
  });
  console.log(JSON.stringify({ msg: 'reminder_sent', rentalId: body.rentalId }));
}

export const handler = async (event: SQSEvent, context: Context): Promise<SQSBatchResponse> => {
  const deadline = Deadline.fromLambdaContext(context, { reserveMs: 1000 });
  const failures: SQSBatchResponse['batchItemFailures'] = [];

  for (const record of event.Records) {
    if (deadline.remainingMs() < PER_MESSAGE_MS) {
      // Out of time: return the message to the queue instead of being killed mid-delivery
      failures.push({ itemIdentifier: record.messageId });
      continue;
    }
    try {
      await sendReturnReminder(JSON.parse(record.body), deadline.signalFor('reminder', PER_MESSAGE_MS));
    } catch {
      failures.push({ itemIdentifier: record.messageId });
    }
  }
  return { batchItemFailures: failures };
};
Enter fullscreen mode Exit fullscreen mode

Step 7: The serverless.yml

This time I describe the infrastructure with the Serverless Framework. Pay attention to the comments: the function timeout of the API function stays clearly below the 30 seconds of API Gateway, and the visibility timeout of the queue is six times the worker timeout.

# serverless.yml
service: bike-rental-timeouts
frameworkVersion: '4'

provider:
  name: aws
  runtime: nodejs22.x
  region: eu-central-1
  memorySize: 512
  environment:
    TABLE_NAME: !Ref BikesTable
    PARTNER_BASE_URL: https://maintenance.example.com
    API_BUDGET_MS: '8000'
  iam:
    role:
      statements:
        - Effect: Allow
          Action: dynamodb:GetItem
          Resource: !GetAtt BikesTable.Arn

functions:
  availability:
    handler: src/handler.handler
    timeout: 10 # well below the 30 s of API Gateway (HTTP API)
    events:
      - httpApi: GET /bikes/{bikeId}/availability

  returnReminder:
    handler: src/worker.handler
    timeout: 60
    events:
      - sqs:
          arn: !GetAtt ReminderQueue.Arn
          batchSize: 10
          functionResponseType: ReportBatchItemFailures

resources:
  Resources:
    BikesTable:
      Type: AWS::DynamoDB::Table
      Properties:
        BillingMode: PAY_PER_REQUEST
        AttributeDefinitions:
          - AttributeName: pk
            AttributeType: S
        KeySchema:
          - AttributeName: pk
            KeyType: HASH

    ReminderDLQ:
      Type: AWS::SQS::Queue
      Properties:
        MessageRetentionPeriod: 1209600 # 14 days

    ReminderQueue:
      Type: AWS::SQS::Queue
      Properties:
        VisibilityTimeout: 360 # 6 × 60 s function timeout
        RedrivePolicy:
          deadLetterTargetArn: !GetAtt ReminderDLQ.Arn
          maxReceiveCount: 5
Enter fullscreen mode Exit fullscreen mode

Step 8: Test the behavior

Timeouts are hard to test with real clocks and real networks. That is why the Deadline gets a replaceable clock, and the partner API is replaced by a fetch that never answers. The most important test checks that a hanging call really aborts after the budget.

// test/deadline.test.ts
import { describe, expect, it } from 'vitest';
import { Deadline, DeadlineExceededError } from '../src/deadline';
import { getMaintenanceStatus } from '../src/partner-client';

const fakeClock = (start = 0) => {
  let t = start;
  return { now: () => t, advance: (ms: number) => { t += ms; } };
};

describe('Deadline', () => {
  it('subtracts the reserve and respects the upper limit', () => {
    const clock = fakeClock();
    const d = Deadline.fromLambdaContext({ getRemainingTimeInMillis: () => 10_000 }, { reserveMs: 500, capMs: 8000, now: clock.now });
    expect(d.remainingMs()).toBe(8000);
  });

  it('never gives a step more than what is left', () => {
    const clock = fakeClock();
    const d = new Deadline(1000, clock.now);
    clock.advance(700);
    expect(d.budgetFor('partner', 1500)).toBe(300);
  });

  it('throws when the budget is exhausted', () => {
    const clock = fakeClock();
    const d = new Deadline(1000, clock.now);
    clock.advance(980);
    expect(() => d.budgetFor('partner', 1500)).toThrow(DeadlineExceededError);
  });
});

describe('getMaintenanceStatus', () => {
  it('aborts a hanging partner call after the budget', async () => {
    const hangingFetch = ((_url: string, init?: RequestInit) =>
      new Promise((_resolve, reject) => {
        init?.signal?.addEventListener('abort', () => reject(init.signal?.reason));
      })) as typeof fetch;

    const started = Date.now();
    await expect(
      getMaintenanceStatus('bike-42', new Deadline(400), { baseUrl: 'https://maintenance.test', perAttemptMs: 150, fetchFn: hangingFetch }),
    ).rejects.toThrow();
    expect(Date.now() - started).toBeLessThan(600);
  });

  it('returns the status when the partner answers in time', async () => {
    const okFetch = (async () => new Response(JSON.stringify({ state: 'in_repair' }), { status: 200 })) as typeof fetch;
    const status = await getMaintenanceStatus('bike-7', new Deadline(2000), { baseUrl: 'https://maintenance.test', fetchFn: okFetch });
    expect(status.state).toBe('in_repair');
  });
});
Enter fullscreen mode Exit fullscreen mode
npx tsc --noEmit
npx vitest run
Enter fullscreen mode Exit fullscreen mode

Expected result: the type check finishes without output, and Vitest reports Tests 5 passed (5). I checked the project with TypeScript 5.9, Vitest 5.1 and AWS SDK 3.1168.

Step 9: Deploy and try it out

serverless deploy
aws dynamodb put-item --table-name <TableName> --item '{"pk":{"S":"BIKE#bike-42"},"station":{"S":"Central Station"},"available":{"BOOL":true}}'
curl -s https://<api-id>.execute-api.eu-central-1.amazonaws.com/bikes/bike-42/availability
Enter fullscreen mode Exit fullscreen mode

serverless deploy or serverless info shows you the table name and the URL. Since the workshop URL in the example points to example.com, you get an answer with "degraded": true and "maintenance": "unknown". That is exactly the intended behavior when the partner does not play along. In CloudWatch Logs you will see the entry maintenance_status_missing with the remaining budget.

Typical mistakes with Lambda timeouts

SDK calls without any timeout

The classic. Without a requestHandler configuration and without an abortSignal, every SDK call waits until Lambda ends the function. Set at least connectionTimeout and requestTimeout together with throwOnRequestTimeout: true.

Lambda timeout higher than API Gateway

A function timeout of 60 seconds behind an HTTP API gets you nothing but costs. After 30 seconds the client has long received its error, while the function keeps running. Long work belongs in an asynchronous job pattern with 202.

Visibility timeout too short

If the visibility timeout is only slightly larger than the Lambda timeout, a message can become visible again while it is still being processed. A second invocation then processes it in parallel. Stick to the factor of six and make the processing idempotent.

Returned messages end up in the DLQ

Every message the worker hands back for lack of time counts as another receive. With a tight maxReceiveCount, a perfectly healthy message can end up in the dead-letter queue this way. AWS recommends at least 5. How to monitor the DLQ and bring messages back is covered in the article about the SQS dead-letter queue.

Retries without looking at the clock

Three attempts with a 5 second timeout each do not fit into a budget of 8 seconds. Sounds obvious, yet it shows up in configurations surprisingly often because the values are maintained in different places. So derive the values from the deadline instead of hard-wiring them.

Costs and security

Shorter, deliberately chosen timeouts save money directly because Lambda bills by run time. You can play through how run time and memory size affect the bill with the Lambda cost calculator. A high timeout also opens the door to so-called denial-of-wallet attacks: anyone who deliberately triggers slow requests keeps your functions busy for a long time and drives up costs. A tight budget plus rate limiting limits the damage. Never log complete requests in timeout messages, only IDs and timings.

My take

I consider the Lambda timeout one of the most underestimated settings of all. Not because the number is hard to find, but because on its own it decides almost nothing. The real work lies in the question of who in the chain gives up when, and what happens next. Once you have thought this through properly, you automatically build better error paths.

Where I disagree: the reflex of simply raising the value on timeout errors is almost always wrong. It hides a slow third-party system instead of making it visible. Better to abort early, log cleanly and live with a partial answer. If a partner is permanently too slow, it belongs behind a circuit breaker, not behind a bigger timeout.

To be fair, the pattern has costs too: every call needs a signal, and tests with time logic are fiddlier than normal unit tests. For an internal function that only reads from DynamoDB, a correctly configured SDK client is often enough. A full Lambda timeout budget pays off where external systems are involved or people are waiting for an answer.

FAQ

What is the maximum Lambda timeout?

900 seconds, which is 15 minutes. The default is 3 seconds, in the Serverless Framework 6 seconds. For Lambda Managed Instances, asynchronous invocations and most event source mappings allow up to 90 minutes.

Why does API Gateway report an error although my Lambda function succeeded?

Because API Gateway gave up earlier. An HTTP API waits at most 30 seconds, a REST API 29 seconds by default. If your function runs longer, the client gets a 503 or 504, even if the function finishes successfully later.

Does the AWS SDK for JavaScript have a default timeout?

No. connectionTimeout, requestTimeout and socketTimeout in the NodeHttpHandler default to 0. Without your own configuration or an abortSignal, a call waits until Lambda ends the function.

How high should the SQS visibility timeout be with Lambda?

At least six times the Lambda timeout. With a 60 second function timeout that means 360 seconds. Lambda does not accept an event source mapping whose visibility timeout is shorter than the function timeout.

Your next step

Pick a function that calls an external system, sketch its Lambda timeout budget and write the timeout chain down as a table once: client, API Gateway, Lambda, every downstream call, every retry. If any layer waits longer than its caller or an SDK client has no timeout at all, you have found your first candidate. How do you deal with slow third-party systems today: raise the timeout or abort early? Let me know in the comments.

Next in the series: Previous part: DynamoDB optimistic locking: version numbers with Lambda · All parts of the series “Serverless patterns in practice” · Next part: Step Functions timeout: getting heartbeats right

All code from this article, ready to run: smirowstanitzok/sascha-ms-examples

Sources

This post was created with AI assistance.


👉 Next step: Curious what your own Lambda functions cost? Try my Lambda cost calculator – it runs right in your browser.

📬 Stay updated: New articles on serverless, AI and leading tech teams via RSS, browser push or the weekly newsletter (in German).

Originally published on sascha-ms.de. More articles on serverless, AI in everyday development and leading tech teams: sascha-ms.de/en

Top comments (0)