Systemsfor Aravinda
0 / 78 core
Week 8 · Modern systems

Serverless and the edge

1.5 hours · core path

Read first: Service boundaries, DNS and CDNs

In one sitting

Serverless scales to zero and bills per invocation, at the cost of cold starts and a hard time with long-lived connections or local state. That fits spiky glue and fits a steady low-latency service badly. Edge functions have a small CPU budget and belong on auth checks, redirects, and cache keys, not on a large model or a database pool.

A function that disappears when it is idle is a good place for glue that runs in bursts. It is a bad place for a connection pool, a websocket, or a model. The edge, closer to the user and even more constrained, is a good place to reject, redirect, or pick a cache key. It is a bad place to do the work you just redirected.

Core concepts

Scale to zero means the platform runs no copy of your code when nothing is calling it. You pay per invocation instead of paying for a process that sits up. The next call may have to create an instance, load your code, and run initialization before the handler. That wait is the cold start. It sits on the user’s clock. A warm instance hides it, and warmth is not a promise. The platform can freeze or discard the process between calls.

Local state dies with the instance. An in-memory map, an in-process cache, a half-open file, a websocket: all of them belong to a process that scale-to-zero is allowed to throw away. The next invocation can land on a different instance that has never seen that state. If the state was the source of truth, you lost it. If the state was a shortcut, you pay the cold path and you must be correct without it.

Connections are local state with a victim. A pool is a set of open database connections kept so a request does not pay a handshake per query. A TCP handshake is one round trip before data on a cold connection. TLS 1.3 adds about one more. The pool hides those round trips on a long-lived process. On a function that scales to zero, the pool is created in initialization, used for a burst, and destroyed when the instance dies. A spike does not reuse one pool. It creates one pool per new instance, and every pool opens its own sockets against the same database. The function scaled. The database ate the sockets.

This is a good fit for spiky glue: a webhook, a thumbnail, a deploy hook, work that is idle most of the day and ugly for a minute. It is a bad fit for a steady low-latency service that already fills one machine. You are never at zero, so you are not collecting the idle saving, and you still pay cold starts whenever the platform replaces an instance. Service boundaries are the deeper cut. Do not split that steady service into scale-to-zero pieces because the diagram looks elastic. Put it on ordinary processes with a pool sized once.

The edge is a function with a small CPU budget that runs near the user. Three jobs fit.

  • Auth checks. Authentication is who the caller is. A signed token or a session lookup that rejects an anonymous request should happen before you spend a cross-country round trip on it. Latency numbers that matter put a floor on that trip: fiber is about 200 km per millisecond, so a 4,000 km path is about 20 ms one way and about 40 ms round trip before routers. Rejecting at the edge spends a tiny CPU budget and skips that path for traffic you were going to refuse.
  • Redirects. Send the user at the edge to the region that actually holds their data. The redirect is a small response. The heavy work happens where the data is, on a service that can keep connections.
  • Cache keys. A CDN cache key is usually the URL plus selected headers. Personalizing the key means choosing those headers on purpose. DNS and CDNs is the rest of that system: the key decides whether you hit, and a purge is eventual.

The edge is the wrong place for a large model. Inference wants GPU memory, a KV cache, and a batch. An edge isolate has a small CPU budget and no GPU. It is also the wrong place for the database pool. You would be opening sockets from every edge site into one origin, which is the connection storm with extra geography.

A websocket does not belong on a scale-to-zero function either. The server that holds the socket is stateful. The next message from that client wants the same machine, or a shared backplane. An instance that may already be gone cannot be that machine.

flowchart LR
  burst[Traffic burst] --> fn[Scale to zero function]
  fn --> pool[New connection pool]
  pool --> db[Shared database]

Read this diagram as the failure. Each new instance brings its own pool. The database is the shared resource the autoscaler does not see.

A worked example

You have a webhook that receives events from a provider you do not control, and you have an agent API that people hit all day. They want different deployments. Someone proposes one scale-to-zero function for both, with a connection pool “so the database stays fast.”

