82

I have some issue with API gateway. I made a few API methods, sometimes they work longer than 10 seconds and Amazon returns 504 error. Here is screenshot below:

enter image description here

Please help! How can I increase timeout?

Thanks!

Morgoth
  • 4,935
  • 8
  • 40
  • 66

12 Answers12

40

Right now the default limit for Lambda invocation or HTTP integration is 30s according to http://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html and this limit is not configurable.

Ran
  • 7,541
  • 12
  • 59
  • 72
  • 4
    Shouldn't this be 29s? – Bill Gale Jan 12 '21 at 19:17
  • 1
    @Ran why do you say it's not configurable? The document you linked to only says it cannot be increased, not that it cannot be configured. I assumed that means you can *decrease* it? – totsubo Feb 16 '21 at 01:35
  • 2
    The answer is from 2016, a lot has chanced since. At the time it wasn't.. – Ran Feb 16 '21 at 06:26
27

As of Dec/2017, the maximum value is still 29 seconds, but should be able to customize the timeout value.

https://aws.amazon.com/about-aws/whats-new/2017/11/customize-integration-timeouts-in-amazon-api-gateway/

This can be set in "Integration Request" of each method in APIGateway.

myouji
  • 346
  • 3
  • 6
  • 37
    Just FYI, the value may be set lower than 29s, not higher, unfortunately – alearg Feb 23 '18 at 11:22
  • Just to confirm, 29s is still the max value as of now. – Abhishek Upadhyaya Dec 10 '20 at 14:49
  • @Abhishek Upadhyaya where is the documentation for this? According to https://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html Maximum integration timeout is 30 seconds. – totsubo Feb 16 '21 at 01:33
  • @totsubo , you can search for "Integration timeout" - "50 milliseconds - 29 seconds for all integration types, including Lambda, Lambda proxy, HTTP, HTTP proxy, and AWS integrations." in the link (document) you shared. Its under the heading "API Gateway quotas for configuring and running a REST API". – Abhishek Upadhyaya Feb 16 '21 at 04:14
  • @Abhishek Upadhyaya Even the HTTP quota says 30 seconds. https://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html#http-api-quotas – Bodhidharma Apr 20 '21 at 18:52
  • Custom timeout between 50 and 29,000 milliseconds for WebSocket APIs and between 50 and 30,000 milliseconds for HTTP APIs. The default timeout is 29 seconds for WebSocket APIs and 30 seconds for HTTP APIs – ObjectMatrix May 28 '22 at 16:27
22

Finally in 2022 we have a workaround. Unfortunately AWS did not change the API Gateway so that's still 29 seconds but, you can use a built-in HTTPS endpoint in the lambda itself: Built-in HTTPS Endpoints for Single-Function Microservices which is confirmed to have no timeout-so essentially you can have the full 15 minute window of lambda timeout: https://twitter.com/alex_casalboni/status/1511973229740666883

For example this is how you define a function with the http endpoint using aws-cdk and typescript:

 const backendApi = new lambda.Function(this, 'backend-api', {
      memorySize: 512,
      timeout: cdk.Duration.seconds(40),
      runtime: lambda.Runtime.NODEJS_16_X,
      architecture: Architecture.ARM_64,
      handler: 'lambda.handler',
      code: lambda.Code.fromAsset(path.join(__dirname, '../dist')),
      environment: {
        ...parsedDotenv
      }
    })

    backendApi.addFunctionUrl({
      authType: lambda.FunctionUrlAuthType.NONE,
      cors: {
        // Allow this to be called from websites on https://example.com.
        // Can also be ['*'] to allow all domain.
        allowedOrigins: ['*']
      }
    })
Capaj
  • 4,024
  • 2
  • 43
  • 56
14

You can't increase the timeout, at least not now. Your endpoints must complete in 10 seconds or less. You need to work on improving the speed of your endpoints.

http://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html

