Hubfly spaceDocs
Console

SDK · Managed services

Managed Databases & Realtime

Both SDKs expose the Managed Services API: client.managed in TypeScript and client.Managed in Go. One module covers database instances (PostgreSQL, MySQL, SQLite/libSQL) and Realtime servers.

This page covers the control plane: creating, configuring and operating instances through the Dashboard API. To connect browsers and publish events from your backend with an app key, use the Realtime client and server packages. For the product itself, read the Managed Databases andRealtime guides; every endpoint is listed in theDatabases API and Realtime APIreferences.

How the module is organised

TypeScriptGoCovers
client.managedclient.ManagedCatalog (catalog / Catalog), unit prices (pricing), price quotes (estimatePrice), your public IP (clientIp / ClientIP), a project's managed workspace and its recent operations.
client.managed.instancesclient.Managed.InstancesBoth services: list, get, create, rename, delete, deletion protection, start, stop, restart, resize, upgrade, operations, metrics, logs, audit log, network and alerts.
client.managed.databasesclient.Managed.DatabasesDatabases only: connection details, CA certificate, credentials, app bindings, databases, users, libSQL tokens, extensions, SQL, schema and rows, exports and imports, configuration, sessions, query insights and shell sessions.
client.managed.realtimeclient.Managed.RealtimeRealtime servers only: apps, keys, webhooks, publish and direct messages, channels, connections, history, insights, usage, the live inspector and app bindings.

Every method takes the managed project id and, for instance routes, the instance id. Method names match across languages (createBinding / CreateBinding); Go methods take acontext.Context first and return *hubfly.Response[T]. Request and response types are generated from the Dashboard OpenAPI document and exported from both packages (for example CreateManagedInstanceBody).

Permissions follow the project roles: database:read, database:query anddatabase:admin for databases, realtime:read,realtime:publish and realtime:admin for Realtime servers. A database route called on a Realtime server (or the reverse) answers 409 withMANAGED_FEATURE_UNSUPPORTED.

Managed service projects

Instances live in a Managed service project, which Hubfly space places for you; there is no region to choose. The SDKs' projects.create creates Cell projects only, so create the managed project in the Dashboard or with the CLI (hubfly db create --project new or hubfly realtime create --project new), then pass its id to the methods below.

Quote and create an instance

Creating or resizing an instance needs a price quote: pass the quoted hourly total asquotedHourlyTotal. If prices changed in the meantime the API refuses the request withMANAGED_PRICE_CHANGED; fetch a new quote and try again. Reuse the sameidempotencyKey when you retry a create so it cannot run twice.

TypeScript
import { randomUUID } from 'node:crypto';
import { HubflyClient } from '@hubfly/sdk';

const client = new HubflyClient(); // reads HUBFLY_TOKEN
const projectId = 'proj_123';      // a Managed service project

const { data: catalog } = await client.managed.catalog();
const nano = catalog.sizes.presets.find((preset) => preset.id === 'nano')!;
const size = { cpu: nano.cpu, memoryMib: nano.memoryMib, storageGib: 10 };

const { data: quote } = await client.managed.estimatePrice(size);
console.log('about $' + quote.monthly.total.toFixed(2) + ' per month');

const { data: created } = await client.managed.instances.create(projectId, {
  name: 'app-db',
  service: 'database',
  engine: 'postgresql',
  version: '18',
  size,
  quotedHourlyTotal: quote.hourly.total,
  idempotencyKey: randomUUID(),
});

const operation = await client.managed.instances.waitForOperation(
  projectId,
  created.instance.id,
  created.operationId,
);
if (operation.status !== 'succeeded') {
  throw new Error(`create failed: ${operation.error?.message}`);
}
Go
ctx := context.Background()
projectID := "proj_123" // a Managed service project

catalog, err := client.Managed.Catalog(ctx)
if err != nil {
	log.Fatal(err)
}
var nano hubfly.GetManagedCatalogSizesPreset
for _, preset := range catalog.Data.Sizes.Presets {
	if preset.ID == "nano" {
		nano = preset
	}
}

quote, err := client.Managed.EstimatePrice(ctx, hubfly.GetManagedPriceEstimateQuery{
	CPU: nano.CPU, MemoryMib: nano.MemoryMib, StorageGib: 10,
})
if err != nil {
	log.Fatal(err)
}

created, err := client.Managed.Instances.Create(ctx, projectID, hubfly.CreateManagedInstanceBody{
	Name:              "app-db",
	Service:           "database",
	Engine:            "postgresql",
	Version:           "18",
	Size:              hubfly.ManagedInstanceSizeInput{CPU: nano.CPU, MemoryMib: nano.MemoryMib, StorageGib: hubfly.Float(10)},
	QuotedHourlyTotal: quote.Data.Hourly.Total,
	IdempotencyKey:    "create-app-db-1",
})
if err != nil {
	log.Fatal(err)
}

op, err := client.Managed.Instances.WaitForOperation(ctx, projectID, created.Data.Instance.ID, created.Data.OperationID, nil)
if err != nil || op.Status != "succeeded" {
	log.Fatalf("create: %v %+v", err, op)
}

