Cloud platforms
Where to run fennec-server on each cloud, or no
server at all on Cloudflare, the config for it, and how your apps and
functions reach it.
A server is one process over one file on a disk, reached over HTTP. That asks three things of a platform: a block disk that outlives the process, one instance at a time, and a stop that waits for the final sync. Pick yours from the table, then read the rules and the volume's owner, which hold on every platform. Serverless needs none of that: on Cloudflare the engine runs inside a Worker, a database in each Durable Object (Serverless), and a function on any platform is a client, of a server or of that Worker (Functions). Servers in several regions take one URL through a Worker in front of them (Distributed), and Cloudflare's pieces on other platforms says what each part is called elsewhere.
| Platform | Run it as | Disk | Section |
|---|---|---|---|
| Fly.io | a Machine | Fly volume | Fly.io |
| Render | a private or web service | persistent disk | Render |
| Railway | a service from the image | Railway volume | Railway |
| AWS, Google Cloud, Azure, DigitalOcean, Hetzner, OVHcloud, Scaleway, Akamai/Linode, Vultr, Oracle Cloud, any VM | a VM | the cloud's block volume (EBS, Persistent Disk or Hyperdisk, managed disk, Volume) | A VM |
| EKS, GKE, AKS, DOKS and any Kubernetes | a StatefulSet of one | a ReadWriteOnce claim | Kubernetes |
| Cloudflare Workers | no server: the engine in a Durable Object, a database each | the object's storage | Serverless |
| Cloudflare in front of regions | the global entry Worker, over Tunnel and Access, before servers on VMs | the nodes' block volumes | Distributed |
| Vercel, Netlify, Lambda, Cloud Run, Cloud Functions, Azure Functions, Deno Deploy | functions, as clients of a server or of a Worker | none needed | Functions |
| ECS on Fargate, App Runner, Container Apps, App Service, App Platform, Heroku | your app, as a client | none that fits | Not a home |
The rules on every platform
- A block volume, never a network share. EBS, Persistent Disk and
Hyperdisk, an Azure managed disk, a DigitalOcean, Hetzner or Linode
volume, a Fly volume, a Render disk, a Railway volume. Not EFS, Azure
Files or Filestore (NFS and SMB), and not a bucket shown as files (Cloud
Storage FUSE, Mountpoint for S3, s3fs): the server holds
<file>.lockto keep a second process out, and a network file system may not keep that lock (--file).--no-mmapexists for them; this page does not recommend them. - One instance. Replicas 1, no autoscaling, and a deploy stops the old instance before it starts the new: a second process over the file is refused (exit 1), so a platform that starts the new beside the old must be told not to.
- A token from the secret store.
FENNEC_HTTP_TOKEN, in the environment, never--http-token:argvshows inps. Without a token the server refuses to listen beyond loopback and exits 2. Make it yourself and keep a copy for your apps: most secret stores never show a secret again. - Health is
GET /_health. It needs no token and takes no lock. The port binds only after the file is opened, so a large file takes a while: give a startup check a grace period of minutes (the image's own check,--ping, waits 120 s). Orchestrators other than Docker ignore the image'sHEALTHCHECK. - Wait for the stop. SIGINT, SIGTERM and SIGHUP all run the clean
shutdown: a final sync, then a checkpoint of the vector graphs. Killed before
it ends (SIGKILL, an out-of-memory kill, a grace period that ran out), up to
one
--syncinterval of writes is lost and the graphs are linked again at the next start. Set the platform's stop timeout to 30 to 60 s. - Memory. There is no buffer pool: the file is mapped and the page
cache holds it; the process holds the indexes. Give
--max-memory(in MiB) a third of the memory limit, and a write past it gets 507 rather than an out-of-memory kill. - Every flag, when you override the command. The image's is
--http 0.0.0.0:8080 --file /data/data.fennec --sync 250; write out whatever you change, or the file is dropped and the database is in memory.
Who owns the volume
Nothing to set on any platform. The image starts as root, and
fennec-server becomes 65534:65534, the
nobody of Linux, before it opens a file or starts a thread: it
never serves as root. A platform's volume is often an empty file system whose
root belongs to root, where 65534 could not make its file, so the
server hands it over first:
$ docker run --rm --mount type=volume,dst=/data,volume-nocopy=true \
-e FENNEC_HTTP_TOKEN="$(openssl rand -hex 32)" ghcr.io/fennec-db/fennec-server:0.2.0
handed /data to 65534:65534
running as 65534:65534, started as root (FENNEC_USER)
opened: /data/data.fennec- What is handed over. The directory the server writes in
(
--file's, or--dir) and the database's files in it —data.fennecand the files beside it named after it, a node's tenants' files — where they are not 65534's already. A start after the first hands over nothing, and neither does a Docker named volume, which Docker fills from the image's/data, 65534's in the image. - What is not. Only a volume of its own holding nothing but the
database and a
lost+found: never/, a path through a symbolic link, a directory on the image's or the host's own file system, one anyone may write in, nor one holding any other file, a link or a directory. The server says why in its log and goes on as 65534; if it then cannot write there, make the directory 65534's yourself, or start the server as its owner. - Another user. Started as anyone but root —
docker run --user 1000:1000, Kubernetes'runAsUser— the server runs as that user and hands nothing over: the volume has to be that user's.FENNEC_USER, or the--userflag over it, names whom root becomes,<uid>:<gid>in numbers. - Every capability dropped. Root without
SETUID,SETGIDandCHOWN(docker run --cap-drop ALL, a pod'sdrop: ["ALL"]) cannot become anyone: the server says so and exits 2 rather than serve as root. Start it as 65534 there,--user 65534:65534orrunAsUser, on a volume that is 65534's. docker execand the health check.--ping, and anything else run in the container, starts as root and drops it the same way: nothing it makes is root's.
Releases after 0.2.0. The image of 0.2.0 starts as 65534 and hands
nothing over: on a volume its platform made root's it stops with its
lock file: Permission denied. With that image, run it as root there —
a derived image of two lines, FROM
ghcr.io/fennec-db/fennec-server:0.2.0 and USER 0:0, or
Railway's RAILWAY_RUN_UID=0 — or make the volume 65534's
(fsGroup: 65534 on Kubernetes, which the manifest below
sets).
Why the image starts as root
The image holds the static binary and nothing else: no shell, no
chown, no gosu. Images with a shell, postgres's and
redis's, fix a volume's owner in an entrypoint script that runs as root and then
drops to the database's user; here the binary does it, between reading its
arguments and opening anything. An image that started as 65534 could not: where
the platform makes the volume itself it is root's, and each platform needed a way
around it (a derived image running as root, Railway's
RAILWAY_RUN_UID=0). Root is kept for the hand-over alone: the
supplementary groups, the group and then the user are dropped, and the server
checks that root cannot be had back before it goes on; a step that fails ends
the start.
A VM and its block volume
The same recipe serves AWS (EC2, Lightsail), Google Compute Engine, Azure,
DigitalOcean, Hetzner, OVHcloud, Scaleway, Akamai/Linode, Vultr, Oracle Cloud
and a machine of your own: a Linux VM, a block volume attached to it in its
zone, fennec-server as a systemd service.
| Cloud | Create the disk | Gotcha |
|---|---|---|
| AWS EC2 | an EBS volume, gp3, in the instance's Availability Zone | On Nitro instances it shows as /dev/nvme1n1, and the number can change at a reboot: mount by UUID. |
| AWS Lightsail | a block storage disk, attached to the instance | You format and mount it yourself; same zone as the instance. |
| Google Cloud | a Persistent Disk or Hyperdisk, attached to the instance | Zonal: it follows the VM's zone. |
| Azure | a managed data disk | Mount a data disk by UUID, not the OS disk's /dev/sdX. |
| DigitalOcean, Hetzner, Linode, others | the provider's volume, in the Droplet's or server's region | One attachment at a time, in one location. |
-
Format and mount the volume once. The device name is on
lsblk.sudo mkfs.ext4 /dev/nvme1n1 sudo mkdir -p /var/lib/fennecdb echo "UUID=$(sudo blkid -s UUID -o value /dev/nvme1n1) /var/lib/fennecdb ext4 defaults,nofail 0 2" | sudo tee -a /etc/fstab sudo mount -aTrim the volume on a timer rather than with the
discardmount option:defaultsleaves it out, andsudo systemctl enable --now fstrim.timertrims every week. Withdiscarda file's blocks are discarded as it goes, and on a disk that discards slowly the reads and fsyncs queued behind them wait: about a quarter of a second for each gigabyte freed, measured in Docker Desktop's VM, which mounts its disk so. The server lets go of a file a compact replaced, or a tenant deleted, 32 MB at a time on ext4, XFS, Btrfs and F2FS, so its own pauses stay short there too; another program freeing a large file on the same disk is not paced. To see whether a mount discards,findmnt -no OPTIONS /var/lib/fennecdb. -
Install the programs (a
.debor.rpmput them in/usr/bin; the packages ship no systemd unit), a user to run them, and the token file.sudo useradd --system --no-create-home --shell /usr/sbin/nologin fennec sudo chown fennec:fennec /var/lib/fennecdb sudo install -d -m 0750 -o root -g fennec /etc/fennecdb sudo install -m 0640 -o root -g fennec /dev/null /etc/fennecdb/server.env echo "FENNEC_HTTP_TOKEN=$(openssl rand -hex 32)" | sudo tee /etc/fennecdb/server.env >/dev/null -
The unit. It is the repository's
deploy/systemd/fennec-node.servicecut down to one file: the same hardening, the token from an environment file, a user of its own, and a stop that waits./etc/systemd/system/fennec-server.service[Unit] Description=fennec-server After=network-online.target local-fs.target Wants=network-online.target RequiresMountsFor=/var/lib/fennecdb [Service] User=fennec Group=fennec EnvironmentFile=/etc/fennecdb/server.env ExecStart=/usr/bin/fennec-server \ --file /var/lib/fennecdb/data.fennec \ --http 0.0.0.0:8080 \ --sync 250 \ --max-memory 1024 Restart=on-failure RestartSec=2s # SIGTERM runs the final sync and the checkpoint of the vector graphs. KillSignal=SIGTERM TimeoutStopSec=60s LimitCORE=0 UMask=0077 ReadWritePaths=/var/lib/fennecdb NoNewPrivileges=yes CapabilityBoundingSet= AmbientCapabilities= ProtectSystem=strict ProtectHome=yes PrivateTmp=yes PrivateDevices=yes ProtectKernelTunables=yes ProtectKernelModules=yes ProtectKernelLogs=yes ProtectControlGroups=yes ProtectClock=yes ProtectHostname=yes ProtectProc=invisible RestrictNamespaces=yes RestrictRealtime=yes RestrictSUIDSGID=yes LockPersonality=yes MemoryDenyWriteExecute=yes RemoveIPC=yes RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX SystemCallArchitectures=native SystemCallFilter=@system-service SystemCallFilter=~@privileged @resources SystemCallErrorNumber=EPERM [Install] WantedBy=multi-user.targetsudo systemctl daemon-reload && sudo systemctl enable --now fennec-server curl -s localhost:8080/_health
- The volume's owner is the
chownabove: the service user, not 65534, since there is no image here. - Memory.
--max-memory 1024is for a machine of about 3 GiB; keep it at a third of what the instance has. - The network. Open 8080 to your app's security group, firewall or
network security group only, not to the world. For HTTPS, give the server
--tls-certand--tls-key(a renewed certificate takes a restart; HTTPS) or put Caddy in front. - Upgrades. Replace the binary and
systemctl restart fennec-server: the stop waits, the start opens the file again.
Kubernetes
One StatefulSet with one replica, a ReadWriteOnce
claim, and a Service. A Deployment would need
strategy: Recreate, since a rolling update keeps two pods up
together for a moment. The pod runs as 65534 and its volume is made 65534's by
fsGroup; the root file system is read-only and every capability
dropped. The image's own user is root, which hands a volume over and becomes
65534 itself (Who owns the volume), so
runAsNonRoot: true needs runAsUser beside it: without
one the kubelet refuses to start the pod.
apiVersion: v1
kind: Service
metadata:
name: fennec
spec:
selector:
app: fennec
ports:
- name: http
port: 8080
targetPort: http
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: fennec
spec:
serviceName: fennec
replicas: 1
selector:
matchLabels:
app: fennec
template:
metadata:
labels:
app: fennec
spec:
terminationGracePeriodSeconds: 60
securityContext:
runAsNonRoot: true
runAsUser: 65534
runAsGroup: 65534
fsGroup: 65534
fsGroupChangePolicy: OnRootMismatch
containers:
- name: fennec
image: ghcr.io/fennec-db/fennec-server:0.2.0
# args replace the image's CMD, so every flag is written out.
args:
- --http
- 0.0.0.0:8080
- --file
- /data/data.fennec
- --sync
- "250"
- --max-memory
- "340"
envFrom:
- secretRef:
name: fennec
ports:
- name: http
containerPort: 8080
resources:
requests:
cpu: 500m
memory: 1Gi
limits:
memory: 1Gi
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
# No token needed, no lock taken. The port binds once the file is
# open: up to 5 minutes for a start over a large file.
startupProbe:
httpGet: {path: /_health, port: http}
periodSeconds: 5
failureThreshold: 60
readinessProbe:
httpGet: {path: /_health, port: http}
periodSeconds: 10
livenessProbe:
httpGet: {path: /_health, port: http}
periodSeconds: 20
timeoutSeconds: 5
failureThreshold: 6
volumeMounts:
- name: data
mountPath: /data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
# storageClassName: see the table below; omit for the cluster's default
resources:
requests:
storage: 20GiThe manifest holds no token, so none is committed with it: make the
Secret it names first, apply it, then reach the server from
inside the cluster at
http://fennec.<namespace>.svc.cluster.local:8080:
kubectl create secret generic fennec \
--from-literal=FENNEC_HTTP_TOKEN="$(openssl rand -hex 32)"
kubectl apply -f fennec.yaml
kubectl rollout status statefulset/fennec
kubectl port-forward svc/fennec 8080:8080 # then curl localhost:8080/_health
# the token, for your apps' own secrets
kubectl get secret fennec -o jsonpath='{.data.FENNEC_HTTP_TOKEN}' | base64 -d| Cluster | storageClassName | Notes |
|---|---|---|
| EKS | one you create: provisioner ebs.csi.aws.com, parameters: {type: gp3}, volumeBindingMode: WaitForFirstConsumer | Install the EBS CSI driver add-on and give it its IAM role first. An EBS volume is in one Availability Zone. |
| EKS Auto Mode | one you create (the docs call it auto-ebs-sc): provisioner ebs.csi.eks.amazonaws.com, type: gp3 | Auto Mode creates no class and needs no driver install. |
| GKE | standard-rwo (balanced Persistent Disk) or premium-rwo (SSD) | Provisioner pd.csi.storage.gke.io. Not regional-rwx, which is a shared file system. |
| AKS | managed-csi (Standard SSD) or managed-csi-premium | Azure managed disks. Not azurefile-csi (Azure Files). |
| DOKS | do-block-storage | do-block-storage-retain keeps the volume when the claim is deleted. |
| Linode (LKE) | linode-block-storage, or linode-block-storage-retain | 10 GiB is the smallest volume. |
| Others | the provider's block-volume CSI class | Whatever is ReadWriteOnce on a block device; kubectl get storageclass. |
Why a StatefulSet, and what the probes allow
A StatefulSet of one replica starts the replacement pod only after the old
one has stopped, and ties it to the same claim; a Deployment's default rolling
update would start the new pod beside the old one, with two processes over a
volume that a block device lets only one node mount, or a network share that
lets both and keeps no lock. OnRootMismatch makes Kubernetes
change a volume's ownership when its root is not fsGroup's, once,
rather than walking every file at each start. A pod that leaves
runAsNonRoot, runAsUser and fsGroup out
starts the server as root, which hands the volume to 65534 and becomes it; that
needs the CHOWN, SETUID and SETGID
capabilities, which drop: ["ALL"] takes away: there it cannot
drop root, says so and exits 2. With every capability dropped, run it as 65534
from the start, as above. The memory limit is 1 GiB and
--max-memory 340 MiB, a third of it, as in the repository's
docker-compose.yml. terminationGracePeriodSeconds: 60
holds the final sync and the checkpoint; the default, 30 s, is short for a large
graph.
Fly.io
A Machine with a volume, in one region. Fly's private network is IPv6, so
the server listens on [::] (which takes IPv4 too on Linux) and the
command is written out in a one-line Dockerfile:
FROM ghcr.io/fennec-db/fennec-server:0.2.0
CMD ["--http", "[::]:8080", "--file", "/data/data.fennec", "--sync", "250", "--max-memory", "340"]app = "my-fennec"
primary_region = "ams"
# The default is 5 s; 300 s is the most it takes.
kill_timeout = 60
[build]
dockerfile = "Dockerfile"
[[mounts]]
source = "fennec_data"
destination = "/data"
initial_size = "10GB"
[http_service]
internal_port = 8080
force_https = true
# Fly's proxy stops a Machine it sees no traffic for, and apps reaching it
# over .internal pass around the proxy: keep it running.
auto_stop_machines = "off"
auto_start_machines = false
[[http_service.checks]]
method = "GET"
path = "/_health"
grace_period = "120s"
interval = "15s"
timeout = "5s"
[[vm]]
memory = "1gb"
cpu_kind = "shared"
cpus = 1fly apps create my-fennec
fly volumes create fennec_data --region ams --size 10
TOKEN=$(openssl rand -hex 32) # keep it: Fly never shows a secret again
fly secrets set FENNEC_HTTP_TOKEN="$TOKEN"
fly deploy --ha=false
fly status- One Machine, one volume. A volume attaches to one Machine, so
fly deploy --ha=falseand neverfly scale count 2. A deploy of one Machine with one volume is down for its length; thecanaryandbluegreenstrategies cannot be used with a volume. - Public, unless you say otherwise. The first deploy gives the app
public addresses, and
[http_service]then answers athttps://my-fennec.fly.dev, behind Fly's certificate, to anyone holding the token. For a server only your apps reach, deploy withfly deploy --ha=false --no-public-ips, or give back addresses it already has (fly ips list,fly ips release):.internalbelow needs none of them. - Memory.
--max-memory 340is a third of the Machine's 1 GB; change the two together. - The volume's owner. Nothing to do: the
CMDabove keeps the image'sFENNEC_USER, and the server hands a new volume to 65534 at its first start, its log saying so (Who owns the volume). - Inside Fly. Other apps in your organization reach it at
http://my-fennec.internal:8080, over the private network and around Fly's proxy, with the token. - Backups. Fly takes a daily snapshot of a volume and keeps it 5 days
by default (
snapshot_retention, up to 60), and says a snapshot may lack the latest writes: take a backup of your own too.
Render
A private service (or a web service, to be public) with a persistent disk.
Render builds it from a repository holding a two-line Dockerfile,
which writes out the command with a --max-memory for the plan:
FROM ghcr.io/fennec-db/fennec-server:0.2.0
CMD ["--http", "0.0.0.0:8080", "--file", "/data/data.fennec", "--sync", "250", "--max-memory", "170"]services:
- type: pserv # web, for a public URL
name: fennec
runtime: docker
dockerfilePath: ./Dockerfile
plan: starter
numInstances: 1
healthCheckPath: /_health # asked of a web service; a private one is checked by its port
maxShutdownDelaySeconds: 60
envVars:
- key: FENNEC_HTTP_TOKEN
sync: false # asked for once, when the Blueprint is created
disk:
name: fennec-data
mountPath: /data
sizeGB: 10- Port. A web service is routed to
PORT, 10000 unless you set it: setPORT=8080beside the token, which is where the image listens. A private service needs no routing. - Health. Render asks
healthCheckPathof a web service alone; a private service passes once its port accepts a connection, which is once the file is open. - Memory. The
starterplan has 512 MB, and--max-memory 170in theDockerfileis a third of it; change the two together. A Blueprint can also deploy the image as it is (runtime: image,image: {url: ...}), with the image's command and no--max-memory. - The disk's owner. Render does not document who owns a disk's
mount; whoever does, the server hands it to 65534 at its first start (Who owns the volume), as it does an empty Docker
volume made with
volume-nocopy, which is where that was checked. - One instance, and a gap at every deploy. A disk cannot be shared
or scaled, and attaching one switches off zero-downtime deploys: Render
stops the old instance, then starts the new, a few seconds with a large
file's open on top.
maxShutdownDelaySecondstakes 1 to 300 and defaults to 30. - The disk is mounted at runtime only, not in a build, a pre-deploy command or a one-off job. It can grow but not shrink. Render snapshots it every 24 hours and keeps each for seven days, restoring whole disks: take a backup of your own too.
- Inside Render. Other services in the workspace reach a private
service by its internal hostname and the port it listens on,
http://<internal-hostname>:8080, copied from the service's Connect menu, Internal tab.
Railway
A service from the image, a volume at /data, and one
replica. A Railway volume is root's, and the server hands it to 65534 at its
first start (Who owns the volume): Railway's
RAILWAY_RUN_UID=0 is not needed.
-
New service, from the Docker image
ghcr.io/fennec-db/fennec-server:0.2.0. -
Variables, three:
FENNEC_HTTP_TOKEN=<a random string, sealed; keep a copy for your apps> PORT=8080 RAILWAY_DEPLOYMENT_DRAINING_SECONDS=60PORTis where Railway's health check asks, and the server listens on 8080 whatever it says. The draining seconds are the time between Railway's SIGTERM and its SIGKILL, 0 unless set: without them every redeploy kills the server before its final sync. -
Add a volume to the service, mount path
/data. A service has one volume. -
Settings: a health check path of
/_health. Railway asks it while a deployment starts, for 300 s unless told otherwise (RAILWAY_HEALTHCHECK_TIMEOUT_SEC), and not again once it is live. Leave the replicas at 1.
- More flags. A start command replaces the image's entry point, so
it is the whole command, the program first:
/usr/local/bin/fennec-server --http 0.0.0.0:8080 --file /data/data.fennec --sync 250 --max-memory 340, with--max-memorya third of the service's memory limit. The image'sFENNEC_USERis a variable, not a flag, so the server still hands the volume over and drops root under a command of your own. - A deploy is a brief outage. Railway never runs two deployments mounted to one volume, so a redeploy stops the old one first, with a health check or not. Replicas cannot be used with volumes.
- Inside Railway. Services of the same environment reach it at
http://fennec.railway.internal:8080(the service's name). An environment made before 16 October 2025 resolves that name to IPv6 only; then the server has to listen on[::], as Fly'sDockerfiledoes. - The volume's size depends on the plan; it grows live and never shrinks, and Railway makes manual and automatic backups of it: take a backup of your own too.
Cloudflare
Cloudflare carries fennecdb two ways, and they combine. Serverless: the engine runs inside a Worker, a database in each Durable Object, and there is no server anywhere. Distributed: servers in regions of your own with Cloudflare as their only way in, one URL for every tenant through a Worker that sends each request to its tenant's region, over Cloudflare Tunnel and behind Cloudflare Access. Around both, a Worker is an endpoint with logic in front of a database, Access an identity provider whose tokens a server takes, and R2 where files and archives go.
| a database in each Durable Object | servers in regions, behind the global entry | |
|---|---|---|
| where the data is | the object's storage, kept by @fennecdb/cloudflare | a file a tenant, on nodes you run in regions of two zones or more |
| what you run | a Worker | nodes, each region's router and its standby, a global router; the entry Worker and a tunnel a router in front |
| a database's size | about 60 000 rows of 128 dimensions, or 12 000 of 768 (Limits) | the node's disk, the file mapped |
| writers | one an object | one a tenant, many tenants a node |
| a client far away | an object lives where it was first asked for | writes go to the tenant's home region; reads may stay in the client's, from a read replica |
| a machine lost | Cloudflare's to handle | the region's router fails its node over to a replica in another zone, cut off from every other region |
| fits | a database for each user, team, tenant or document; a tenant's own RAG corpus; no server to run | many tenants, large ones, failover inside a region, clients on every continent |
Serverless: a database in each Durable Object
The browser module, @fennecdb/web, opens a database in a
Durable Object, and @fennecdb/cloudflare keeps it in the object's
storage as a file would hold it: an image, then the writes since, each stored
before its answer goes, and the object's alarm deleting expired rows and
writing a new image when one is worth it. There is no process to run, no
volume and no instance count: an object is one writer, as a file is.
-
Install the two packages and wrangler.
npm install @fennecdb/web @fennecdb/cloudflare npm install -D wrangler -
Bind the object's class. A class a new account makes is SQLite-backed, and
persistkeeps the database in its SQL storage.wrangler.jsonc{ "name": "my-fennec", "main": "worker.ts", "compatibility_date": "2026-09-01", "durable_objects": { "bindings": [{ "name": "TENANT", "class_name": "Tenant" }] }, "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Tenant"] }] } -
The Worker: the
Tenantclass of A database a Durable Object, and afetchthat lets in only the callers holding its token before it sends a tenant's statements to that tenant's object. The class there is typed, so the file isworker.ts: that page's code, with this in place of itsexport default.integrations/cloudflare/example/worker.jsis the same Worker in JavaScript, importing from the repository where yours imports the packages, run by its test underwrangler dev.worker.ts// In Env, beside TENANT: FENNEC_TOKEN: string; const enc = new TextEncoder(); /** Whether the request carries the Worker's token, compared in constant time. */ async function allowed(req: Request, env: Env): Promise<boolean> { const [got, want] = await Promise.all( [req.headers.get('authorization') ?? '', `Bearer ${env.FENNEC_TOKEN}`] .map((s) => crypto.subtle.digest('SHA-256', enc.encode(s))), ); return crypto.subtle.timingSafeEqual(got, want); } export default { async fetch(req, env) { if (!env.FENNEC_TOKEN || !(await allowed(req, env))) { return new Response('unauthorized', { status: 401 }); } // POST /t/<tenant>/query, to that tenant's object const m = new URL(req.url).pathname.match(/^\/t\/([a-z0-9_-]+)\/query$/); if (!m || req.method !== 'POST') return new Response('not found', { status: 404 }); const tenant = env.TENANT.get(env.TENANT.idFromName(m[1])); const { sql, params = [] } = await req.json<{ sql: string; params?: unknown[] }>(); return Response.json(await tenant.query(sql, params)); }, } satisfies ExportedHandler<Env>; -
The deploy, then the token: until it has one the Worker answers 401 to everyone.
npx wrangler deploy TOKEN=$(openssl rand -hex 32) # keep it: wrangler never shows a secret again echo "$TOKEN" | npx wrangler secret put FENNEC_TOKEN curl -X POST https://my-fennec.<account>.workers.dev/t/acme/query \ -H "Authorization: Bearer $TOKEN" -d '{"sql": "collections"}'
- The Worker is the access layer. The server's scoped tokens and rules (HTTP security) are a server's; in a Worker, what a caller may run is its own code. One that runs whatever FennecQL it is sent gives every holder of its token the whole database, so a page or an app's users get endpoints for what they may do instead, each its statement, as Functions and webhooks writes them.
- Collation data for scripts the module does not carry is fetched from a URL unless the Worker hands it from its bundle (Limits).
- A cold start, after an eviction or a deploy, reads the database back: tens of milliseconds for 10 000 rows, under 200 for 50 000 (A cold start).
- Apps anywhere reach the Worker as they would a server: its URL and its token (Functions). Data in Durable Objects and functions on Vercel or Lambda make a stack with no server in it.
Distributed: one URL in front of regions
Tenants live on fennec-server nodes, a file each, in regions
you run on VMs of any cloud; each region has a router that
leases its nodes and fails them over, and a standby in another zone (Tenants and sharding). In front of them all is the
global entry, a Worker (integrations/cloudflare/entry):
https://db.example.com/t/<tenant>/... reaches the routers
of the region the tenant lives in, from wherever the client is.
clients, every continent https://db.example.com/t/<tenant>/...
|
the entry Worker (REGIONS, ENTRY_TOKEN, an Access service token)
| |
Cloudflare Tunnel + Access Cloudflare Tunnel + Access
| |
region eu: router, standby region us: router, standby
nodes in fra and ams nodes in iad and pdx
each node's archive -> R2 each node's archive -> R2- Homes are learned, not configured. The router that forwards a
request to the tenant's node names the node's region in its answer, to
the entry alone, and the entry keeps it, shared with its colo's other
isolates through the Cache API. A tenant it has not seen goes to the
region of the client's continent (Cloudflare's
request.cf.continent), whose router serves it or relays it home once; a tenant moved since costs one hop, never an error. - Reads near the client. A read marked
Fennec-Read: replicagoes to the region of the client's continent first, answered there from the tenant's read replica; writes always go home. - A router down is passed over for its region's standby. A known tenant's request never goes to another region; an unknown one's goes on to the next region, whose router relays it home.
- No open port. Each router is reached through Cloudflare Tunnel
(
cloudflaredbeside it), whose rules pass a tenant's paths alone:/_shard/,/_replicationand/_metricsanswer 404 at the edge. Cloudflare Access on each tunnel's hostname admits the service token the entry holds and nothing else, and the routers drop everyCf-Access-*header before a node sees the request. - Archives in R2. An archiver on another machine keeps every write of a node with its time, copied to a bucket (R2, S3, B2) by rclone every five minutes, for a restore to any moment.
- A plain Worker, not a Workers for Platforms dispatch, which would put a dispatch in every database request's path.
cd integrations/cloudflare
# entry/wrangler.jsonc: REGIONS -- each region's routers, the one keeping its
# directory first, and the continents it serves -- and DEFAULT_REGION
npx wrangler secret put ENTRY_TOKEN --config entry/wrangler.jsonc
npx wrangler secret put ACCESS_CLIENT_ID --config entry/wrangler.jsonc # the Access service token
npx wrangler secret put ACCESS_CLIENT_SECRET --config entry/wrangler.jsonc
npx wrangler deploy --config entry/wrangler.jsonc"REGIONS": {
"us": { "routers": ["https://router-1.us.example.com", "https://router-2.us.example.com"], "continents": ["NA", "SA"] },
"eu": { "routers": ["https://router-1.eu.example.com", "https://router-2.eu.example.com"], "continents": ["EU", "AF"] }
},
"DEFAULT_REGION": "eu"The machines behind it come from the repository's deploy/:
a systemd unit for a node, a router and its standby, the global router, an
archiver and its copy to the bucket, and cloudflared, with the
tunnel's rules, the alerts and the operator's runbook;
make drill breaks two regions on purpose in Docker and holds them
to losing no acknowledged write. The parts are on One URL for every region, Regions, Read replicas and Deploying it.
The rest of Cloudflare
- A Worker as an endpoint in front of a server or the objects: a webhook arriving, a check the rules cannot say, a call to a third party before the write, with a token of its own (Functions and webhooks).
- Cloudflare Access as the identity provider. A server takes
Access's JWTs as scoped tokens, its keys from the team's
/cdn-cgi/access/certsand--jwt-audiencethe application's tag; a Worker in front moves theCf-Access-Jwt-Assertionheader toAuthorization(Cloudflare Access). - R2 for files. The bytes in R2, their facts a row; the backend, a Worker among them, signs a link only after the server has said yes (Files with S3 and R2).
- Cloudflare Containers is not a home for the server: its disk is ephemeral, and an instance that sleeps starts again from the image. Persistence there would be R2 mounted as files, which this page's rule excludes.
Cloudflare's pieces on other platforms
Each part of the Cloudflare setup above has a counterpart, or none, on the
other platforms. Only Cloudflare's are built and tested here; where a table
says an adapter, it is one no one has written yet, shaped as
@fennecdb/cloudflare is. The shortest way off Cloudflare is often
to keep only its front: the entry Worker, Tunnel and Access stand in front of
servers on VMs of any cloud.
A database's home with no server
| Platform | Its counterpart of a Durable Object | fennecdb there |
|---|---|---|
| Fly.io | a Machine and a volume for each tenant, its requests sent to it with the fly-replay header (instance=); a body over 1 MB is not replayed | works today: fennec-server itself in each Machine (Fly.io); the map from a tenant to its Machine is your front app's |
| Rivet Actors | a keyed actor with an SQLite database of its own, on Rivet's cloud or yours | the closest: @fennecdb/cloudflare keeps a database in an object's SQL storage, a table a generation and a row a write, and an adapter would keep it in the actor's |
| Azure | Durable Entities: an entity of Durable Functions handles one operation at a time | an adapter: the image and the writes in the entity's state |
| Restate, Dapr, Orleans | a virtual object, an actor, a grain: one writer for each key, over a state store | an adapter, as above |
| Deno Deploy | Deno KV: atomic writes checked against a version, but no single writer, and a value of 64 KiB at most | the weakest fit: an adapter would need a lease of its own and the image in chunks |
| AWS, Google Cloud, Vercel, Netlify, Fastly, Supabase | no keyed single writer with storage | a server elsewhere, the functions its clients (Functions) |
An entry in front of regions
| Platform | Its counterpart of the entry Worker | fennecdb there |
|---|---|---|
| Fastly Compute | code at the edge with the client's location, a cache, backends and their headers; a request runs 2 minutes at most | the closest: the entry's logic would port, its long subscriptions reconnecting at the bound |
| Vercel | Routing Middleware or an Edge Function, the client's country in x-vercel-ip-country; an answer begun within 25 s and streamed for up to 300 s; its runtime cache is a region's | a front that learns homes a region at a time |
| Netlify | Edge Functions, the client's location in context.geo | a front, as Vercel's |
| Fly.io | fly-replay with region=: a server sends a request on to another region | a region's front can hand a tenant's request to its home region |
| AWS, Google Cloud, Azure | CloudFront with Lambda@Edge, the global load balancer, Front Door: each routes by host, path or the client's geography | a tenant's region written in its hostname, rather than learned |
No open port, one caller let in
| Platform | Its counterpart of Tunnel and Access |
|---|---|
| AWS | CloudFront VPC origins: an ALB, an NLB or an EC2 instance in a private subnet, reached by CloudFront alone |
| Azure | Front Door Premium with Private Link to the origin, approved on the origin's side |
| Google Cloud | Identity-Aware Proxy in front of the load balancer, which admits named users and service accounts |
| Fly.io | the private network: a Machine with no public address, reached over .internal or Flycast by the organization's apps |
| any cloud | cloudflared runs on any machine: the deploy/ kit's tunnel works in front of a VM anywhere |
Object storage for archives and files
An archive goes to a bucket by rclone, which speaks all of them:
s3 for S3, R2, Tigris (Fly.io's), Backblaze B2's S3 API and
Supabase Storage's S3 endpoint, gcs for Google Cloud Storage,
azureblob for Azure Blob Storage. The files
recipe is the S3 API's calls: S3, R2, Tigris, and Cloud Storage through its
S3 interoperability; Azure Blob, Vercel Blob and Netlify Blobs speak their own
APIs, which the recipe does not.
An identity in a header
The server reads Authorization: Bearer alone and takes HS256,
RS256 and ES256 tokens, its keys from a file a job of yours fetches
(Keys); a proxy in front moves a
platform's header there, as for Access.
| Platform | Header and token | The server |
|---|---|---|
| Google Cloud IAP | x-goog-iap-jwt-assertion, ES256, keys at https://www.gstatic.com/iap/verify/public_key-jwk, aud /projects/<number>/global/backendServices/<id> | takes it, as it takes Access's |
| Azure App Service | with its token store on, Entra's ID token in X-MS-TOKEN-AAD-ID-TOKEN (RS256); X-MS-CLIENT-PRINCIPAL is base64 JSON, not a token | takes the ID token with Entra's keys, the app passing it on |
| AWS ALB | x-amzn-oidc-data, ES256, its parts base64 with padding and its key fetched one by one | refuses it, as a strict JWT reader does: verify it in the app, or send the identity provider's own token (Auth, Cognito) |
| Vercel, Netlify, Fly.io, Fastly | none of their own | an identity provider's tokens: Clerk, Auth0, Supabase Auth, Cognito, Firebase (Auth) |
Functions: clients from anywhere
Vercel, Netlify, AWS Lambda, Cloud Run, Cloud Functions, Azure Functions
and Deno Deploy keep no disk a database can live on (below), so a function there is a client: of a
fennec-server on a platform above, or of a Worker holding the
databases in Durable Objects (above). Every client is
HTTP, so a function has no connection pool to run out of, and the JavaScript
one, @fennecdb/web/client, needs fetch alone, so it
runs in Node, Bun, Deno and the edge runtimes as it is.
import { connect } from '@fennecdb/web/client'; // the builder and the HTTP client, no WebAssembly
// Once an instance, outside the handler: the calls after the first reuse it.
const db = connect(process.env.FENNEC_URL, {
token: process.env.FENNEC_TOKEN,
timeout: 5000, // ms to an answer's head, under the function's own limit
});
export async function POST(req) {
const { id, title } = await req.json();
// A retried invocation sends the write again: the key makes it once.
await db.withIdempotencyKey(`note-${id}`).from('notes').insert({ title });
return Response.json({ ok: true });
}- Made once an instance. Python's
Client, Go'sfennecdb.Newand .NET'sFennecClienttoo: at module scope, in Lambda's init phase, not in the handler. - Bounded under the function's limit. A client bounds every request
in time (
timeout, 30 s unless given) and sends one again only where it cannot have run or may run twice: a read, or a write carrying an idempotency key (Retrying a write). Set the timeout under the platform's, so the function answers rather than being cut off mid-wait. - A platform's retry is a second write. Lambda tries an asynchronous invocation again, and a queue delivers a message again; key such writes by the event, its id or the message's, and a server answers the second as it answered the first.
- Private addresses. A function reaching a server's private address needs the platform's VPC attachment (a Lambda in the VPC, Cloud Run's Direct VPC egress, Azure's VNet integration); one without it is given an HTTPS address and the token. A Worker needs neither.
A read-only copy inside the function
A function can also hold a database in its own memory, read-only: a catalog, a search index, data that changes with a deploy. The image is built once, shipped in the bundle or a bucket, and loaded at a cold start; the module runs in Node, Bun and Deno as in a page, as the site's own search runs in the page from an image. Its writes stay in that instance and are lost with it: data that changes goes to a server.
import { readFile, writeFile } from 'node:fs/promises';
import { Fennec } from '@fennecdb/web';
const db = await Fennec.open(await readFile('node_modules/@fennecdb/web/fennec.wasm'));
db.run('create collection products (name text @text, price int @sorted)');
db.run("put products {name: 'red fox mug', price: 12}");
await writeFile('catalog.fennec', db.snapshot());import { readFile } from 'node:fs/promises';
import { Fennec } from '@fennecdb/web';
// Once an instance: the module and the image read at a cold start.
const db = await Fennec.open(await readFile('node_modules/@fennecdb/web/fennec.wasm'));
db.load(await readFile('catalog.fennec'));
export async function GET(req) {
const q = new URL(req.url).searchParams.get('q') ?? '';
return Response.json(db.run('get products select name, price match name $1', [q]));
}The image can also be your server's own data: a file fennec
backup wrote (Backups) loads as it is. A backup
copied to the bundle or the bucket at each deploy, or each night, gives every
instance the server's database as of that backup, read without a request to
the server. Use the @fennecdb/web of the server's release or a
later one.
fennec backup https://db.example.com catalog.fennec --token "$REPL"Lambda, Cloud Run and Vercel give a function gigabytes of memory, so an image of tens of megabytes loads; a cold start pays its load, tens of milliseconds for 10 000 rows (A cold start).
Platforms that are not a home
These run your apps and functions, which are clients of a server elsewhere or of a Worker (Functions, below). None gives a process a block disk it keeps.
| Platform | Why not |
|---|---|
| ECS on Fargate | An EBS volume belongs to one task: a service's volumes are deleted when the task ends, so a replacement starts empty (or from a snapshot, a copy). EFS is NFS. ECS on EC2 can bind-mount an instance's disk, with the task pinned to that instance; at that point it is a VM with extra steps. |
| AWS App Runner | No volumes. It is also closed to new customers. |
| AWS Lambda | No persistent disk; EFS is NFS. |
| Cloud Run, Cloud Functions | Volumes are a Cloud Storage bucket through FUSE, Filestore over NFS (with locking off) or memory. |
| Azure Container Apps, Container Instances, App Service | The persistent volume is Azure Files, SMB or NFS. The rest is ephemeral. |
| DigitalOcean App Platform | No volumes; the local file system is lost at a deploy. |
| Heroku | Each dyno's file system is discarded when it stops or restarts. |
| Vercel, Netlify, Deno Deploy, Azure Functions | Functions and static hosting: no disk of their own, and a function's memory goes with its instance. Vercel's Drives, since October 2026, mount only into a Vercel Sandbox, one read-write mount at a time, and its Functions, OCI images too, run on an ephemeral disk with no volume or Drive, scaled down after 5 idle minutes. |
Using it from your apps
Every app needs two values, the server's URL and its token, from its
platform's environment and secret store, as FENNEC_URL and
FENNEC_TOKEN say:
import os
from fennecdb import Client
db = Client(os.environ["FENNEC_URL"], token=os.environ["FENNEC_TOKEN"])import { connect } from "@fennecdb/web/client";
const db = connect(process.env.FENNEC_URL, { token: process.env.FENNEC_TOKEN });Go is fennecdb.New(url, fennecdb.WithToken(token)), .NET
new FennecClient(url, new() { Token = token }), and Swift, Kotlin
and Dart Fennec.connect(url, token: ...); Your language has each in full, and Mobile and native apps the apps'.
| Your app runs on | Reach the server at |
|---|---|
| Fly.io | http://my-fennec.internal:8080, or Flycast where you want Fly's proxy on the private network |
| Render | http://<internal-hostname>:8080, from the service's Connect menu |
| Railway | http://fennec.railway.internal:8080 |
| Kubernetes | http://fennec.<namespace>.svc.cluster.local:8080, a Service; a NetworkPolicy naming the apps that may |
| A cloud's VMs and VPC | the VM's private address, port 8080 open to the app's security group, firewall or network security group only |
- Functions are clients, made once an instance, bounded under the platform's limit and keyed against its retries: Functions.
- A browser never gets the server's token. Give it a scoped JWT
that names what its user may read and write, and let the server accept
the page's origin with
--http-cors(HTTP security and scoped access,--jwt-*). - Studio and the shell.
--studioserves the admin pages at/_studio/, behind the token (Studio). The shell opens a file, not a URL:fennec backupthe database and open the copy, or send statements withcurl(The shell). Reach a private address by the platform's tunnel (fly proxy,kubectl port-forward, a bastion or SSH) rather than by opening the port.
Backups, then more than one server
A disk snapshot is a crash-consistent copy: a fine extra, not the backup.
fennec backup takes the running database whole through the
replication stream, and fennec archive keeps the stream for a
restore to a moment. Give the server a replication token, as
FENNEC_REPLICATION_TOKEN in its environment beside the HTTP
token (the flag, --replication-token, shows in ps),
and run them from anywhere that reaches it; both read their token from that
variable too, where --token is not given.
fennec backup https://db.example.com nightly.fennec --token "$REPL"
fennec archive https://db.example.com /backups/archive --token "$REPL" --image-every 1h --keep 7d
# to the cloud's bucket, beside the archiver
aws s3 sync /backups/archive s3://my-bucket/fennec --delete # AWS
gcloud storage rsync --recursive /backups/archive gs://my-bucket/fennec # Google Cloud
azcopy sync /backups/archive "https://acct.blob.core.windows.net/fennec" # Azure
rclone sync --local-no-check-updated /backups/archive r2:fennec # R2, Spaces, B2, ...--local-no-check-updated, since the newest segment grows
while its database is written: rclone otherwise refuses a file that changed
as it read it (source file is being updated), and a busy
database's newest segment never reaches the bucket. Restoring to a moment,
and the bucket's side, are on Replication and
In object storage.
A server grows two ways. Reads: --replica-of starts a
read replica on a second machine, on its own disk, fed from the primary's
(Replication; POST
/_replication/promote makes it the primary when the first is gone).
Writes, many tenants or regions: a database for each tenant behind a
router, each a file on a node (Tenants and
sharding; Deploying it
has the systemd kit and runbook, and the global entry one URL across
regions). Neither is a second process over the same file.