Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for ways to detect AWS Lambda timeouts(few seconds before timeout) in Java and to test the same

My current Lambda function is calling a 3rd party web service Synchronously.This function occasionally times out (current timeout set to 25s and cannot be increased further) My code is something like:

 handleRequest(InputStream input, OutputStream output, Context context) throws IOException {
       try{
       response = calling 3rd party REST service
       }catch(Exception e){
          //handle exceptions
       }
}

1)I want to custom handle the timeout (tracking the time and handling few milli seconds before actual timeout) within my Lambda function by sending a custom error message back to the client. How can I effectively use the

context.getRemainingTimeInMillis()

method to track the time remaining while my synchronous call is running? Planning to call the context.getRemainingTimeInMillis() asynchronously.Is that the right approach? 2)What is a good way to test the timeout custom functionality ?

like image 495
Kodeffeminate Avatar asked Mar 03 '26 10:03

Kodeffeminate


1 Answers

I solved my problem by increasing the Lambda timeout and invoking my process in a new thread and timing out the Thread after n seconds.

        ExecutorService service = Executors.newSingleThreadExecutor();
         try {
                Runnable r = () ->{
                        try {
                           myFunction();    
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                };
                f = service.submit(r);
                f.get(n, TimeUnit.MILLISECONDS);// attempt the task for n milliseconds
            }catch(TimeoutException toe){
                //custom logic
        }
like image 175
Kodeffeminate Avatar answered Mar 06 '26 00:03

Kodeffeminate



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!