Contents

About serverless function

   Jun 26, 2023     2 min read

This is a post about serverless functions.

Serverless FunctionsWhat is a function?

It is an independent function that runs in a cloud computing environment. Serverless architecture is a way for developers to run application code without having to manage server infrastructure. Serverless functions are called only when needed, and the cloud provider handles the automatic scaling and management of infrastructure resources.

They are also event-driven, meaning they are executed when certain events occur. For example, events such as HTTP requests, message queues, and timers can trigger serverless functions. Functions perform a single function and typically have a short execution time, ranging from a few seconds to a few minutes.

Key Features of Serverless Functions
  • Simplified management: Without the need to manage server infrastructure, developers can focus on the code of the function. Infrastructure automation, scaling, monitoring, etc. are handled by the cloud provider.

  • Event-triggered: Functions are triggered by events and automatically scale if necessary. Events can come from a variety of sources and trigger serverless functions to execute.

  • Billing: Most serverless platforms charge based on the execution time and resource consumption of the function. Even when a function is inactive, no infrastructure resources are allocated, allowing for efficient cost management.

  • Scalable: Functions automatically scale as needed, so they can reliably handle increased traffic or load.

Example of a serverless function (Vercel)
const sharp = require("sharp");

module.exports = async (req, res) => {
  try {
    const { image } = req.body; // Get the image data from the body of the request.

    // We use the sharp library for image compression.
    const compressedImageBuffer = await sharp(image)
      .resize(800) // resize the image
      .toBuffer(); // return the compressed image buffer

    // Save the compressed image or return it to the client.
    // In this example, we return the compressed image directly to the client.
    res.setHeader("Content-Type", "image/jpeg");
    res.send(compressedImageBuffer);
  } catch (error) {
    console.error("Image compression error:", error);
    res.status(500).send("Image compression failed.");
  }
};
Example Description

Use the sharp library to handle image compression. After receiving the image data from the request body of the ad function, it uses sharp to resize the image and create a compressed image buffer. Finally, it returns the compressed image to the client.