Writing response streaming-enabled Lambda functions - AWS Lambda

Writing response streaming-enabled Lambda functions

Writing the handler for response streaming functions is different than typical handler patterns. When writing streaming functions, be sure to do the following:

  • Wrap your function with the awslambda.streamifyResponse() decorator that the native Node.js runtimes provide.

  • End the stream gracefully to ensure that all data processing is complete.

Configuring a handler function to stream responses

To indicate to the runtime that Lambda should stream your function's responses, you must wrap your function with the streamifyResponse() decorator. This tells the runtime to use the proper logic path for streaming responses and enables the function to stream responses.

The streamifyResponse() decorator accepts a function that accepts the following parameters:

  • event – Provides information about the function URL's invocation event, such as the HTTP method, query parameters, and the request body.

  • responseStream – Provides a writable stream.

  • context – Provides methods and properties with information about the invocation, function, and execution environment.

The responseStream object is a Node.js writableStream. As with any such stream, you should use the pipeline() method.

Example response streaming-enabled handler
const pipeline = require("util").promisify(require("stream").pipeline); const { Readable } = require('stream'); exports.echo = awslambda.streamifyResponse(async (event, responseStream, _context) => { // As an example, convert event to a readable stream. const requestStream = Readable.from(Buffer.from(JSON.stringify(event))); await pipeline(requestStream, responseStream); });

While responseStream offers the write() method to write to the stream, we recommend that you use pipeline() wherever possible. Using pipeline() ensures that the writable stream is not overwhelmed by a faster readable stream.

Ending the stream

Make sure that you properly end the stream before the handler returns. The pipeline() method handles this automatically.

For other use cases, call the responseStream.end() method to properly end a stream. This method signals that no more data should be written to the stream. This method isn't required if you write to the stream with pipeline() or pipe().

Example ending a stream with pipeline()
const pipeline = require("util").promisify(require("stream").pipeline); exports.handler = awslambda.streamifyResponse(async (event, responseStream, _context) => { await pipeline(requestStream, responseStream); });
Example ending a stream without pipeline()
exports.handler = awslambda.streamifyResponse(async (event, responseStream, _context) => { responseStream.write("Hello "); responseStream.write("world "); responseStream.write("from "); responseStream.write("Lambda!"); responseStream.end(); });