Assumptions:

  • The webhook delivers 1,000,000 events a day.
  • The burst is 50 times the average and lasts long enough to scale out. Spike factor is an assumption. This workload is spiky; a flat service would not use 50×.
  • During the burst the platform runs one event per concurrent instance. Assumption about concurrency, so you can count pools.
  • Each cold instance opens a pool of 8 connections in initialization. Assumption you would read from the driver config. The bug is the multiplication, and it survives a different 8.
  • A cold start adds 200 ms before the handler. That is an assumption about this runtime, not a vendor SLA. Measure yours.
  • The steady agent API already fills one machine at a flat rate, with a latency budget tighter than that 200 ms.
1 day = 86,400 s
shortcut ≈ 100,000 s
1,000,000 events / 86,400 ≈ 11.6/s ≈ 12 events/s average

assumption: the burst is 50×
burst arrival ≈ 50 × 12 = 600 events/s

assumption: one cold instance per concurrent event, pool of 8
sockets aimed at the database ≈ 600 × 8 = 4,800

a long-lived service of 4 processes × 8 connections = 32 sockets

Four thousand eight hundred connections against a database that is healthy at 32. The symptom is not in the function logs. Each invocation connected, did its write, and returned. The database spends memory on sockets, new connections fail, and every other service that uses that database slows down. You scaled the easy tier and stampeded the hard one.

The cold start sits in the same burst. Six hundred instances each paying 200 ms of initialization is fine if the webhook sender waits a second and the work is glue. It is not fine on the agent API. A user path budgeted at a few tens of milliseconds does not have 200 ms to create a process, and that API was already filling a machine, so scale-to-zero was not saving an idle fleet. It was adding a startup tax to a service that should have been a warm process with one pool of 32.

Fix the webhook without giving up the burst. Cap the function’s concurrency so 600 arrivals become a short queue in front of a bounded number of instances. Or push the events onto a log and let a fixed set of workers pull. The workers hold the pool. They do not scale to zero. The function, if you still want it, is glue that enqueues. Queues and logs are the buffer that turns 4,800 sockets back into 32.

There is a second local-state bug that matters if this webhook can refund or mutate. An idempotency key stored only in the instance’s memory is gone when the instance is gone, and was never visible to the sibling instance that receives the provider’s retry. The retry looks new. The charge runs twice. The key store has to live outside the function, in a database that does not scale its connection count with your cold starts. The cap on concurrency is what keeps that database reachable while you do the lookup.

Edge, same product. A user fetches a lesson page and then starts an agent turn.

At the edge you can do three cheap things. Check the session. Missing or bad, redirect to login, and do it before the 40 ms-class round trip to the origin. If the user is in the wrong region, redirect to the region that holds their data. For the public page, set a cache key of URL plus the headers that actually change the bytes, usually almost nothing. For a private progress fragment, the key has to include the identity, or one user will be served another’s fragment from a shared entry. Do not put a unique request id in the public key. Every request will miss, and the origin will send the bytes out on every view, which is the egress problem with a CDN in front of it doing nothing.

Do not run the agent turn at the edge. The turn is a loop of model calls and tools, with timeouts and a step cap, on a model server that needs GPU memory. The edge can route /agent to the regional service and refuse to do inference itself. A small CPU budget spent on a prefill will either time out or teach you that the isolate was never going to hold a batch.

Tradeoffs

Choice What you gain What you spend
Scale to zero for spiky glue No process sitting up between bursts Cold start, and no durable pool or local map
A long-lived process for steady traffic Warm pool, local cache, predictable latency You pay for the machine while it is idle
Cap concurrency or queue in front The database sees a bounded number of sockets The burst finishes later, or the sender retries
Edge auth and redirect Rejects and routes happen near the user A small CPU budget, useless for heavy work
Cache key of URL plus a few headers Public bytes hit at the edge A wrong header fragments the cache or leaks a private body
Idempotency stored in the instance Fast on one warm process The retry lands elsewhere and the side effect runs again
Websockets on the function Looks simple in a demo The next message wants a process you already froze

