On this page

Using Statsig in Serverless Environments

Use Statsig in serverless environments like AWS Lambda, Vercel Functions, and Cloudflare Workers, including initialization patterns and cold start tips.

This guide explains how to use Statsig’s platform in serverless environments. The examples use the statsig-node SDK in a Google Cloud Function. You may need to adjust your implementation based on your cloud provider.

How Statsig runs in serverless environments

Statsig server SDKs work in serverless environments. If you can't call initialize outside of a serverless function, the SDK makes a server round trip to Statsig servers to initialize on every function invocation.

After initialization, all checks are evaluated locally within the function.

Before the function exits, flush any enqueued events (exposure and custom events) to Statsig by calling statsig.flush(). Refer to the Node.js SDK flushing documentation for the Cloudflare example.

Google Cloud Function example

The following example includes debugging information to show the cost of initializing the SDK in a cloud function. The initialize call typically takes less than a second, and subsequent function invocations don't incur this startup cost.

javascript
const statsig = require('statsig-node');

let requestsHandled = 0;
const initStart = Date.now();
let initEnd = 0;
let initialized = false;

const initializationPromise = statsig.initialize(process.env.sdkKey).then(() => {
  initEnd = Date.now();
  initialized = true;
});

exports.statsig = async (req, res) => {
  const functionStart = Date.now();
  requestsHandled++;

  if (!initialized) {
    await initializationPromise;
  }

  const alwaysOnGateValue = await statsig.checkGate({userID: 'gcp'}, 'always_on_gate');
  const functionEnd = Date.now();

  res.status(200).send({
    initStart,
    initEnd,
    functionStart,
    functionEnd,
    requestsHandled,
    initializeTime: initEnd - initStart,
    functionTime: functionEnd - functionStart,
    alwaysOnGateValue: alwaysOnGateValue,
  });
};

Alternative: Database-backed initialization

If the approach above doesn't work, you can set up a custom integration, though it requires additional setup. For example, you could create a background function that fetches your definitions from Statsig servers periodically and stores them in your database. When initializing a Statsig server SDK, fetch the values from your database instead of making a request to Statsig servers.

Reach out in Slack to discuss how to adapt Statsig to your architecture.

Fastly implementation

Some Fastly account settings enable an extra security layer that requires a custom fetch method for network requests to third-party domains. Implement a custom fetch method that uses Fastly's required backend parameter.

First, define a module in its own file that implements a global override of fetch:

javascript
export { };

const ogFetch = fetch.bind(fetch.prototype);

globalThis.fetch = (input, init) => {
  const backend: string = input instanceof URL ? input.hostname :
    input instanceof Request ? new URL(input.url).hostname :
    new URL(input).hostname;

  const initWithBackend: typeof init = { ...init, backend };

  return ogFetch(input, initWithBackend);
}

(globalThis as any).EdgeRuntime = "fastly";

Next, in the main function entrypoint, import the fetch override module before importing the Statsig SDK:

javascript
import "./providers/utils/fastly-fetch-setup";
import Statsig from "statsig-node";

Was this helpful?