Andrew Fribush

← All posts

Four Things That Do Not Survive Serverless

· January 25, 2027 · 8 min read

Four pieces of my SaaS starter template assumed one process that is still alive after it answers a request. On serverless functions neither half holds. A request can land on a fresh instance, many instances run at once, and an instance can be suspended as soon as its response goes out. The four were a rate limiter, a background job queue, a helper that queued jobs without waiting, and the content security policy. The commit that replaced them opens with "Fixes four issues that wouldn't survive the serverless deploy target."

The template is a Next.js 16 and Supabase codebase that apps pull from as an upstream remote, and it already targeted Vercel: its vercel.json declared a cron, and its deployment runbook said to set the cron secret. I moved the limiter counts into a Postgres table behind one atomic function, the queue's schedule onto a per-minute platform cron with a bounded handler, and the deferred insert into Next's after() hook. The dev server's eval allowance went behind a production check. Two commits followed the first: one closed the new table off from the public key, one added the claim and its recovery.

fig. 2.36.1 · all four pieces assumed one process still alive after the response: on short-lived instances the limiter counts per Map, the daily drain strands the eleventh job, the deferred insert is cut off, and the only written policy allowed eval.
ALL FOUR ASSUMED ONE PROCESS, STILL ALIVE AFTER THE RESPONSEA LINE IS A PROCESS OVER TIME: SOLID WHILE IT RUNS, DOTTED WHILE SUSPENDED. ATICK IS A REQUEST. ACCENT: WHERE IT BREAKS.ONE LONG-LIVED PROCESSMANY SHORT-LIVED INSTANCES1 RATE LIMITER123456111222ONE MAP: THE 6TH AUTH TRY IN 5 MIN ISREFUSEDA MAP EACH: THE 6TH GETS IN; 3 WARMONES LET 15 THROUGH2 JOB QUEUE04:00 · 10 JOBSCRONA DAILY 04:00 RUN DRAINS ONE BATCH OF10WOKEN ONLY BY A CRON OR A REQUEST: THE11TH JOB WAITS ANOTHER DAY3 DEFERRED ENQUEUEREQUESTRESPONSEINSERTREQUESTRESPONSEINSERT?THE EVENT LOOP RUNS THE INSERT AFTERTHE RESPONSESUSPENDED AT THE RESPONSE: THE INSERTMAY NEVER RUN, NOTHING THROWS4 SECURITY POLICYnext devscript-src 'unsafe-eval'PRODUCTIONCSP HEADER: NONETHE DEV SERVER: TURBOPACK HOT RELOADNEEDS EVALNO POLICY SHIPPED; THE ONE WRITTEN,COMMENTED OUT, ALLOWED EVAL

source: dendrite commit 05a39e4 body and its parent: infra.config.ts lines 192, 195; src/infra/rate-limit.ts line 6; vercel.json; src/infra/jobs/processor.ts line 12; src/infra/jobs/queue.ts enqueueAsync · serverlessFour.data.ts

The rate limiter that forgot on every cold start

The middleware built its limiters once, at module load. Each was a closure over one module-level Map keyed by route prefix and IP. The rules were 5 requests per 5 minutes on the auth routes, 10 a minute on checkout, 20 a minute on uploads, and 60 a minute on everything else under /api/. In one process that is the limit. On functions every instance has its own Map, so an IP whose auth requests spread over three warm instances gets 15 attempts in the window, and a cold start hands out a new Map with every count at zero.

The replacement is a table and a function. rate_limit_counters holds a key, a count and a reset time. consume_rate_limit(key, max, window_ms) does the check and the increment in one statement: an insert that, when the key exists, updates the row instead. The update takes a row lock, so concurrent requests from different instances queue on that row and each sees the count the previous one left. Once the reset time has passed, the same statement starts a new window at 1.