The idle machine and the cold start are the same trade seen from two sides. You keep a process warm because the latency budget is smaller than initialization. You let it scale to zero because the workload is absent most of the day and the caller can wait. Pick per workload. One platform setting for both the webhook and the agent API is how you get 4,800 sockets and a 200 ms tax on the same Tuesday.

Pitfalls

  • A connection pool inside a function that scales to zero. Each cold instance opens its own sockets, and the database sees concurrency times pool size. The function metrics stay green.
  • Storing idempotency or session state only in the instance. The retry arrives on another instance, finds nothing, and repeats the side effect.
  • Putting a steady service that already fills one machine onto scale-to-zero. You keep the cold start and lose the reason you accepted it.
  • Holding a websocket on an instance the platform may freeze. The client reconnects to a different instance and you have no backplane, so presence and in-flight turns vanish.
  • Running a large model, or a database pool, at the edge. The CPU budget is small, the GPU is elsewhere, and the sockets would fan in from every site.
  • A cache key that includes a unique request id. The edge never hits, and every byte comes from the origin.
  • A cache key that omits identity on a private body. The edge hits, and it hits with someone else’s data.
  • Depending on a warm start you did not pay for. The platform owed you scale-to-zero, which includes throwing the process away.

In the interview

Split the workload in the first minute. Spiky glue can scale to zero if the caller tolerates a cold start and every connection is bounded. A steady service that fills one machine should stay a warm process. Then do the pool arithmetic: concurrent instances times connections per pool, against the long-lived baseline. Say the edge does auth, redirect, and cache key, and does not do inference.

Skip a vendor’s product names and any claim about a universal cold-start time. If you use a number, call it an assumption.

The question that usually follows is where the sockets live, or what happens to an in-memory key when the second instance handles the retry. Answer with a pooler or a fixed worker fleet that does not scale to zero, and a key store outside the function. If they ask what you refuse to put at the edge, say the model and the pool, and say why the CPU budget and the fan-in make those failures predictable.

Check yourself

A burst runs 600 concurrent function instances, and each opens a pool of 8 database connections. How many sockets is that, and why is 4 processes times 8 a useful comparison?

Six hundred times 8 is 4,800 sockets aimed at the database from this burst alone. Four long-lived processes with the same pool size hold 32 sockets. The database was likely sized for a number near 32. Scale-to-zero multiplied pools by instances, and the shared database is what falls over while each function invocation looks successful.

The agent API already fills one machine and the latency budget is tighter than the cold start. Why is scale-to-zero a bad fit?

You are not idle, so you do not collect the benefit of running nothing between calls. You still pay initialization whenever an instance is replaced, and that initialization does not fit the budget. A warm process with one connection pool matches the traffic you actually have.

Which three jobs belong at the edge, and why is a model prefill not on that list?

Auth checks, redirects, and cache-key selection. Each is a small CPU decision close to the user, and a reject or a redirect can skip a long round trip. A prefill needs a GPU, a KV cache, and a batch. An edge isolate has a small CPU budget and none of that hardware. Route the agent call to the regional server.

The provider retries a webhook after a timeout. The function stored the idempotency key in memory and the first instance is gone. What happens?

The retry lands on an instance that has never seen the key, so the handler treats the event as new and repeats the side effect. A charge runs twice or a row is applied twice. The key has to live in a store outside the function, and the function’s concurrency has to stay low enough that the store’s connection count survives the burst.

A public lesson page is cached at the edge with a key that includes a unique request id. What happens to origin bytes?

Every request misses, because every key is new. The edge caches nothing useful, and the origin sends the page on every view. A public page should be keyed by the URL plus only the headers that change the body. A private fragment is the opposite problem: omit identity and you serve the wrong user’s bytes from a shared hit.

Based on: Serverless scale-to-zero and edge CPU budgets; TCP handshake and TLS 1.3; CDN cache keys.