Book a free call

Serverless Best Practices: What Works in Production

Serverless works well when functions stay small, state lives outside them, and costs are watched. These are the practices that hold up in production.

Hertiv engineering teamReviewed by a senior engineer
7 min read
Serverless Best Practices: What Works in Production
On this page

Short answer

Serverless best practices are the habits that keep functions fast, cheap and easy to fix once real users depend on them. The core idea is simple: each function does one small job, keeps no state of its own, and starts quickly. Teams that follow that idea spend their time on the product instead of on servers, timeouts and surprise bills.

What are serverless best practices?

Serverless best practices are the working habits that keep a serverless system reliable in production. In serverless computing, the cloud provider runs your code when an event happens, such as a web request or a file upload, and you pay for the time the code runs instead of for a server that sits idle.

The practices matter because serverless hides the server but not the trade-offs. A function that is too big starts slowly, a function that keeps data in memory loses it, and a function that calls other services without limits can run up a bill. The habits below stop those problems before users notice them.

Use this table as a quick reference for the practices in this article.

Practice What it means What goes wrong without it
One job per function Each function does a single task Slow starts and tangled code
State outside the function Data lives in a database or queue Lost work when the function ends
Short timeouts Functions stop after seconds, not minutes Hung calls and rising bills
Small packages Only the code and libraries needed Cold starts that users feel
Idempotent handlers Running twice gives the same result Double charges and duplicate orders
Logs and alarms Every run is traced and watched Failures found by customers first

None of these need special tools. They are design choices, and they are cheapest to make before the first user arrives.

How should you design a serverless function?

Design each function around one job with a clear input and a clear output. A function that takes an order, checks stock, charges the card and sends the email does four jobs, and a failure in any one of them is hard to find. Four small functions, each doing one of those jobs, are easier to test, easier to fix and easier to reuse.

Keep the function short and its package small. Import only the libraries the function uses, and keep large files, such as models or reference data, in storage the function reads on demand. A small package starts faster, and a fast start matters most for the functions users call directly, such as login or checkout.

Set a timeout that fits the job, usually seconds rather than minutes, and set a memory size that fits the work. A function that waits on a slow database should fail fast and report the problem, not sit for the full timeout on every call. For background on the model itself, see what is serverless.

How do you keep cold starts under control?

A cold start is the delay when a function runs for the first time in a while and the provider has to load its code. Users feel it as a slow first click, often a second or more, while later clicks are fast. The delay comes from loading the package and starting the runtime, so the fixes are about size and timing.

The simplest fix is a smaller package and a lighter runtime. A function written in a fast-starting language with few dependencies starts quicker than one that loads a large framework. Keep the code the function runs at start-up to a minimum: connect to services lazily, load reference data only when needed, and avoid work that runs before the first request is handled.

For the functions where a slow first call hurts, such as a login or a payment page, keep a small number of instances warm, or choose a provider setting that does so. Warm instances cost money, so use them only where the delay matters. Measure the cold-start time on real traffic before paying to fix it, because a function called every few seconds may never go cold at all.

Where should state and data live?

State should never live inside a function. A function instance can be stopped at any time, and the next call may run on a different instance with no memory of the last one. Anything that must survive, such as an order, a session or a counter, belongs in a database, a cache or a queue that lives outside the function.

Choose the store by the job. A database holds records that must last, a cache holds data that is read often and can be rebuilt, and a queue holds work that can wait, such as sending an email or resizing an image. Passing work through a queue also protects the system: if the email service is slow, orders still go through and the emails catch up later.

Make every handler idempotent, which means running it twice gives the same result as running it once. Queues and retries can deliver the same event more than once, and a handler that charges a card or creates an order twice will cause real damage. A simple check, such as an order number already seen, stops the second run from doing the work again.

For the wider shape of a serverless system, see serverless application architecture.

How do you control cost and stay secure?

Serverless cost follows usage, which is good until a mistake multiplies it. A function that retries forever, a loop that calls itself, or a public endpoint with no limit can turn a small bug into a large bill. Set a spending alarm before launch, limit retries with a small number and a delay, and give each function only the permissions it needs.

