DEV Community

Cover image for Guide to Implementing Function-as-a-Service: A Deep Dive into Serverless Computing
Suraj Vishwakarma for Documatic

Posted on

Guide to Implementing Function-as-a-Service: A Deep Dive into Serverless Computing

Introduction

Serverless computing is gaining more popularity nowadays, especially for launching new applications faster. Serverless does mean that you will not have a server but it is when the server is managed by a third-party application. Developers just need to write code without worrying about the underlying servers or hardware.

This serverless can be achieved with various methods one of those is FasS i.e, Function as a Service. You just write code as a function which gets deployed on the cloud. Whenever you need to execute it you just need to fire the function. We will discuss more in the article.

Implementing FasS architecture can be challenging when not knowing the principle. So, today we are going to look into implementing function as a service through the following topics:

  • What is FasS?
  • Principle of FasS
  • Benefit of FasS
  • Implementation of FasS using Supabase

Let’s get started.

What is FasS?

FasS stands for function as a service, it is a cloud computing model that allows developers to deploy a piece of code as a function to the cloud without managing the underlying technology. This function can be triggered using HTTP requests, database changes, or file uploads. By doing this, it provides the functionality of serverless as it is managed by the platforms. It is one such reason of FasS getting more recognition nowadays.

It is particularly popular for building microservices, APIs, and event-driven applications, offering a scalable and cost-effective approach to cloud computing. It can be also used for the rapid development of a prototype or quick application that does not require a lot of functionality. It provides agility to the development cycle. You can also skip a lot of work of setting up of backend and integrating with the frontend.

Principle of FasS

There are a few principles that you should follow while implementing FasS architecture. Here are those:

  • One Function One Task: Make sure that your function should perform one task. This will simplify each function and helps in managing different function based on the task.
  • Dependency Management: Make sure that the function has less dependency along with a clear declaration of each dependency. Avoid implicit dependencies to ensure predictable behavior, easier testing, and version management.
  • Error Handling: It should handle errors gracefully. It should provide proper responses or trigger retries when errors occur. It should also send a proper message back to the client when an error occurs.
  • The function should not call another function: Avoid making calls to other functions when in another function. This will reduce the isolation of each function. It can increase costs too.

The benefit of Using FasS

Let’s look into some of the benefits that you can get by using FasS:

  • Cost Effective: Clouds that provide FasS services are mostly pay-as-you-go. This means that you will be charged on the basis of the time used by your function. This can be helpful for early startups to reduce unnecessary costs despite being not used on a large scale.
  • Focus on Code: By reducing the management cost and time required for the server, it gives more time for developers to focus on the code. This streamlined development process allows for quicker development cycles and faster time-to-market for applications.
  • Modularity: As FasS tries to break code into function it encourages modularity of the code which align with the Microservice architecture. This helps developers to build complex programs by writing code in functions.
  • Scalability: FasS-providing platforms can automatically scale the function based on the demand. The edge function provided by Supabase allows multiple deployments of the function on different servers for faster execution based on their location. ## Implementing Function

You can implement functions on cloud platforms such as AWS using lambda function, Azure using Azure Functions, or Google Cloud Platform using Google Cloud Functions. These platforms are good when you use them directly these platforms in your application. But if you don’t use these platforms then it might get tricky to integrate and set the cloud for your application.

Apart from directly using the cloud services we can use applications that take away the headache of managing the cloud and we can use functions we ease. One such platform is Supabase. It is a powerful backend-as-a-service platform that allows developers to easily build scalable web applications with serverless functions and a PostgreSQL database.

It provides the facility of serverless function through a feature called edge function. The edge here means that it is globally distributed across various edges (cloud servers). So when the request is made to the function, the nearest deployed function will run and send the response. Let’s look into implementing function as a service using supabase.

Adding a project to Supabase