The catalog lists engines with their versions and minimum memory, the size presets, the storage range and your instance limit. Sizes and limits are described inDatabase pricing & limits. A Realtime server is created the same way with service: 'realtime', a size fromcatalog.realtime.sizes and an optional initialApp.

Wait for operations

Create, start, stop, restart, resize, upgrade, configuration and network changes run as operations. These methods return an operation id right away; waitForOperation /WaitForOperation polls it until it succeeds, fails or is canceled and returns the final state. A failed operation is not thrown as an error: check status anderror.

OptionTypeScriptGo (*WaitForOperationOptions)
Poll interval (default 2 s)intervalMsInterval
Give up after (default 15 minutes)timeoutMs (throws a HubflyApiError with status 408)Timeout, or cancel ctx
Progress callbackonProgress(operation)OnProgress
Cancelsignal (an AbortSignal)ctx

Lifecycle and network

Method (TypeScript / Go)Notes
list, getInstances of a project, or one instance. Realtime servers carry a realtime block.
start, stop, restart, upgradeReturn an operation id. A stopped instance pays for storage only.
resizecpu, memoryMib, storageGib (grow only) and restart, with a fresh quotedHourlyTotal.
update, updateDeletionProtection, deleteRename, protect, or delete. delete needs confirmName equal to the instance name and fails while deletion protection is on.
getNetwork, updateAllowlist, updatePublicAccessThe allowlist is replaced as a whole: pass the revision from getNetwork. Public access applies to databases only. On a Realtime server the allowlist guards the server API; WebSocket clients are never IP-restricted.
metrics, logs, audit, listOperations, getAlerts, updateAlertsMonitoring and history for either service.
TypeScript
const { data: network } = await client.managed.instances.getNetwork(projectId, instanceId);
const { data: me } = await client.managed.clientIp();
if (!me.ip) throw new Error('could not detect your public IP');

// The list is replaced as a whole: keep the existing entries and add yours.
await client.managed.instances.updateAllowlist(projectId, instanceId, {
  revision: network.revision,
  entries: [
    ...network.allowlist.map(({ cidr, label }) => ({ cidr, label: label ?? undefined })),
    { cidr: me.ip, label: 'laptop' },
  ],
});

Connect and bind a database

databases.getConnection returns the host, port, default database and user without a password; getCertificate returns the instance's CA certificate forsslmode=verify-full. To give a Cell app the connection string, bind the database to the app's project instead of copying the password: Hubfly space writes DATABASE_URL (orLIBSQL_URL and LIBSQL_AUTH_TOKEN) into the project and keeps it current when credentials rotate. The URL is not returned to you.

TypeScript
await client.managed.databases.createBinding(projectId, instanceId, {
  targetProjectId: 'proj_web',
  envKey: 'DATABASE_URL',        // optional; this is the default
  createUser: true,              // a dedicated user instead of the admin user
  access: 'read_write',
});
Go
_, err = client.Managed.Databases.CreateBinding(ctx, projectID, instanceID, hubfly.CreateManagedInstanceBindingBody{
	TargetProjectID: "proj_web",
	CreateUser:      hubfly.Ptr(true),
	Access:          "read_write",
})

Redeploy the app afterwards so it reads the new variable. SeeConnect a Cell app for naming rules and what happens on rotation and removal.

Databases, users, tokens and SQL

MethodsEngines
listDatabases, createDatabase, deleteDatabase (needs confirmName)PostgreSQL, MySQL
listUsers, createUser, updateUser, deleteUser, rotateUserPasswordPostgreSQL, MySQL. Presets read_only, read_write, admin, for listed databases or allDatabases.
listTokens, createToken, deleteTokenSQLite (libSQL). Deleting any token rotates the signing key, which revokes every token.
listExtensions, installExtension, deleteExtensionPostgreSQL, from Hubfly space's allowlist
query, getSchema, getTableRows, changeTableRowsAll engines. Results are your data and are never cached.

query runs SQL through Hubfly space, like the Dashboard's SQL editor, so it needs neither a driver nor an allowlist entry. Set readOnly: true unless the statement must write. The response holds one entry per statement with its columns, rows (as strings ornull), row count and any error.

TypeScript
const { data: result } = await client.managed.databases.query(projectId, instanceId, {
  sql: 'select id, email from users order by id limit 10',
  readOnly: true,
  maxRows: 10,
});

for (const statement of result.statements) {
  if (statement.error) throw new Error(statement.error.message);
  console.log(statement.columns.map((c) => c.name), statement.rows);
}
Go
res, err := client.Managed.Databases.Query(ctx, projectID, instanceID, hubfly.PostManagedInstanceQueryBody{
	SQL:      "select count(*) from users",
	ReadOnly: true,
})
if err != nil {
	log.Fatal(err)
}
fmt.Println(res.Data.Statements[0].Rows)

