Collapsing AWS lambdas

It can be a hassle to create and maintain hyper-granular lambdas for every little function in a serverless application. Luckily, there is a way to bundle lots of functions together into a more dynamic lambda.

The basic strategy is to provide the function name in addition to the normal arguments.

// From the frontend
Backend.call('packagesService.getPackage', [list, args], {keyword: args});
// Or, more granular:
PackagesService.call('getPackage', [...], {...});

Then in the backend you have a MethodGetter class responsible for looking up methods. Here is the critical method (Python 3.6):

def getMethod(self, methodString):
parent = None
method = methodString.split('.')
allowedMethods = MethodGetter.ALLOWED_METHODS
for attr in method:
if not attr in allowedMethods:
raise ValueError('Error: attribute ' + str(attr) + ' not allowed.')
if attr is method[0]:
'''
Safe because only specific strings are allowed.
Change with caution. Arbitrary strings must not be passed to eval().
'''
parent = eval('self._' + attr)
else:
parent = getattr(parent, attr)
allowedMethods = allowedMethods[attr]
if attr is method[-1]:
return parent

There you have it.

Pros:

  • Can call N methods per 1 lambda.
  • Reduces the number of cold starts, making your application more responsive.
  • Saves you time creating/maintaining/deploying lambdas.

Cons:

  • Deployment packages can get large if those N methods have large, non-overlapping dependencies. Group your methods with caution.
Like what you read? Give John Sutton a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.