E.J. Brennan
  • 45,870
  • 7
  • 88
  • 116
  • 7
    Considering the limitations with lambda and the time it takes to spinup (which can easily exceed this timeout), I'm a bit surprised that this isn't configurable. – CasualT Aug 20 '15 at 22:42
  • 6
    @CasualT: I know this is kind of old, but have you tried upping the amount of memory your Lambda function is configured for? Lambda functions scale their CPU based on the value you choose for memory. Counter-intuitive I know, but it works. Try bumping up to at least 1024MB and see if it doesn't help your startup lag. – Matt Hornsby Dec 06 '15 at 19:47
  • In my case it was more related to how long it took to have a dormant lambda spin up, and then reply, the code was literally hello-world esque in nature. (but yes, I did try with more resources) – CasualT Dec 07 '15 at 18:04
  • 1
    The cold start behavior should be limited to the first few responses. Even if you're invoking the function once a minute or even once every 5 minutes, the function should stay warm. – jackko Dec 18 '15 at 19:36
  • 9
    It's 30 seconds now, not 10 -- shows 30 on the page you provided. – Chris Johnson Dec 12 '16 at 22:28
  • 24
    I for one am astonished by the tone-deaf response coming from AWS on this limitation. How many folks are moving their databases to cloud and take their first foray into AWS stack, write a VPC-lambda API only to run into this fine-print limitation well into development phase? Back to the drawing board because AWS refuses to allow longer requests. Its ridiculous if you ask me. – nachonachoman Jul 26 '18 at 12:55
10

Lambda functions will timeout after a max. of 5 min; API Gateway requests will timeout after 29 sec. You can't change that, but you can workaround it with asynchronous execution pattern, I wrote I blog post about:

https://joarleymoraes.com/serverless-long-running-http-requests/

joarleymoraes
  • 1,891
  • 14
  • 16
  • 1
    As of 10/2018 lambda functions now have 15 min. https://aws.amazon.com/about-aws/whats-new/2018/10/aws-lambda-supports-functions-that-can-run-up-to-15-minutes/ – Bill Gale Mar 25 '21 at 00:15
5

I wanted to comment on "joarleymoraes" post but don't have enough reputation. The only thing to add to that is that you don't HAVE to refactor to use async, it just depends on your backend and how you can split it up + your client side retries.

If you aren't seeing a high percentage of 504's and you aren't ready for async processing, you can implement client side retries with exponential backoff on them so they aren't permanent failures.

The AWS SDK automatically implements retries with backoff, so it can help to make it easier, especially since Lambda Layers will allow you to maintain the SDK for your functions without having to constantly update your deployment packages.

Once you do that it will result in less visibility into those timeouts, since they are no longer permanent failures. This can buy you some time to deal with the core problem, which is that you are seeing 504's in the first place. That certainly can mean refactoring your code to be more response, splitting up large functions into more "micro service" type concepts and reducing external network calls.

The other benefit to retries is that if you retry all 5xx responses from an application, it can cover a lot of different issues which you might see during normal execution. It is generally considered in all applications that these issues are never 100% avoidable so it's best practice to go ahead and plan for the worst!

All of that being said, you should still work on reducing the lambda execution time or going async. This will allow you to set your timeout values to a much smaller number, which allows you to fail faster. This helps a lot for reducing the impact on the front end, since it doesn't have to wait 29 seconds to retry a failed request.

  • Retries are not a viable solution if your backend is already working the request. If this is a POST for example, retrying would send duplicate requests, without ever knowing the disposition of the initial one. – Bill Gale Jan 12 '21 at 19:22
  • @BillGale You are not incorrect. The context being that any request you send should return a descriptive error if it fails. In which case one can trap and implement the appropriate logic on the client side to retry or not based on the error message/nature of the failure. This was speaking strictly from the sycn processing aspect as I was mentiong that refactor for async was not required specifically. For async processing of course you would have to reconsider your approach. – NoPathInParticular Jan 13 '21 at 21:08