SQL
-- schema.sql, inside consume_rate_limit(p_key, p_max, p_window_ms)INSERT INTO rate_limit_counters (key, count, reset_at)VALUES (p_key, 1, v_now + make_interval(secs => p_window_ms / 1000.0))ON CONFLICT (key) DO UPDATE  SET count = CASE WHEN rate_limit_counters.reset_at < v_now                   THEN 1 ELSE rate_limit_counters.count + 1 END,      reset_at = CASE WHEN rate_limit_counters.reset_at < v_now                      THEN v_now + make_interval(secs => p_window_ms / 1000.0)                      ELSE rate_limit_counters.reset_at ENDRETURNING count INTO v_count;RETURN QUERY SELECT (v_count <= p_max), GREATEST(p_max - v_count, 0);

I loaded the table and function into a local Postgres 16 and called it with the auth rule's numbers (5 per 300,000 ms), alternating between two connections to stand in for two instances:

text
request 1 via connection A: t|4request 2 via connection B: t|3request 3 via connection A: t|2request 4 via connection B: t|1request 5 via connection A: t|0request 6 via connection B: f|0

Then I fired 40 calls at once against the catch-all rule (10 per minute) for one IP. Ten came back allowed and 30 refused. The row's count ended at 40, because a refused request still increments it. The window doesn't stretch, since the reset time only moves once it has passed. A daily cleanup-rate-limits cron deletes the rows whose reset time is behind them.

fig. 2.36.2 · 40 concurrent calls from one IP against a limit of 10: the Postgres row allowed 10 and refused 30; one in-memory Map per instance would allow 10 per instance.
ONE POSTGRES ROW LET 10 OF 40 THROUGH; THREE IN-MEMORY MAPS WOULD LET 30ONE CELL: ONE OF 40 CONCURRENT CALLS FROM ONE IP, LIMIT 10 PER MINUTE. ACCENT:ALLOWED.POSTGRES 16, ONE COUNTER ROW SHARED BY EVERY INSTANCE (A REAL RUN)10 ALLOWED30 REFUSED; THE ROW'S COUNT STILL ENDED AT 40IN MEMORY, A MAP PER INSTANCE (ARITHMETIC, NOT A RUN). INSTANCES:123410 OF 1410 OF 1310 OF 1330 ALLOWED, 3 TIMES THE LIMIT; 10 REFUSED

source: content/writing-sources/drafts/37-four-things-that-do-not-survive-serverless-factcheck.md, local run transcript (Postgres 16, consume_rate_limit from dendrite 0f7e1bc:schema.sql); in-memory side is arithmetic from consumeMemory in 0f7e1bc:src/infra/rate-limit.ts lines 21-40 · rateLimitRun.data.ts

The old Map is still there as the fallback. checkRateLimit() calls the database only when the service-role key is set, and drops to the in-memory path if the key is missing or the call fails:

TypeScript
// src/infra/rate-limit.ts, checkRateLimit() (trimmed)if (optionalEnv("SUPABASE_SERVICE_ROLE_KEY")) {  try {    const { data, error } = await supabaseAdmin.rpc("consume_rate_limit", {      p_key: key, p_max: max, p_window_ms: windowMs,    });    const row = Array.isArray(data) ? data[0] : data;    if (!error && row && typeof row.allowed === "boolean") {      return { success: row.allowed, remaining: row.remaining ?? 0 };    }  } catch {    // fall through to in-memory  }}return consumeMemory(key, max, windowMs);

Failing open is deliberate. The catch-all rule covers every route under /api/, so a limiter that refused requests whenever the RPC errored would turn a database hiccup into an outage of the whole API. The code comment says a transient DB issue never hard-fails the request path, and during an outage the fallback still enforces the old per-instance limit. The changelog keeps the fallback for local development.

The next commit closed the table off. The first version's comment called it "Service-role only" with "no RLS". In the next one, row-level security was on, every privilege was revoked from the anon and authenticated roles, and both functions ran as SECURITY DEFINER with execute granted only to service_role. A browser holding the public key can't read or reset anyone's counter.

The queue drained once a day

Before the change, vercel.json declared one cron: /api/infra/cron/sync-billing at 0 4 * * *. Despite the name, that route ran every registered job, and one of them was process-jobs, which called processJobQueue() with its default batch of 10. The queue moved at most 10 jobs a day. A job enqueued just after 04:00 waited almost a full day, and the eleventh job in line waited another one.

