AWS Lambda is consistently showing a 10-second delay before the function finally ends once the code

https://i.sstatic.net/kcB03.png

In a TypeScript Lambda API I developed, there is a specific point where the callback complete logs occur. Following those logs, the lambda takes approximately 10 seconds to respond as shown by the timestamps.

export const handler = async (event, context, callback) => {
  const { headers: { Authorization } } = event

  start = Date.now()

  const auth = await authorizer(Authorization)

  console.log(`Authorizer took ${Date.now() - start} seconds to complete`)

  if (!auth.isAuthenticated) {
    callback(null, { statusCode: 401, body: JSON.stringify("Unauthorized") })
    return
  }

  start = Date.now()
  const associations = await dynamoDb.query({
    // DynamoDB Query params
  }).promise()

  console.log(`DynamoDB query took ${Date.now() - start} seconds to complete`)

  const customers = associations.Items.map(association => association.customer)

  if (customers.length === 0) {
    callback(null, { statusCode: 200, body: JSON.stringify([]) })
    return
  }

  start = Date.now()
  const customerDetails = await pool.query(`XXXXXXXX`)

  console.log(`PostgreSQL query took ${Date.now() - start} milliseconds to complete`)

  const { rows } = customerDetails

  callback(null, { statusCode: 200, body: JSON.stringify(rows) })
  console.log('callback complete')
  return
}

Answer №1

After doing some research on AWS Documentation, I came across this information:

When utilizing callbacks in your handler, the function will continue to run until the event loop is empty or until it times out. The response won't be sent back until all tasks in the event loop are completed.

In my specific case, the PostgreSQL connection pooling mechanism was still running as part of the event loop task, causing the lambda function to execute for an additional 10 seconds.

According to the documentation, callbacks can still be used:

If the function exceeds its timeout limit, an error will be returned. To send the response immediately, you can adjust the configuration by setting context.callbackWaitsForEmptyEventLoop to false.

I personally believe that @jarmod's comment provides a cleaner approach in this situation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a String-only pattern Validator: A step-by-step guide

Below is the code I've written: ***<input type="text" placeholder="First Name" name="firstName1" [(ngModel)]="firstName" #firstName1="ngModel" required pattern="^[a-z0-9_-]{8,15}$" >*** ...

Converting Antdesign's Datepicker to Typescript

I'm having trouble figuring out how to properly annotate the dateObj parameter in the handleDateChange function that I've created. App.tsx import { useState } from 'react'; import logo from './logo.svg'; ...

What is the best way to close ngx-simple-modal in angular7 when clicking outside of the modal component?

Can anyone help me with closing the modal in my angular7 app when the user clicks outside of the modal component? I have been using the ngx-simple-modal plugin, and I tried implementing the following code: this.SimpleModalService.addModal(LinkPopupCompone ...

How can you alter the background color of a Material UI select component when it is selected?

I am attempting to modify the background color of a select element from material ui when it is selected. To help illustrate, I have provided an image that displays how it looks when not selected and selected: Select Currently, there is a large gray backgr ...

In my experience with Angular 8, I have found that the ViewChild() method is successful when used with an array, but does not work

How do I achieve the following functionality: I want a child component to have an input field and a SEND button. When the button is clicked, the value entered in the input field should be displayed in the parent component. This approach currently works: ...

Context for Apollo server has not been defined

Following the upgrade to Apollo v4 and migration guide, my project was functioning properly. However, the context is now undefined. const { url } = await startStandaloneServer(server, { listen: { port: 3000 }, context: async ({ req }) => { try ...

Creating a number of arrays based on the row of a .CSV file can be accomplished in Angular by utilizing the

Implementing an Angular template to read .CSV files and generate a table involves creating two separate files: one for the header and another for the table content. For the header CSV file: header.csv https://i.stack.imgur.com/ojMo6.png For the table da ...

Internet Explorer 11 fails to include Authorization header when making API requests

Technology Stack : ReactJS, axios, API deployed on AWS In my ReactJS application, I am making API calls to an AWS deployment using axios. The app works flawlessly in Chrome and Firefox, but encounters issues in Internet Explorer 11. All APIs have been pr ...

Having trouble installing dependencies in a React project with TypeScript due to conflicts

I encountered a TypeScript conflict issue whenever I tried to install any dependency in my project. Despite attempting various solutions such as updating dependencies, downgrading them, and re-installing by removing node_modules and package-lock.json, the ...

How to display currency input in Angular 2

Is there a way to dynamically format input as USD currency while typing? The input should have 2 decimal places and populate from right to left. For example, if I type 54.60 it should display as $0.05 -> $0.54 -> $5.46 -> $54.60. I found this PLUN ...

Issues with overloading of functions

I am facing an issue with function overloading in a scenario where a function can either return something or undefined, depending on the input parameter possibly being undefined as well. Here is an example: type Point = { x: number; y:number} function sy ...

Troubleshooting issue with applying hover effect to child divs

How come when I hover over one of the child items in my parentDiv, the background of the last childDiv changes no matter which child I place my mouse on? for (let i = 0; i < Number(height); i++) { for (let j = 0; j < Number(width); j++ ...

Cannot find property in type, and the parameter is implicitly of an unspecified type

I've been encountering this issue where I keep getting an error message. I attempted to resolve it by setting "noImplicitAny": false in tsconfig.json, but unfortunately that did not work. As for the 'Property does not exist on type' error, I ...

Confirm the identity of a user by checking their email against the records stored in a MySQL database

I am currently working on creating a user verification system using email that is stored in a mySql database and utilizing express JS. The user is required to input their email before filling out any other forms. If the email is not found in the email tabl ...

Error encountered with TypeScript when utilizing conditional types in React components

Having trouble with TypeScript error when working with conditional types in React components. The issue arises when attempting to render different component types based on a type prop and providing corresponding props for each type. type PairingCardProps ...

Guide to building a price comparison website with opencart 2.x

Currently, I am working with OpenCart for my development projects. One of the challenges I am facing involves utilizing affiliate APIs from Amazon, eBay, Flipkart, and Snapdeal. I aim to aggregate all API results onto my webpage with pagination functional ...

Tips for Embedding Icons Within a Data Grid Using Material UI and Implementing Them in Typescript

Welcome to my Data Grid! import * as React from 'react' import { DataGrid, GridColDef } from '@material-ui/data-grid' import { ProductService } from '../services/ProductServices' const columns: GridColDef[] = [ { field: &ap ...

Two-way conditional type mapping

Currently, I am working on mapping the various "data types" of an object to a corresponding "schema" type. If the property's data type is boolean, it should be mapped to the "BooleanComponents" type The code snippet below demonstrates how this can ...

Potential absence of object.ts(2531)

Currently, I am working on a project using Node.js with Typescript. My task involves finding a specific MongoDB document, updating certain values within it, and then saving the changes made. However, when I try to save the updated document, an error is bei ...

"Step-by-step guide to using InfoType or other data types from the google-cloud/dlp library in a Node.js TypeScript environment

Currently utilizing Google cloud DLP in harmony with nodejs. Once the import of DLP from "@google-cloud/dlp" is complete, I am seeking guidance on how to efficiently import InfoType, Likelihood, IInspectContentRequest, and any other types required from t ...