# Designing Stateless Functions — Serverless & Edge

Source: https://www.skillbyai.com/en/serverless-edge/se-stateless

> Keep durable state out of function instances and use globals and local disk only as safe caches.

## Design as if every instance can vanish

A function instance may be created for one request and destroyed right after it, and two consecutive requests from the same user can land on different instances. So the code must be **stateless** between invocations: anything that must survive goes to an external store such as a database, a cache like Redis, object storage or a durable workflow service. Local disk (`/tmp` on Lambda) and global variables are only a *cache*: useful for reusing a downloaded model file or a database client, never the source of truth. User sessions belong in signed cookies, tokens or a session store, not in memory. The same rule catches in-memory rate limits and counters: with 30 instances running you have 30 separate counters, each seeing a fraction of the traffic. Statelessness is exactly what lets the platform add and remove instances freely, and it is the price of not managing servers.

## A different clerk at every visit

Imagine a government office where a different clerk serves you on every visit and no clerk remembers you. Things only work if your file is kept in the central record room, or if you carry the signed papers yourself. Function instances are those clerks; the database is the record room; a signed token is the paper you carry.

## The in-memory rate limiter bug

A common mistake is limiting "10 requests per minute per user" with a `Map` in a global variable. Under load the platform runs many instances, each with its own empty `Map`, so a user can make 10 requests *per instance*. Keep counters in a shared store with atomic increments, or use the API gateway's built-in throttling.

**Quiz:** Which of these is safe to keep in a module-level variable of a function?

- [x] An SDK client configured once from environment variables
- [ ] The ID of the user making the current request
- [ ] A running total of orders that must be reported accurately
- [ ] The only copy of a file uploaded by a user

*Answer:* An SDK client configured once from environment variables. A client is safe to share and costly to recreate. Per-request data, authoritative totals and the only copy of user data belong in external storage.
