Best practice for API and Lambda

Hello everyone. I’m wondering what’s the best practice if you build a AWS REST API that uses different routes. Let’s assume we have 3 routes. One is for product and one for user. Basically example.com/product and example.com/user. Now I also need a GET request for a specific product. The third route is something like example.com/user?id=1

I see three different options.

  1. I create a lambda for example.com/product, for example.com/product?id=1 and for example.com/user.
    Pro: each lambda has only one responsibility
    Contra: I get a lot lambdas for bigger sites and a lot repetition because the database model, connection parameters etc. are the same, only the SQL queries are different.

  2. I handle everything inside 1 lambda.
    Pro: I have one lambda per service.
    Contra: I have multiple responsibilities, the code can be very long, hard to test and messy.

  3. create a Lambda for the user logic and a lambda for the product logic.
    Pro: I have well defined domains and I don’t repeat myself too much. I can reuse most of my code. I don’t have so many lambdas.
    Contra: I might have several responsibilities and the code can become very long.

My gut feeling says that the third option is the right one but I also like the first approach. I just dislike the repetition on approach one and the fact that I might have 20 lambdas for one application.

Additionally:
Are there best practices for the naming of lambdas?

do check lambda layers, because they can make option 1 much more manageable.

Why Lambda at all?

Pro: each lambda has only one responsibility

Why is this a pro? Is every Lambda going to be developed by a separate department entirely made of dysfunctional morons?

Are you using serverless framework or something similar? Other than config, there’s no need for repetition on option 1. You can DRY things up to your heart’s content.

I’d start with one lambda and change to more if you need em. Put all shared code in a layer

Make sure you understand SAM

I believe in single responsibility principle and would go with option 1. As others have stated use layers for common code.

If you have any serialized workflows be sure to see if lambda destinations is correct for you. For complicated workflows step functions have served me well in many solutions.

Build your solution into a single package (cloud formation, SAM) and you can management it in one place.

If it really gets unyielding think about using ECS - Fargate. Very little management required for your cluster.

Another option: host a NestJS server inside your lambda. Route all possible operations to it. Allow Nest to do routing and software layer coordination. Pros: single responsibility because each controller will handle routes. You get the ability to use inversion of control to test all of your layers. Nest will handle DB connections for you.
Cons: possibly increase your memory by a 128 mb unit. Could add an extra 100ms billable time unit since server has to initialize each cold start. You can cache the server for warm starts.

I found Lambda to be pretty inconsistent (thread dying immediately once it reaches a time limit or memory constraint). Which happened frequently for us as we used it to ingest sets of images on to our platform. While being 10x more expensive and 5x slower than even just running a bunch of threads with the same exact function on an EC2 instance.

Here’s a likely run down of what will happen if you start developing a lambda-based microservices suite today..

You will use message queues or some API gateway for triggering the event. SQS has, and API Gateway had, an arbitrary limit of only triggering a maximum of 1000 instances of lambda functions at any time. Why? because fuck you.

If you are connecting to a database, you will end up needing to run some CRUD API server to support lambda requests as lambda will quickly max out the number of connections allowed to the database, and will be significantly slower as each one will have to completely negotiate a new connection.

So you will end up using a monolithic API to accept and handle requests from lambda functions. At this point you might as well just run the actual functions (provided they are not compute intensive - such as image manipulation and ingestion) on the API server as well, maybe making an ELB environment for the API instances to scale with demand - making lambda scalability redundant.

If you are supporting a legacy application which was built using lambda functions, I can understand why you would want to continue using it, but with the rise of containerization and the ease of testing and deploying containers via ECS/EKS/whatever, building a new application on lambda functions seems like going backwards.

I would suggest using containers for your microservices at the very least so you can persist your database sessions across requests. It’ll be less resource intensive on both the DB and the services and give you a considerable speed up versus all the spin up/down a lambda function will do.

Lambda is also much harder to test, deploy, and monitor than modern solutions available today as there is really no good way of emulating the amazon-defined events that trigger them. So while you can unit test sub-functions, until you actually try it on lambda itself, you really won’t know if it is really working… Unless you have cloudwatch logs, which again… is stupid expensive and would cover the costs of running an instance or container and using logfiles.

edit: sorry for the multiple edits and rambling. Im tired and very drunk.

Thank you for the answer! Never heard of the layer function. I’ll def look it up :slight_smile:

Also I definitely have to take a look into SAM. I’ve worked a few times with the JetBrains AWS Toolkit plugin and the SAM hello world template. I found it very annoying use it :open_mouth: maybe I should start writing this from scratch :slight_smile:

Thank you for the answer! Gonna take a look into the layering

No I’ve only used the JetBrains AWS Toolkit (for a SAM template) a few times and went back to classic lambda development → write code → zip it → upload.

Others have given great advice but none have mentioned that your rest API should be restful so it’s intuitive to consumers. So your example of

GET example.com/user?id=1

I would make it look like this

GET example.com/users/1

notice plural resource name users and identifier is after the slash.

Also, I would recommend you check out AWS SAM and do one lambda for each http method for each route

Hey,

I think that there is no right or wrong. Singular makes sense because I request one specific user.

Also since I have a form on the index page that generates a dynamic url something like

example.com/user?firstname=Hello&lastname=world

Makes perfect sense. Everything after the ? is automatically interpreted as a query parameters

You just changed your example from getting a unique ID to searching. The fact that you changed the use case makes the query string parameter correct to use in this example. Getting a resource by ID using query string parameters isn’t best practices and thus a client would not expect that and would need to read the documentation wondering why the more restful

GET example.com/users/1

Isn’t working. You will also run into issues when you start to get deeper into the url. How would you get all of user 1 orders? The correct way would be

GET example.com/users/1/orders

You are right that there is no right or wrong as it will work. But this style is one is more accepted as best practices

You are absolutely right. The url with id was just for clarification of the lambda problem. I wouldn’t use this in the real world application.

Also. Please check out AWS SAM. I would highly recommend it for your use case

You should just try using Amplify, it will set up you API Gateway, Lambdas, and DynamoDB tables for you following their recommended practices.

https://aws.amazon.com/amplify/features/#

Yeah, so that’s going to not be scalable/sustainable no matter what your approach is, sorry to say.

Yeah I’ve read more about SAM and you are absolutely right. I’ll try to provide every functionality in the SAM project. Lambdas and also the API Gateway

Yeah, the function handler is just the entry point. Keep it well decoupled to avoid polluting your business logic with any deployment/runtime/lambda details, including details of the event structure, etc. you should be able to trivially lift the logic into being triggered from some other middleware, especially to just be able to test locally. Don’t fall into the trap of trying to mock out all the AWS infrastructure locally, decouple your code instead.