Why API Gateway returns 504 "Endpoint request timed out", the 29-second and 30-second integration limits for REST and HTTP APIs, what you can and cannot raise, and how to move slow work behind a job ID instead.

API Gateway answers {"message": "Endpoint request timed out"} with a 504 when the backend does not respond in time. The limit is lower than most people expect, and a Lambda timeout of 15 minutes does not help, because the gateway gives up first.
You can often raise the limit for REST APIs, but a request that regularly runs for half a minute usually belongs behind a job ID instead.
The API Gateway quotas state that raising the REST API timeout above 29 seconds might require a reduction in your Region-level throttle quota for the account. The HTTP API quotas list a fixed 30-second maximum.
Check the integration latency against the total latency in the CloudWatch metrics for the API. An IntegrationLatency close to the limit and a 504 count that matches it point at the timeout rather than at a crash. The execution logs show Execution failed due to a timeout error, and the Lambda logs show the function still running or finishing after the response was already lost.
Also check the backend's own timeouts. A load balancer or proxy behind the gateway with a shorter idle timeout produces its own 504, which looks the same to the client, so compare timestamps across the layers.
Raising it is reasonable for a Regional REST API that has occasional slow calls, for example a report that takes 40 seconds. It is a poor fit when the request time grows with data, because every client then holds a connection open, mobile networks drop long requests, and retries from impatient clients start more copies of the same work.
A request that takes longer than a few seconds is better as a job: accept it, return an ID, process it elsewhere and let the client check. The pattern needs a status table, a queue and a consumer that is safe to run twice, as in idempotent message consumers.
Encore is a backend framework with built-in infrastructure, and an asynchronous job API declares its Postgres database for job status and a Pub/Sub topic with a subscription for the slow work as code. The start endpoint publishes and returns at once, and Encore provisions the database and topic in your AWS or GCP account.

Run in your terminal to get started locally.
-- reports/migrations/1_create_jobs.up.sql
CREATE TABLE report_jobs (
id TEXT PRIMARY KEY,
status TEXT NOT NULL DEFAULT 'queued', -- queued | running | done | failed
result_url TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
started_at TIMESTAMPTZ,
finished_at TIMESTAMPTZ
);
// reports/reports.ts
import { api, APIError } from "encore.dev/api";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { Topic, Subscription } from "encore.dev/pubsub";
import { randomUUID } from "node:crypto";
const db = new SQLDatabase("reports", { migrations: "./migrations" });
interface ReportRequested {
jobId: string;
from: string;
to: string;
}
const requested = new Topic<ReportRequested>("report-requested", {
deliveryGuarantee: "at-least-once",
});
// Returns in milliseconds, far below any gateway timeout.
export const start = api(
{ expose: true, method: "POST", path: "/reports" },
async (req: { from: string; to: string }): Promise<{ jobId: string; status: string }> => {
const jobId = randomUUID();
await db.exec`INSERT INTO report_jobs (id) VALUES (${jobId})`;
await requested.publish({ jobId, from: req.from, to: req.to });
return { jobId, status: "queued" };
},
);
// The client polls this until the status is done or failed.
export const status = api(
{ expose: true, method: "GET", path: "/reports/:jobId" },
async ({ jobId }: { jobId: string }): Promise<{ status: string; resultUrl?: string }> => {
const row = await db.queryRow<{ status: string; result_url: string | null }>`
SELECT status, result_url FROM report_jobs WHERE id = ${jobId}`;
if (!row) throw APIError.notFound("no such job");
return { status: row.status, resultUrl: row.result_url ?? undefined };
},
);
const _ = new Subscription(requested, "build-report", {
handler: async (msg) => {
// Claim the job. A repeated message for a finished job matches no row, and a
// running job is claimed again only after an hour, which must be longer than
// the slowest report so a live worker is never taken over.
const claimed = await db.queryRow<{ id: string }>`
UPDATE report_jobs SET status = 'running', started_at = now()
WHERE id = ${msg.jobId}
AND (status = 'queued' OR (status = 'running' AND started_at < now() - interval '1 hour'))
RETURNING id`;
if (!claimed) return;
const url = await buildReport(msg.from, msg.to); // the slow part, minutes if needed
await db.exec`
UPDATE report_jobs SET status = 'done', result_url = ${url}, finished_at = now()
WHERE id = ${msg.jobId}`;
},
});
async function buildReport(from: string, to: string): Promise<string> {
// Query, aggregate and write the file to object storage, then return its URL.
return `https://example.com/reports/${from}-${to}.csv`;
}
encore run starts a local Postgres and runs the topic and subscription in process, so the whole flow can be tested from a test or a script before it is deployed. Locally and on deploy the start endpoint answers in milliseconds, and the gateway timeout never comes into play, since the slow work runs in the subscription. On deploy, the database runs on RDS or Cloud SQL and the topic on SNS and SQS or GCP Pub/Sub, as the AWS docs describe.
A coding agent that turns a slow endpoint into a job edits the handler, the migration and the subscription in one change and runs them locally, with no queue or IAM policy to create separately.
Best fit: Teams whose API has a few slow endpoints, such as exports and imports, that need to stop depending on a gateway timeout.
On AWS the same pattern is an API Gateway route to a Lambda function that writes the job row and sends to SQS, a second Lambda function or container consuming the queue, an RDS or DynamoDB table for status and IAM roles for each. It works well, and each piece is a separate resource to define and test. The handler code is close to what is shown above.
The backend did not answer within the integration timeout. For REST APIs the default is 29 seconds, and for HTTP APIs the maximum is a fixed 30 seconds. A Lambda function with a 15-minute timeout still gets cut off at the API Gateway limit, and the client sees a 504 even though the function keeps running.
Yes. Only Regional and private REST APIs allow it, and for those you can raise the integration timeout above 29 seconds by requesting a quota increase, which may reduce your Region-level throttle quota. Edge-optimized REST APIs cannot be raised, and HTTP APIs have a fixed 30-second maximum.
Return immediately with a job ID, do the work in a queue consumer and let the client poll a status endpoint or receive a callback. This works at any duration and keeps connections short.
With Encore, declare a Postgres table for job status, a Pub/Sub topic and a subscription that does the slow work. The start endpoint publishes and returns a job ID, and Encore provisions the database and topic in your AWS or GCP account.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.