First, let’s set up our project on the supabase dashboard. Visit supabase.com then click on Start your project from the right of the nav bar. This will take you to the sign-in page. Enter your details for sign-in or sign-up as you required. After logging in, you will be redirected to the project page. From here, click on New project to create a project. On the Create New Project page, you will be asked to enter details of your project.

Screenshot - Create a new project page

Fill in the details of your project. Enter the project’s name as per your choice. For passwords, you can use the Generate a password for generating the password. Select the region that is nearest to the user of your project. In the free tier, you can create two projects. After filling in the details, click on Create new project. It will take a few minutes to set up the project.

Setting up the supabase CLI

We need to have supabase CLI to create, and deploy functions to the Supabase. It’s quite easy to install run the below command to install:

    npm i supabase --save-dev
Enter fullscreen mode Exit fullscreen mode

Note: Node and NPM should be pre-installed to run the command.

Now, we need to log in to the subbase in the CLI. To run any supabase command just prefix it with npx supabase then command. So for login here it is:

    npx supabase login
Enter fullscreen mode Exit fullscreen mode

This will ask for the access token. You can generate an access token from here for your project. Enter that token in the asked input.

Now, let's go to the project directory where you want to write code for your function. In the root directory, run the below command to initialize the supabase.

    npx supabase init
Enter fullscreen mode Exit fullscreen mode

After this at last we just need to provide the reference URL of your project from supabase. Here is the command for it:

    npx supabase link --project-ref your-project-ref
Enter fullscreen mode Exit fullscreen mode

Change the to your project reference. You can get the project reference URL from the Supabase's setting→ API.

Writing the function

For writing the function, first, we need to create a file for writing the function. You can create the function with the Supabase CLI. Here are the commands:

    npx supabase functions new hello-world
Enter fullscreen mode Exit fullscreen mode

This will create a file in the supabase→function→hello-world with the index.ts. You can write your function here. The index file initially will look like this:

    import { serve } from "https://deno.land/std@0.168.0/http/server.ts"

    console.log("Hello from Functions!")

    serve(async (req) => {
      const { name } = await req.json()
      const data = {
        message: `Hello ${name}!`,
      }
      return new Response(
        JSON.stringify(data),
        { headers: { "Content-Type": "application/json" } },
      )
    })
Enter fullscreen mode Exit fullscreen mode

It is just like any route file of the backend where you can get the request and send the response to the client. You can access all the API keys such as a Supaabse URL, and Anon key directly using the demo function. This can help in performing other functionality of the supabase. You can write as you will write any other file. For now, we are keeping the same. After writing the function it’s time to deploy the function.

Run the below command to deploy the function to the supabase:

    npx supabase functions deploy hello-world
Enter fullscreen mode Exit fullscreen mode

Invoking the edge function

You can invoke the edge function with the following method:

Using CURL

This can be useful in making requests from Postman or any API testing platform to test the function.

    curl --request POST 'https://<project_ref>.supabase.co/functions/v1/hello-world' \
      --header 'Authorization: Bearer ANON_KEY' \
      --header 'Content-Type: application/json' \
      --data '{ "name":"Functions" }'
Enter fullscreen mode Exit fullscreen mode

Using Supabase Client

The below code can be used to invoke the function from any file.

    const { data, error } = await supabase.functions.invoke('hello-world', {
      headers: {
        'my-custom-header': 'my-custom-header-value',
      },
      body: { foo: 'bar' },
    })
Enter fullscreen mode Exit fullscreen mode

Conclusion

We learned about the Function as a Service(FaaS) that can help in the rapid development of the project. Later we see the principle and benefits of using it. After that, we go through a guide on implementing the edge function of Supabase for implementing FaaS in the application.

The function does provide lots of flexibility to the developers as they do not have to focus more on architecture and can work on the core functionality of the application. I would love it if you would try to implement a function in your next and then see if it works for you.

I hope this article has helped you know the Function as a Service. Thanks for reading the article.

Top comments (1)

Collapse
 
psykeus profile image
psykeus

This was a great info article on FaaS. But please 🙏, fix all the FasS abbreviations to FaaS!!