Now /api/infra/cron/jobs runs every minute and calls drainJobQueue(). It takes batches of 25 and stops at the first of three things: an empty batch, 20 batches, or 50,000 ms. That caps one invocation at 500 jobs and keeps it under the function timeout. A batch in which every job failed still counts as work, so the drain keeps going. The daily route became /api/infra/cron/run, which is what it does. The runbook notes that a per-minute cron needs Vercel's Pro plan, since Hobby allows only daily crons.

The per-minute schedule created a race the daily one never had. processJobQueue() selected pending rows in one query and marked each one running in a separate update later. Two drains a day apart never overlap. Two drains a minute apart can, and both would select the same row. The follow-up commit replaced the select with claim_background_jobs(p_limit), which picks due rows FOR UPDATE SKIP LOCKED, marks them running and increments their attempts in one statement. A second worker skips the rows the first has locked and takes the next ones. That commit also changed the daily run. It stopped running process-jobs, because the minute cron does that now. The old sync-billing path came back as its own endpoint and only syncs billing. The route's comment says it is there for "older monitors/manual invocations."

The enqueue that never happened

enqueueAsync() let a route handler queue a job without waiting for the insert:

TypeScript
enqueue(type, payload, opts).catch((err) =>  console.error(`[enqueueAsync] Failed to enqueue ${type}:`, err));

The handler returns, the response goes out, and the insert is still a pending promise. In a process that stays up, the event loop gets to it a few milliseconds later and the row lands. On a function the platform can suspend the instance once the response is sent, and the insert might finish, freeze partway, or never get its turn. The .catch doesn't fire in any of those cases, because nothing threw. On a dev server the process keeps running after the response, so every one of these inserts lands and the bug never shows.

The fix hands the insert to Next's after(), which runs a callback after the response is flushed and keeps the function alive until the callback finishes:

TypeScript
// src/infra/jobs/queue.ts, enqueueAsync()const run = () =>  enqueue(type, payload, opts).catch((err) =>    console.error(`[enqueueAsync] Failed to enqueue ${type}:`, err)  );try {  after(run);} catch {  void run();}

after() throws when it's called outside a request, from a cron handler or a script. There the code runs the insert immediately, as it did before.

The policy that allowed eval

The content security policy in infra.config.ts was a commented-out line, and the line allowed both 'unsafe-eval' and 'unsafe-inline' in script-src. next.config.ts adds the header only when that field is set, so no policy shipped at all. Turning the line on as written would have allowed eval for every visitor. A policy without eval breaks Turbopack's hot reload in the dev server, which needs it.

Now a policy ships. It sets default-src 'self', object-src 'none' and frame-ancestors 'none', allows scripts from the app and from Stripe's script host, and drops 'unsafe-eval'. next.config.ts adds the header only when NODE_ENV is production, so the dev server keeps hot reload. 'unsafe-inline' stays in script-src because Next injects inline runtime scripts and styles.

The shape of the four

All four leaned on the same three things: one process, alive after the response, with memory that persisted between requests. Read as a pre-deploy checklist:

  • Anything in process memory that must be shared across requests (limits, caches, locks) goes to a store with an atomic operation.
  • Anything scheduled goes to an external cron, with a handler bounded by batch count and time.
  • Anything deferred past the response goes through the platform's keep-alive hook.
  • Anything only the dev server needs goes behind a production check.
  • Anything a worker claims needs a way back if the worker dies.

The fifth came out of the second fix. The atomic claim marks a row running before the work starts. A worker killed mid-job by a timeout, an out-of-memory kill or a deploy leaves that row saying running, with an attempt already spent, and nothing ever picks it up again. The third commit changed claim_background_jobs() to bury stale running jobs (started more than 5 minutes ago) that are out of attempts as failed, and to reclaim the rest, spending one retry each time.

The template's changelog lists release 0.1.1 as six bullets: the four replacements, the route rename, and the orphan reclaim. An app built on the template merged all six from upstream in September.

Andrew Fribush, software and computer engineer in Austin. I build consequential systems where software meets institutions: finance, healthcare, commerce, government data, and the mechanisms that govern AI agents. Taking new engagements: hello@andrewfribush.com.

I write when a system teaches me something. Get new posts by email — no tracking, one-click unsubscribe.