Skip to content

Durable State

One fundamental feature that separates Membrane from other serverless runtimes is that it is stateful.

You don’t need to store data in a database or file to persist it. Instead, the state of your program (the entire JS heap) is transparently and efficiently persisted every time it changes.

Managing state

To keep data around, put it in the state object, and that’s it.

import { const state: any

This object is automatically persisted by Membrane. Its type is defined by the exported State interface below.

state
} from "membrane";
const state: any

This object is automatically persisted by Membrane. Its type is defined by the exported State interface below.

state
.count ??= 0;
export function function count(): voidcount() { const state: any

This object is automatically persisted by Membrane. Its type is defined by the exported State interface below.

state
.count++;
}

Note that the entire JS heap is persistent, not just state. Since each deploy (i.e. code change) creates a new ES Module, this object serves as a convenient way to pass data from one version to the next.

In most cases Membrane will generate typing information for state based on usage. For example, from the code above, we will automatically infer the type of state to be:

type 
type State = {
    count: number;
}
State
= {
count: numbercount: number; };

As an alternative, you can also provide typing information for state by exporting a State type or interface from index.ts:

export interface State {
  State.count: numbercount: number;
}

JavaScript objects as the database

Membrane’s durability means you can treat your JavaScript objects as a database. For example, you can store some data in one call and use it again in subsequent calls.

This persistence model enables behavior that wouldn’t be possible in most serverless runtimes. For example, Promises can be await’ed indefinitely without worrying about execution timeouts. You might use an indefinite await to wait for an email handler.