Using Bearer with Serverless Functions

Did you know that you can use Bearer with serverless functions? While serverless, or cloud functions, might not be your first choice for making API calls they can be a great way to proxy API requests or even act as a lightweight API gateway. They also offer a great way to bring some of the benefits of Bearer into the Jamstack.

The set up process is similar to installing the Bearer Agent into a traditional app, but there are a few things to watch out for. In this article, we'll explore some best practices and tips to help you get the most out of using Bearer with cloud functions.

Initialize inside the handler

Cloud functions, like AWS Lambda, are mostly stateless, with some exceptions, meaning that actions need to happen inside the handler. To make sure the Bearer Agent initializes, it needs to be set up inside the handler.

cont Bearer = require('@bearer/node-agent')

exports.handler = async function(event, context) {
	await Bearer.init({ ... })
	// ...
}

We recommend combining this approach with the next one, to ensure your codes isn't dependent on any external factors.

Avoid failures with proper error handling

Always wrap the Bearer Agent's initialization in a try/catch block, or similar pattern. Here are examples for Node, Ruby, and Python.

In Node.js, use try-catch-finally:

try {
  await Bearer.init({ ... })
} catch (e) {
  console.warn(e)
} finally {
// Your API calls here
}

In Python, use try-except-finally:

try:
	bearer_agent.init(secret_key="YOUR_SECRET_KEY")
except:
	print('Failed to initialize agent')
finally:
	# Add your API calls here

In Ruby, use begin-rescue-ensure:

begin
	Bearer.init_config do |config|
		config.secret_key = "YOUR_BEARER_SECRET_KEY"
	end
rescue
	# Handle error
ensure
	# Add your API calls
end

Using an approach like try-catch-finally ensures that your code will wait for the agent to initialize, but still run if there is an error. This is a great practice in non-serverless environments as well, and especially useful when using async/await in Node.js.

Make sure your bundle includes dependencies

Confirm that your code bundle includes the Bearer Agent and any other third-party libraries.

Depending on the workflow you are using to push changes to cloud functions, you may need to confirm that the service installs any necessary dependencies. The same goes for anyone using the "zip and upload" approach to AWS. In most cases, modern workflows will install any dependencies included in a manifest (package.json for Node.js, requirements.txt for Python, or Gemfile for Ruby.

Increase the max-timeout for complex actions

Actions like automated retry remediations, large request payloads, and other longer actions often need more time to excecute. The default invocation timeout for providers is normally six seconds or less. Make sure to adjust the duration of your functions to suit the specific use case.

For example, if you know you plan to use a retry remediation with a backoff strategy, increase the timeout on the serverless function to accomdate the multiple requests, delays between requests, and the potential success condition's processing time.

If you're using the serverless framework, this is set in the serverless.yml file. In the AWS console this is in the function's configuration page, or using the SAM or AWS CLIs. Other providers, like Google Cloud and Azure, offer similar ways to configure the timeout value.

Many providers charge by invocation and duration, so plan and adjust these timeouts to fit your needs.

Expect a slight delay on cold-start

Cloud functions have a concept of being "cold" and "hot". Unlike a traditional application that is always running, the container housing the function needs to "boot up" before it is used. This delay is often minor, but can be noticeable.

Since we recommend initializing the Bearer Agent early on when your application starts, this means your function will need to wait for the initial connection to Bearer before it can perform its core task. When combined with the response time of the API call, and the round-trip to the part of your application that calls the function, this delay has the potential to result in a poor user experience.

Bringing it all together

In this post, we examined some best practices for connecting Bearer with your serverless functions. These tips will allow you to use Bearer with services like Azure's Serverless Compute Functions, AWS Lambda Functions, Google Cloud Functions, and even services built on top of these like Vercel's serverless APIs.

You may also like

Consume APIs. Stay in Control.

Monitor, track performance, detect anomalies, and fix issues on your critical API usage.

Learn more Schedule a Demo