Security starts with those permissions. A function that reads product data should not be able to write to the payment table, and a function that sends email should not be able to read customer records. Short-lived credentials, secrets kept in the provider's secret store rather than in code, and no credentials in logs are the basics, and they cost nothing to set up.

Watch the bill the way you watch errors. Look at cost per function each week, and check the most expensive ones first. A function that costs ten times more than the rest usually has a retry loop, a missing cache or a query that scans a whole table. Compare the approaches in serverless vs microservices if you are still choosing the shape of the system.

Example (hypothetical): a checkout function that stays fast

Example (hypothetical): a small shop runs checkout as a serverless function that is called 1,000 times a day. Each call runs for about 0.4 seconds on average, so total compute is 1,000 times 0.4, which is 400 seconds, or about 7 minutes, of compute a day. The function is small, uses 512 MB of memory and has a 10-second timeout.

One week, the payment service slows down and some calls take 9 seconds. Because the timeout is 10 seconds, the slow calls still finish, but the team sees the delay in the logs and adds a 3-second limit on the payment call, so a slow payment fails fast and the shopper sees a clear message instead of a spinning page. The total compute for the week barely changes, because the slow calls stop hanging.

The same shop also makes the handler idempotent. When the queue delivers one payment event twice, the second run sees the order number already recorded and does nothing, so no shopper is charged twice. The check is five lines of code and it prevents the worst failure a checkout can have.

What are the common mistakes?

The most common mistake is treating a serverless function like a small server. Functions that keep state in memory, run for minutes, or hold a database connection open across calls will fail in ways that look random, because each call may land on a fresh instance. Design for a fresh start on every call and the random failures go away.

  • Putting several jobs in one function so a failure is hard to trace
  • Storing orders, sessions or counters in function memory
  • Letting a function retry without a limit, which multiplies cost
  • Shipping a large package with libraries the function never uses
  • Giving every function full access to every database and service
  • Deploying without logs, traces or a spending alarm
  • Testing only on a laptop and never under real traffic

Most of these are fixed by the same habit: keep functions small, keep state outside them, and watch what happens in production every day. Serverless rewards teams that measure real runs instead of guessing, and the first week of logs usually shows exactly which practice to fix next.

Key takeaways

  • One job per function keeps code fast, testable and easy to fix.
  • State belongs in a database, cache or queue, never in function memory.
  • Small packages and light start-up work keep cold starts short.
  • Idempotent handlers stop retries from charging or ordering twice.
  • Least-privilege permissions and a spending alarm stop small bugs becoming big bills.

Frequently asked questions

What is the first serverless best practice to adopt?

Make each function do one job. It is the practice the others build on, and it makes testing, fixing and reusing code easier from the first week, while keeping every later change smaller and safer.

How do I reduce cold starts in serverless functions?

Use a small package, a light runtime and lazy loading of data and connections. For user-facing functions where delay hurts, keep a few instances warm and measure the result before spending more on warm instances.

Should serverless functions connect directly to a database?

They can, but the connection should be short-lived and pooled where the provider supports it. Long-lived connections across calls do not work well when instances start and stop often, which is normal for most workloads.

How do I stop a serverless function from running up a big bill?

Set a spending alarm, limit retries, give each function only the permissions it needs, and check cost per function each week. Most surprises come from retry loops or missing caches.

What does idempotent mean for a serverless function?

It means running the handler twice gives the same result as running it once. It protects against duplicate charges and orders when a queue delivers the same event more than once.

Is serverless cheaper than running a server?

It depends on the workload. Steady traffic can be cheaper on a server, while spiky or light traffic is often cheaper serverless. Compare real usage on your own traffic, not on a benchmark, before choosing.

Found this useful? Share it.
Hertiv engineering team

Written from projects we build for clients: software products in production. Every post is reviewed by a senior engineer before publishing and updated when practice changes.

About HertivHow we work

Moving a workload to serverless and want it to hold up?

A senior engineer replies within one business day. Or see our Cloud Services service.

Book a free call

Keep reading

All posts

Tell us what you want to build

A senior engineer reads every request and replies within one business day with questions, a rough range, or a call link.

  • NDA on request before any details
  • You own all code, models and IP
  • US, UK and EU time-zone overlap

Your email app should open with your message ready to send. If it does not, write to [email protected].

Prefer email? Write to [email protected]
Estimate costBook a call