Exports, configuration and insights

  • Exports and imports. createExport starts an export (an operation);downloadExport returns a download URL valid for 10 minutes. For an import, calluploadImport to get an upload URL (valid for 1 hour), upload the file to it, thenstartImport. Exports expire after 7 days. getBackups reports backup status: automatic backups are not available yet.
  • Configuration (PostgreSQL, MySQL). getConfig returns the settings and a generation; validateConfig checks changes without applying them;applyConfig applies them for the current generation; getConfigHistoryand revertConfig return to an earlier revision.
  • Sessions and insights (PostgreSQL, MySQL). listSessions,cancelSession, terminateSession, getInsights andresetInsights.
  • Shell. createShellSession returns a short-lived terminal token and URL for a SQL shell that runs on Hubfly space (PostgreSQL, MySQL).

Realtime servers

client.managed.realtime manages a server's apps and keys and can publish events through the Dashboard API with your Hubfly space token. Your application's backend normally publishes with the app key and secret instead, using @hubfly/realtime/server or the Go realtime package.

AreaMethods (TypeScript; Go uses the same names capitalised)
AppslistApps, getApp, createApp, updateApp, updateAppSettings (pass the app's settingsRevision as revision), deleteApp
KeyslistKeys, createKey, rotateKey (the old key keeps working for a grace period), revokeKey, revealKey
Eventspublish to channels, send to 1–100 connections or one user
StatelistChannels, inspectChannel, listConnections, terminateConnection, terminateUser, getHistory, purgeHistory
WebhookslistWebhooks, createWebhook, updateWebhook, deleteWebhook, testWebhook, getWebhookDeliveries, redeliverWebhook
ObservegetInsights, getUsage, openInspector (live event stream), createInspectorToken, getInspectorRecent
ConnectgetConnection (host, URLs, public keys, pusher-js options and variable names, no secrets), listBindings, createBinding, deleteBinding

The TypeScript client also has async iterators for paged lists (iterateChannels,iterateConnections, iterateWebhookDeliveries); Go hasListAllChannels, ListAllConnections andListAllWebhookDeliveries.

TypeScript
// Bind an app to a Cell project: writes HUBFLY_REALTIME_URL, _APP_ID, _KEY and _SECRET
// (plus NEXT_PUBLIC_ copies of the URL and key for the browser).
await client.managed.realtime.createBinding(projectId, instanceId, {
  appId,
  targetProjectId: 'proj_web',
  preset: 'hubfly',          // or 'laravel' for PUSHER_* variables
  clientPrefix: 'NEXT_PUBLIC_',
});

// Publish through the Dashboard API (data may be any JSON value).
await client.managed.realtime.publish(projectId, instanceId, appId, {
  channels: ['orders'],
  event: 'order.created',
  data: { id: 42 },
});
Go
// In Go, Data is the event's data string (usually JSON text).
_, err = client.Managed.Realtime.Publish(ctx, projectID, instanceID, appID, hubfly.PostManagedRealtimePublishBody{
	Channels: []string{"orders"},
	Event:    "order.created",
	Data:     `{"id":42}`,
})

End-to-end connection ids (<socket_id>~<key>) are accepted wherever a socket id is: the SDK removes the key part on your machine before any request, and refuses to send plaintext to such an id (MANAGED_REALTIME_E2E_CONNECTION_ID). Send end-to-end encrypted direct messages from your own server with theRealtime server packages.

Methods that return secrets

These responses contain a password, token, key secret or signed URL. Do not log them, and store them only where your application needs them. Reveals and rotations are recorded in the instance's audit log.

  • Databases: revealCredentials, rotateCredentials (on libSQL it rotates the signing key and returns no secret), createUser, rotateUserPassword, createToken, downloadExport, uploadImport, createShellSession.
  • Realtime: createApp, createKey, rotateKey, revealKey, createInspectorToken.

Error codes

Failed calls throw HubflyApiError (TypeScript) or return *hubfly.APIError(Go) as described in Errors & retries. Managed routes add a machine-readable code. Branch on it with isManagedApiError(error, code)and the ManagedErrorCodes constants in TypeScript, orhubfly.IsAPIErrorCode(err, code) and the hubfly.ErrCodeManaged…constants in Go.

CodeMeaning
MANAGED_PRICE_CHANGEDThe quote is stale. Fetch a new estimate and retry.
MANAGED_INSTANCE_NOT_RUNNINGThe instance must be running for this call.
MANAGED_FEATURE_UNSUPPORTEDA database route on a Realtime server, or the reverse.
MANAGED_CONFIRMATION_MISMATCHconfirmName does not match the instance, database or app name.
MANAGED_RATE_LIMITEDToo many requests. Retry later.
MANAGED_REALTIME_ENGINE_UNSUPPORTEDThe server's engine version does not support this feature yet. Upgrade the server.
MANAGED_REALTIME_E2E_REQUIREDThe app requires end-to-end encryption, so Hubfly space cannot publish plaintext for you.
MANAGED_REALTIME_PAYLOAD_TOO_LARGEThe event is larger than the app allows.
MANAGED_REALTIME_CONNECTION_NOT_FOUNDNo such connection.

Prefer the CLI for one-off tasks

For interactive work, hubfly db andhubfly realtime wrap the same API with quotes, confirmations and waiting built in. Use the SDKs when you automate these steps from your own code.
Something unclear or out of date? Emailsupport@hubfly.spaceBack to top