Managed Data
FullStacked Cloud runs PostgreSQL, Redis, MongoDB, S3-compatible object storage (RustFS) and FullStacked P2P (realtime presence, messaging, shared state and audio/video between the users of an app) instances, each in its own container. A project reaches an instance linked to it through fullstacked/tunnel: register the tunnels hub with the user's AUTH_TOKEN and the instance's data token, then point the standard npm driver at the returned name. The runtime keeps a WebSocket session to the hub for that tunnel and carries every driver connection as a stream on it. Credentials come from process.env and match the current user's access (read-write or read-only), so the same code serves every user.
Setup
- Provision an instance and link it to the project: Console (https://c.fullstacked.cloud, Data, then Project, Linked data) or MCP (
data_provision, thendata_link_project). - The project environment then carries the data token and credentials (see Injected process.env):
| Engine | Variables |
|---|---|
| PostgreSQL | PG_DATA_TOKEN, DATA_USER, DATA_PASSWORD, DATA_DB |
| Redis | REDIS_DATA_TOKEN, DATA_USER, DATA_PASSWORD |
| MongoDB | MONGO_DATA_TOKEN, DATA_USER, DATA_PASSWORD, DATA_DB |
| S3 | S3_DATA_TOKEN, DATA_KEY_ID, DATA_KEY_SECRET, DATA_BUCKET |
| P2P | P2P_DATA_TOKEN, DATA_USER, DATA_PASSWORD |
The oldest linked instance uses these names; other instances add a prefix from their name (ANALYTICS_DB_DATA_USER, ANALYTICS_DB_PG_DATA_TOKEN, ...).
- Connect with the code below. Always
ssl: false(the tunnel is alreadywss://); the port given to the driver is ignored (the token selects the instance), keep the engine's default for readability.
PostgreSQL (pg)
// db.ts
import tunnel from "fullstacked/tunnel";
import pg from "pg";
let pool: pg.Pool | null = null;
export async function getPool(): Promise<pg.Pool> {
if (pool) return pool;
const host = await tunnel.register({
host: process.env.TUNNELS_HOST!,
authorization: `${process.env.AUTH_TOKEN}:${process.env.PG_DATA_TOKEN}`,
});
pool = new pg.Pool({
host,
port: 5432,
user: process.env.DATA_USER,
password: process.env.DATA_PASSWORD,
database: process.env.DATA_DB,
ssl: false,
max: 10,
});
pool.on("error", (err) => console.error("pg pool error", err));
return pool;
}
const { rows } = await (await getPool()).query("SELECT now()");Redis (ioredis)
import tunnel from "fullstacked/tunnel";
import Redis from "ioredis";
const host = await tunnel.register({
host: process.env.TUNNELS_HOST!,
authorization: `${process.env.AUTH_TOKEN}:${process.env.REDIS_DATA_TOKEN}`,
});
const redis = new Redis({
host,
port: 6379,
username: process.env.DATA_USER,
password: process.env.DATA_PASSWORD,
});
redis.on("error", (err) => console.error("redis error", err));
await redis.set("greeting", "hello");MongoDB (mongodb)
import tunnel from "fullstacked/tunnel";
import { MongoClient } from "mongodb";
const host = await tunnel.register({
host: process.env.TUNNELS_HOST!,
authorization: `${process.env.AUTH_TOKEN}:${process.env.MONGO_DATA_TOKEN}`,
});
const { DATA_USER, DATA_PASSWORD, DATA_DB } = process.env;
const client = new MongoClient(
`mongodb://${DATA_USER}:${DATA_PASSWORD}@${host}:27017/${DATA_DB}?authSource=${DATA_DB}&directConnection=true`
);
await client.connect();
const db = client.db(DATA_DB);Keep directConnection=true (a single server reached through the tunnel name) and authSource set to the database: the app users live there.
S3 (@aws-sdk/client-s3)
import tunnel from "fullstacked/tunnel";
import { S3Client, PutObjectCommand, ListObjectsV2Command } from "@aws-sdk/client-s3";
const host = await tunnel.register({
host: process.env.TUNNELS_HOST!,
authorization: `${process.env.AUTH_TOKEN}:${process.env.S3_DATA_TOKEN}`,
});
const s3 = new S3Client({
endpoint: `http://${host}`,
region: "us-east-1",
forcePathStyle: true,
credentials: {
accessKeyId: process.env.DATA_KEY_ID!,
secretAccessKey: process.env.DATA_KEY_SECRET!,
},
});
const Bucket = process.env.DATA_BUCKET!;
await s3.send(new PutObjectCommand({ Bucket, Key: "hello.txt", Body: "hi", ContentType: "text/plain" }));
const list = await s3.send(new ListObjectsV2Command({ Bucket }));Use http:// (not https://) and forcePathStyle: true. Each instance has one bucket, DATA_BUCKET.
P2P (@fullstacked/p2p)
A P2P instance is a realtime server for the users of a project. Every user who runs the project connects as a peer and sees every other peer (presence), wherever they are in the app, and can message any of them directly (send, request). The rest happens in channels: named scopes such as lobby or board:42 that a client subscribes to. A channel carries its own shared key-value state (persisted by the instance; a subscriber gets it on subscribe), broadcasts, per-channel presence and audio/video, and they reach only its subscribers. Subscribe to what the current screen needs and unsubscribe when it goes away. Use it for multiplayer and collaborative features: live cursors, chat, shared documents and whiteboards, calls.
Add the driver to the project's package.json: "dependencies": { "@fullstacked/p2p": "^0.5.0" }.
// p2p.ts
import tunnel from "fullstacked/tunnel";
import { P2PClient } from "@fullstacked/p2p";
let client: Promise<P2PClient> | null = null;
/** One client per app instance: every caller shares it. */
export function getP2P(): Promise<P2PClient> {
client ??= (async () => {
const host = await tunnel.register({
host: process.env.TUNNELS_HOST!,
authorization: `${process.env.AUTH_TOKEN}:${process.env.P2P_DATA_TOKEN}`,
});
// The signed-in user is the peer: one peerId per user, one session per device.
const res = await fetch(`${process.env.AUTH_URL}/api/v1/me`, {
headers: { Authorization: `Bearer ${process.env.AUTH_TOKEN}` },
});
const { data: me } = await res.json();
return P2PClient.connect({
host,
port: 4444,
user: process.env.DATA_USER, // decides the role: read-write creates channels, read-only joins existing ones
password: process.env.DATA_PASSWORD,
peer: { id: me.id, name: me.name ?? me.username, meta: { color: "#0080ff" } },
});
})();
return client;
}// board.ts
import { P2PError } from "@fullstacked/p2p";
import { getP2P } from "./p2p";
const p2p = await getP2P();
p2p.on("peer:joined", (peer) => console.log(`${peer.name} is online`));
p2p.on("peer:left", (peer, reason) => console.log(`${peer.name} left (${reason})`));
console.log("online:", p2p.getActivePeers().map((p) => p.name));
console.log("boards:", p2p.getChannels().map((c) => c.id)); // listed without subscribing
let board;
try {
// Read-write users create the channel when it is missing; read-only users join existing ones.
board = await p2p.subscribe("board:42", { create: p2p.role !== "ro", meta: { tool: "pen" } });
} catch (err) {
if (err instanceof P2PError && err.code === "CHANNEL_NOT_FOUND") throw new Error("This board does not exist yet");
throw err;
}
// Register listeners right after subscribe: earlier events are not replayed (state is, via getState).
board.on("message", (event) => console.log(event.from.name, event.data));
board.on("state:changed", ({ key, value, deleted }) => console.log(key, deleted ? "deleted" : value));
board.on("subscriber:joined", ({ peer }) => console.log(`${peer.name} opened the board`));
console.log("title:", board.getState("title"));
await board.setState("title", "Sprint planning");
await board.broadcast({ type: "chat", text: "hello" });
await board.broadcast({ type: "cursor", x: 10, y: 20 }, { ephemeral: true });
// Leaving the screen:
await board.unsubscribe();- Client API:
getActivePeers(),getPeers(peerId)(one entry per device),updatePresence(meta)(global),send(peerIdOr{ sessionId }, data),request(target, data)answered byevent.reply(value)in the target'smessagelistener,getChannels()(each with itsmeta: a title, a description, up to 4 KiB),getSubscribers(channel),createChannel(id, { meta? })/updateChannelMeta(id, patch)(read-write only),deleteChannel(id)(its creator only),peek(id | ids, { keys?, prefix? })(read one or many channels' entries and stats without subscribing),getChannelStats({ prefix })/followStats(prefix)(thechannel:statsevent: "edited 3 min ago"),can(action, channel)(the server's rule, for your UI),subscribe(id, { create?, meta?, replace?, state? })(replaceswitches from another channel in one step;state: falseloads no state). Values are any JSON. - Channel API:
getState(key?),setState(key, value, { tag?, ephemeral? })/setStates({ key: value }),deleteState(key, { tag? })/deleteStates(keys),clearState({ prefix? }),broadcast(data, { ephemeral?, throttleMs?, settleMs?, stream? }),getSubscribers(),updatePresence(meta, { merge?, ephemeral?, throttleMs?, settleMs? })(channel presence;ephemeralwiththrottleMs/settleMsfor cursors),lease(name)with thelease:changedevent (exactly one device holds a job at a time). An ephemeralsetStateis a live value while dragging (live: trueonstate:changed), never stored: finish with a regularsetState.tagsays why a key changed (change.tag, e.g."undo");change.createdmarks a new key.shareMedia(stream)/stopMedia()with themediaevent,unsubscribe(), and theclosedevent when the channel is deleted. Concurrent state writes resolve last-write-wins. Every export of the package carries TSDoc; its README is the full guide. - Channel ids are 1 to 128 letters, digits,
.,_,:or-(INVALID_CHANNELotherwise); use a prefix per kind (board:42,call:team). Subscribing to a missing channel withoutcreaterejects withCHANNEL_NOT_FOUND. - Transport: the control connection goes through the tunnel like any driver. FullStacked apps (webview) also open direct WebRTC links to the devices they share a channel with when they can (the instance provides no STUN/TURN servers, so links form between devices that can reach each other directly, such as on one network) and fall back to the relay through the instance otherwise, with no code change. Media over the relay arrives with about 0.3 to 0.8 s of latency at 250 kbps. Actions and the CLI are socket-only: everything but media works.
- Connection drops (instance restart, network change) reconnect automatically with a new
sessionId(samepeerIdanddeviceId) and resubscribe every channel: listen todisconnected/reconnected. When access can change while the app runs, passbeforeConnectto re-read credentials before each reconnect. A failed firstconnect()rejects (AUTH_FAILED,TIMEOUT,SERVER_FULL) and is not retried. - From the Console or MCP,
data_querytakes the driver's inspection operations as JSON, without subscribing:{"operation":"channels"},{"operation":"peers","channel":"board:42"},{"operation":"getState","channel":"board:42","prefix":"shape:"},{"operation":"getStates","channels":["board:1","board:2"],"keys":["thumb"]},{"operation":"stats","prefix":"board:"},{"operation":"setState","channel":"board:42","key":"title","value":"Q4"},deleteState,clearState(prefix?),broadcast(channel,data),send(to,data),createChannel(channel,meta?),updateChannel(channel,meta) anddeleteChannel(channel; only channels you created).data_query_schemashows the connected devices with their channels, every channel with its subscriber count, size and keys, storage and limits;schema_nameset to a channel id shows that channel's subscribers and keys. Writes made there are attributed to your user id (updatedBy).
Read-only users
A user with read access only receives the app_ro credentials and the read-only token: PostgreSQL rejects writes (SQLSTATE 25006 read-only transaction, or 42501 insufficient privilege), Redis allows only read and subscribe commands, MongoDB and S3 refuse writes, and a P2P app_ro client (p2p.role === "ro") cannot create or delete channels (P2PError FORBIDDEN) but joins existing ones and takes full part in them: broadcasts, shared state, presence and media. A frozen instance (over quota) also resolves to read-only credentials for everyone. Design the UI to handle a failed write, and gate write controls with GET /api/v1/user/access: resources.data[<instanceId>].write && !resources.data[<instanceId>].frozen (write stays true on a frozen instance).
Container limits
| Engine | Image | Port | Memory | CPUs | PIDs |
|---|---|---|---|---|---|
| PostgreSQL | postgres:18.6-alpine | 5432 | 256 MB | 2 | 256 |
| Redis | redis:8.10.2-alpine | 6379 | 256 MB | 1 | 128 |
| MongoDB | mongo:8.3.11-noble | 27017 | 512 MB | 2 | 512 |
| S3 (RustFS) | rustfs/rustfs:1.0.0 | 9000 | 768 MB | 2 | 1024 |
| P2P | fullstackedorg/p2p:0.5.1 | 4444 | 256 MB | 1 | 128 |
Engine settings:
- PostgreSQL:
shared_buffers=32MB,maintenance_work_mem=16MB,max_connections=110, and each backend's private memory capped at 64 MB. A query that needs more fails alone without of memory(SQLSTATE53200); if backends together exceed the container memory, one is killed and PostgreSQL resets every connection of the instance. A query's temporary files stop at 1 GB (temp_file_limit, SQLSTATE53400for that query alone). - Redis: AOF persistence (
appendonly yes) andmaxmemory 192mbwithnoeviction: past 192 MB of data, writes fail with anOOMerror while reads keep working; nothing is evicted. Keep keys bounded (TTLs). - MongoDB: default settings inside the container memory limit (diagnostic data capped at 20 MB).
- S3 (RustFS): at most 8 concurrent disk reads and 4 concurrent uploads per instance; further uploads queue for up to 60 s.
- P2P: shared state up to 16 MiB across all channels (
STATE_TOO_LARGEpast it), messages and state values up to 1 MiB each (PAYLOAD_TOO_LARGE), 100 concurrent connections (SERVER_FULL), 1,024 channels per instance and 16 subscribed at once per device (CHANNEL_LIMIT), and a client that falls 1 MiB behind on reliable frames is disconnected (slow_consumer) and reconnects.
Containers have no swap and restart automatically after being killed.
Fair use and driver practices
- Page large results:
LIMITwith keyset pagination or cursors in PostgreSQL so no single query needs more than 64 MB of backend memory;SCANinstead ofKEYS *in Redis; batch MongoDB reads withlimitand cursors. - Bound concurrency: keep
pg.Poolsmall (max10 or less per app) and avoid many heavy queries at once (Promise.allover dozens of large result sets) that together exceed the instance memory. - Bound uploads: run at most 4 S3 uploads at a time per instance and keep the AWS SDK's default retries.
P2P: send high-frequency values (cursors, live strokes) with
{ ephemeral: true }and keep large data out of messages and state. - Handle errors: attach
errorlisteners to pools and clients so a dropped connection (revoked access, instance restart) does not surface as an unhandled error; reconnect on demand. - Register once: call
tunnel.registeronce per instance and reuse the name and the client. - Unlink before deprovisioning: an instance that a project still links cannot be deprovisioned (
409 INSTANCE_LINKED, naming the projects). Unlink it from each project first (Console: Project, Linked data; REST:DELETE /api/v1/projects/:id/data-links). The instance page lists the projects that link it. - Plan quotas: every owner's instances count against the owner's plan: on Base 5 data instances, 1 GiB of storage across their projects and data instances together, and 5 GiB per UTC calendar month of data tunnel transfer (both directions); on Pro 15 instances, 25 GiB and 100 GiB; on Business 60 instances, 200 GiB and 1 TiB. Instances beyond the plan's oldest ones are frozen (read-only) until others are deleted; over the storage limit every non-sponsored instance is frozen until storage falls below 95% of it; once the monthly transfer is spent, new connections are refused (
402 quota_exceeded) until the next month. An instance linked to a project that a Pro or Business member sponsors (an accepted member, within their 10 or 50 sponsored projects and Edges) has no limits.
Troubleshooting
A refused tunnel session fails every connection with an error naming the tunnel and the WebSocket handshake status (for example expected handshake response status code 101 but got 401); the reason word below is in the hub's response body, not in the error.
| Symptom | Cause |
|---|---|
| Variable undefined | Instance not linked, or the user has no access to it (omitted from the environment). |
Connection fails, status 401 | AUTH_TOKEN missing, expired or revoked, or the data token was rolled (re-read the environment). |
Status 403 (read_access_denied / write_access_denied) | The user lost access to the instance. |
Status 402 (quota_exceeded) | Frozen instance (read-write token) or monthly data transfer spent. |
Status 503 (auth_unavailable) | The hub could not check the token: retry. |
| SSL negotiation error | Driver TLS enabled: set ssl: false / plain http://. |
Endpoints
GET /api/v1/data
Managed data instances visible to the caller (?engine=).
- Service:
data(https://t.fullstacked.cloud) - Auth: Bearer fsc_*
curl:
curl -sS -H "Authorization: Bearer $AUTH_TOKEN" "https://t.fullstacked.cloud/api/v1/data"POST /api/v1/data/provision
Provisions an isolated instance { engine: postgres | redis | mongodb | s3 | p2p, label? } (201).
- Service:
data(https://t.fullstacked.cloud) - Auth: Bearer fsc_*
Request:
{
"engine": "postgres"
}GET /api/v1/data/:id
One instance.
- Service:
data(https://t.fullstacked.cloud) - Auth: Bearer fsc_*
DELETE /api/v1/data/:id
Deprovisions an instance (owner only, 204).
- Service:
data(https://t.fullstacked.cloud) - Auth: Bearer fsc_*
GET /api/v1/data/:id/connection
Connection parameters, DATA_* variables and fullstacked/tunnel snippets for ?access_level=rw|ro within the caller's permission.
- Service:
data(https://t.fullstacked.cloud) - Auth: Bearer fsc_*
GET /api/v1/data/:id/schema
Introspects tables, keys, collections or buckets (?schema=).
- Service:
data(https://t.fullstacked.cloud) - Auth: Bearer fsc_*
POST /api/v1/data/:id/query
Runs one operation: { sql, params? } (postgres), { command } (redis), { operation, collection, ... } (mongodb), { operation, key?, prefix?, ... } (s3) or { operation, key?, prefix?, value?, data?, to? } (p2p).
- Service:
data(https://t.fullstacked.cloud) - Auth: Bearer fsc_*
Request:
{
"sql": "select now()"
}