3

Timeouts can be decreased but cannot be increased more than 29 seconds. The backend on your method should return a response before 29 seconds else API gateway will throw 504 timeout error.

Alternatively, as suggested in some answers above, you can change the backend to send status code 202 (Accepted) meaning the request has been received successfully and the backend then continues further processing. Of course, we need to consider the use case and it's requirements before implementing the workaround

  • This answer is just a mix of information from other answers. Please avoid restating what has already been said. – Jack Bashford May 25 '19 at 22:26
  • Can you elaborate how this would work? How do you return a value to the API user? – Crashalot Oct 28 '20 at 00:35
  • When your backend being invoked to handle requests takes > 29s to spin up, the approach you advocate will not work, as the API Gateway will timeout at 29s and return a 504. – Bill Gale Jan 12 '21 at 19:18
3

As of May 21, 2021 This is still the same. The hard limit for the maximum time is 30 seconds. Below is the official document on quotas for API gateway. https://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html#http-api-quotas

vishal
  • 1,646
  • 5
  • 28
  • 56
3

Lambda functions have 15 mins of max execution time, but since APIGateway has strict 29 second timeout policy, you can do following things to over come this.

For an immediate fix, try increasing your lambda function size. Eg.: If your lambda function has 128 MB memory, you can increase it to 256 MB. More memory helps function to execute faster.

OR

You can use lambdaInvoke() function which is part of the "aws-sdk". With lambdaInvoke() instead of going through APIGateway you can directly call that function. But this is useful on server side only.

OR

The best method to tackle this is -> Make request to APIGateway -> Inside the function push the received data into an SQS Queue -> Immediately return the response -> Have a lambda function ready which triggers when data available in this SQS Queue -> Inside this triggered function do your actual time complex executions -> Save the data to a data store -> If call is comes from client side(browser/mobile app) then implement long-polling to get the final processed result from the same data store.

Now since api is immediately returning the response after pushing data to SQS, your main function execution time will be much less now, and will resolve the APIGateway timeout issue.

There are other methods like using WebSockets, Writing event driven code etc. But above methods are much simpler to implement and manage.

varad_s
  • 764
  • 1
  • 12
  • 24
2

While you cannot increase the timeout, you can link lambda's together if the work is something that could be split up.

Using the aws sdk:

var aws = require('aws-sdk');
var lambda = new aws.Lambda({
  region: 'us-west-2' //change to your region
});

lambda.invoke({
  FunctionName: 'name_of_your_lambda_function',
  Payload: JSON.stringify(event, null, 2) // pass params
}, function(error, data) {
  if (error) {
    context.done('error', error);
  }
  if(data.Payload){
   context.succeed(data.Payload)
  }
});

Source: Can an AWS Lambda function call another AWS Documentation: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Lambda.html

Community
  • 1
  • 1
CamHart
  • 3,825
  • 7
  • 33
  • 69
1

The timeout limits cannot be increased so a response should be returned within 30 seconds. The workaround I usually do :

  • Send the result in an async way. The lambda function should trigger another process and sends a response to the client saying Successfully started process X and the other process should notify the client in async way once it finishes (Hit an endpoint, Send a slack notification or an email..). You can found a lot of interesting resources concerning this topic
  • Utilize the full potential of the multiprocessing in your lambda function and increase the memory for a faster computing time
  • Eventually, if you need to return the result in a sync way and one lambda function cannot do the job, you could integrate API gateway directly with step function so you would have multiple lambda function working in parallel. It may seem complicated but in fact it is quite simple
Ghamgui Khaled
  • 364
  • 2
  • 7
0

Custom timeout between 50 and 29,000 milliseconds for WebSocket APIs and between 50 and 30,000 milliseconds for HTTP APIs. The default timeout is 29 seconds for WebSocket APIs and 30 seconds for HTTP APIs

ObjectMatrix
  • 325
  • 1
  • 3
  • 9