Serverless Hosting Explained
Understand how serverless functions run, what they cost, where cold starts and limits bite, and when to use them.
Key takeaways
- A serverless platform runs your code on demand and scales the number of copies automatically.
- Functions should be stateless, with anything worth keeping stored in an external service.
- The first request to a new copy can be slower, which is known as a cold start.
- Metered billing suits uneven traffic and can cost more than a fixed server under steady heavy load.
- Spending limits, concurrency caps and idempotent code protect you from runaway bills and duplicated work.
Serverless hosting lets you run code without renting or managing a particular server. You upload a function or a container, the platform starts it when a request or event arrives, runs as many copies as the load calls for and stops them when the work is done. You usually pay for what runs rather than for a machine sitting idle.
Servers still exist. The name means that patching, capacity planning and process supervision are the provider's problem. In exchange, you accept the platform's rules about how long code may run, what it can remember and how it connects to other things.
How a request is handled
You write a function: a piece of code with an entry point that receives an input and returns a result. You connect it to a trigger, such as an HTTP request, a file landing in storage, a message on a queue or a timer.
When the trigger fires, the platform looks for an idle running copy, called an instance or execution environment. If one exists, it handles the request. If not, the platform creates one, loads your code and then calls it. After a quiet spell, idle instances are removed.
A basic HTTP function in JavaScript often looks something like this, though each platform has its own signature:
export default async function handler(request) {
const name = new URL(request.url).searchParams.get("name") ?? "visitor";
return new Response("Hello, " + name, {
headers: { "content-type": "text/plain; charset=utf-8" }
});
} Check your provider's documentation for the exact form, supported languages and runtime versions.
The wider family
"Serverless" covers more than functions.
- Functions as a service run small units of code per event.
- Serverless containers accept a container image and scale it with demand, which allows any language or framework that fits in a container.
- Edge functions run in many locations close to visitors, usually with a tighter set of capabilities. See edge computing.
- Serverless databases, queues and storage scale and bill by use, so the rest of the application can follow the same model.
A common website combines static files for the pages with a few functions for the parts that need code, such as a contact form, a webhook from a payment provider or a search endpoint.
Statelessness, and where the data goes
An instance may vanish after any request, and two requests from the same person may land on different instances. Variables held in memory and files written to local temporary disk cannot be relied on.
Put lasting data somewhere external: a database, object storage, a key-value store or a cache service. Sessions belong in a signed cookie or a shared store.
Databases need particular care. A traditional database accepts a limited number of connections, and a sudden burst of function instances can use them all up. Remedies include a connection pooler between the functions and the database, a database that offers an HTTP interface, reusing a connection across warm invocations and capping how many instances may run at once.
Cold starts and other limits
A cold start is the delay while a new instance is prepared. Its size depends on the platform, the language, how much code and how many libraries must load, and what your startup code does. Smaller packages and less work at startup help. Some providers offer to keep a number of instances ready for an extra charge.
Other limits to read before designing:
| Limit | What it affects |
|---|---|
| Maximum run time | Long jobs must be split or moved elsewhere |
| Memory and CPU settings | Speed and cost of each call |
| Request and response size | Large uploads often need to go straight to storage |
| Concurrency | How many requests run at once before others wait or fail |
| Temporary disk | Scratch space only, not storage |
Numbers differ between providers and change, so take them from current documentation.
Long-lived connections such as WebSockets also need platform support, since a function that ends after responding cannot hold a connection open on its own.
Events can arrive twice
Many event sources promise to deliver each message at least once. If your function times out after doing its work but before reporting success, the event may be sent again.
Design for that by making operations idempotent, meaning that repeating them has no further effect. Record an identifier for each processed event and skip it if seen. Use payment or order identifiers to prevent double charging. Send failures that keep recurring to a separate dead-letter queue for a person to look at. Message queues and event-driven systems goes further.
How the bill works
Charges typically combine a count of invocations with the time and memory each one consumes, plus related services: gateways, logs, storage and data transfer.
This shape favors quiet or spiky workloads. A form handler used twenty times a day costs very little, while a server for the same job would be billed around the clock. A service that is busy every second may be cheaper on a fixed machine.
A worked example in plain units: 100,000 calls a day, each using half a second, adds up to 50,000 seconds of run time daily, a little under 14 hours of compute. Multiply by your memory setting and the provider's rates to estimate cost, then add the surrounding services.
Waiting counts too. If your function spends most of its time waiting for a slow outside API, on many platforms you are billed for the wait.
Guarding against surprises
Automatic scaling applies to mistakes and abuse as much as to success.
- Set a maximum concurrency on each function.
- Create budget alerts, and learn whether your platform can also enforce a hard stop.
- Put rate limiting in front of public endpoints.
- Avoid loops, such as a function that writes a file into the same storage location that triggers it.
- Set timeouts on calls to other services.
On security, give each function only the permissions it needs, keep secrets in the platform's secret store or environment settings, validate every input and keep dependencies updated. The provider secures the platform; your code and its permissions are yours.
Debugging and portability
You cannot log into the machine, so logs, metrics and traces are your eyes. Log a request identifier and the outcome of each external call. Run functions locally where the provider offers an emulator, but test in a real staging environment, since permissions and triggers behave differently there.
Triggers, permissions and configuration are specific to each platform. To keep moving possible, put your real logic in ordinary modules and let a thin wrapper translate the platform's input and output. Containers are more portable than function-specific formats.
Putting a first function into production
A contact form on a static site shows the whole pattern in miniature. The browser sends the form fields to an HTTP function. The function checks them, hands a message to an email service and returns a short success or error response.
A careful version does these things in order:
- Accept only the method you expect, normally POST, and reject anything else.
- Limit the size of the input, and check that required fields exist and look reasonable.
- Apply a spam control, such as a rate limit or a challenge, before doing any paid work.
- Send the message from your own authenticated domain, placing the visitor's address in the reply-to field.
- Return a clear response without echoing internal error details.
- Log that an attempt happened, leaving the message contents out of the logs where you can.
If the page and the function live on different hostnames, the browser also applies cross-origin rules, so the function must send the right headers; CORS explained shows how. Allow only your own site's origin instead of every origin, and remember that this rule governs browsers. It does not stop scripts from calling your endpoint directly.
Deploying and rolling back
Define functions, triggers and permissions in files kept in version control, using your platform's tool or a general infrastructure tool. Clicking settings into a dashboard works for an experiment and becomes hard to reproduce within weeks. Infrastructure as code describes the approach.
Keep separate development and production environments with separate secrets and data. Many platforms keep numbered versions of a function and let you shift traffic between them, which makes it possible to send a small share of requests to a new release first and return to the old one if errors rise.
Watch runtime versions too. Platforms retire old language runtimes on a published schedule, so even a function you have not touched in a year needs occasional attention.
When to choose it
Good first projects include form handlers, image resizing after upload, scheduled reports, webhook receivers and small APIs. Poor ones include game servers, long video encoding on tightly limited functions and applications that assume a writable local disk. If you are weighing the broader options, shared, VPS, dedicated and cloud hosting compares the traditional choices, and many sites sensibly use one of those alongside a handful of functions.