dabadataDocs
Concepts / Background workers

Concepts

Background workers

Most apps need no worker. A turn-based game against the machine runs with no backend at all: the machine's moves are the server's random picks, and the player's browser computes the result, which the server checks and caps by the match's pot (a machine opponent with no backend). Bobi Coin's games, The Kidnapper and Warcall, run that way, with no worker. A worker is for an app that needs trusted logic of its own: a machine that plays smart with information no player may see, a timer that fires when nobody is calling, a step only a trusted party may take. dabadata does not run your code (server functions are not built yet), so this logic runs in a process of yours: a worker. This page describes a worker that needs no public address, no loop and no secret key, and that scales to any number of identical copies. It separates what dabadata provides from the example code in the repository that you copy.

When you need a worker

Most apps need none: rules, actions, rounds, server randomness and agreements, scheduled actions and webhooks cover the common cases with nothing of yours running. A worker is for logic that is code, must not run on a player's device, and must run when something happens:

  • A machine opponent that must play smart in secret. It reads what no player may see (the player's hand), chooses the machine's moves after a thinking time, and settles each round as the agreement's authority. A machine that plays at random needs no worker (a machine opponent with no backend), and neither do players against each other (server-verified).
  • Timers of its own. The machine's thinking time, a reminder ten minutes after an order, a deadline in a match where only the machine is left to call the round's status.
  • Trusted steps. Derived rows recomputed after an admin edit (statistics, a calibrated model), a call to an outside API with a key of yours, anything no client may be trusted to do.

For a fixed timetable use a scheduled action; for one reaction in a serverless function use a webhook.

What dabadata provides, what you write

The worker is your own process. dabadata gives it the pieces below, all of them ordinary platform features documented elsewhere; the rest is your code, and the repository has an example of that code you can copy.

PieceWhoWhere
Events without a public address: a live subscription on one outbound WebSocketdabadata (platform)Live subscriptions
An identity for the worker: a hosted user holding a role no one else getsdabadata (platform)Managing users, rules
Writes only the worker may make: actions with allow: { role }, expect guards, a round's submit with a participant, an agreement's authoritydabadata (platform)Actions, submit, agreement
Answers that make a repeated step harmless: 409 on a failed expect, already_in, round_over, already_settleddabadata (platform)Conditional writes, Pitfalls
Webhooks, when your backend has a public URL anywaydabadata (platform)Webhooks
The process, its job queue (Redis), its handlers, its deploymentYouYour code; the worker kit is an example to copy

The model: stateless jobs on a shared queue

A worker never loops and never keeps state in memory between events. It turns each event into a job on a queue that every copy of the worker shares, and each job runs once:

  1. An event becomes a job. A row changed (a match against the machine was created, a round closed). The event handler reads nothing; it only adds a job.
  2. A job does one step. It loads what it needs from dabadata, does one step (choose the machine's card, settle a round), writes through an action, adds the next jobs, and ends.
  3. Time is a delayed job. "Choose in 2.4 seconds" or "check the round at its deadline" is a job with a delay, kept in the queue, never a setTimeout in a process. A restart loses no timer.
  4. Every step is safe to run twice. Queues deliver at least once: a retry, a process killed mid-job, a sweep after a reconnect can all run a step again. Each write carries a guard the server checks in the same transaction - expect on the row's state, a round's one move per participant, an agreement's settle-once - and a 409 that says the step is done already (already_in, round_over, already_settled) counts as success. Any other 409 (a failed expect) is success only when a fresh read shows the step is no longer needed - another copy did it, or the state moved on; otherwise throw, and the queue retries the job from fresh reads. A step without such a guard must check the state it read before it writes.
  5. Any number of copies. Every copy holds its own subscription, so every copy sees every event and adds the same job. The queue drops the duplicates by job id, so the work is done once whether one copy runs or ten.

Job ids carry the row's state

The dedupe works only if the same event always gives the same job id, and a new state a new one:

JobIdKept after it ran
Made from an eventThe row's id and the columns that make its state: round.<id>.<status>.<in_a>, match.<id>.<status>.<round>About an hour, so the same change seen by another copy, or replayed after a reconnect, is dropped
Added by a handler (a timer, the next step)Stable, without the state: choose.<round id>, deadline.<round id>No: dropped only while one with that id waits or runs
A sweep (recover after a reconnect, rebuild derived rows)Fixed: recover, stats, debouncedNo: one waits; one more may follow a running one

Never use a random or time-based id for an event job: every copy would add its own and the step would run once per copy. (BullMQ refuses : in a custom id; use . between the parts.)

Why there is no polling loop

A loop that asks "anything new?" every second makes a request every second whether or not anything happened, for as long as the worker runs: each one counts toward the key's request rate and is written to your trace and API log like any read, and a second copy of the worker doubles all of it. It also reacts up to one interval late. A worker on a live subscription sends nothing but the socket's pings while nothing happens, and hears about a change the moment it commits.

The event source: a live subscription

A live subscription is an outbound WebSocket, so the worker needs no public address, no open port and no route on anyone's proxy. Who it signs in as matters:

  • Keys never open sockets. A secret key or a restricted key on /v1/live is refused with 401 restricted keys do not open sockets; use a user token. So the worker signs in as a hosted user of the project (end-user accounts, auth.users.enabled) that holds the worker's role.
  • A role nobody else gets. Declare a role for the worker (worker, kid_worker) and give it only to that user. Sign-up gives auth.users.defaultRole; roles change only with the secret key, on the console's Users page, or by an app admin within manageRoles - leave the worker role out of manageRoles.
  • Read rules that let it in. The worker's role must be able to read every row it subscribes to; otherwise the subscription is refused with 403 forbidden and the rule's explanation. Use where on the subscription so it gets only the rows it acts on (the matches against the machine, not every match).

Make the user once, with the secret key, from your own machine (or on the console's Users page). A user made with a password can sign in at once; use an address at a domain you control or example.com, since nothing is mailed to it:

bash
curl -X POST https://dabadata.com/v1/project/users \
  -H "Authorization: Bearer $DABADATA_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]","name":"Game worker","role":"worker","password":"<a long random password>"}'

The worker then needs only the publishable key, that email and that password - never the secret key. With the JavaScript client (Bun or Node 22+, both have WebSocket):

ts
import { createClient } from "./lib/dabadata.js";

const db = createClient({ url: "https://dabadata.com", key: process.env.DABADATA_PUBLISHABLE_KEY!, storage: "memory" });
await db.auth.signIn({ email: process.env.WORKER_EMAIL!, password: process.env.WORKER_PASSWORD! });

db.subscribe("rounds", { where: { player_b: "bot", settled: false } }, {
  onRows: (rows) => rows.forEach((row) => onEvent("update", row)),   // first load, and again after every reconnect
  onChange: ({ op, row }) => onEvent(op, row),
  onError: (e) => { if (e.status === 403) process.exit(1); },        // the user lacks the role: fix it, do not retry
  onStatus: (s) => { if (s === "open") addRecoverJob(); },            // every (re)open: look at every live match again
});

// onEvent reads nothing: it only adds a job whose id carries the row's state.
function onEvent(op: string, row: any) {
  if (op === "delete") return;
  queue.add("round", { id: row.id }, { jobId: `round.${row.id}.${row.status}.${row.in_a ? 1 : 0}`, keepMs: 3_600_000 });
}
  • Reconnects. The client reconnects by itself and sends every subscription again; the server answers each with fresh rows (onRows), which hold whatever changed while the socket was down. Replay them as events (the job ids drop what was already done) and add one debounced recover job that looks at every live item again, timers included.
  • Tokens. The client refreshes the access token by itself. If the refresh token is dead (revoked or expired), sign in again; a refused password is fatal - exit and let the supervisor restart the process after you fix it.
  • Each copy signs in on its own. Do not share a token between processes. Sign-in is rate limited (10 per 15 minutes per email, 30 per IP): many copies restarting at once, or a crash loop, can get 429 - retry with a backoff. Each copy's socket counts toward the workspace's connections.

Webhooks instead, when you have a public URL

If your backend already has a public HTTPS address (a serverless function, an app server behind your own domain), a webhook can be the event source instead: dabadata calls your endpoint after each matching change commits, signs it and retries it for 15 hours. The endpoint verifies the signature, adds the same job the subscription would have added, and answers 204. Writes then go with a restricted key of the worker's role, since no user signs in.

Live subscriptionWebhooks
NeedsAn outbound connection onlyA public HTTPS endpoint of your own
Signs in asA hosted user with the worker roleNothing (dabadata calls you); writes with a restricted key
Missed eventsFresh rows on every reconnect, plus your recover jobRetries for 15 hours; a delivery log with "send again"
Counts towardConnections (one per copy)The monthly webhook allowance

Both feed the same job handlers, so a worker can support both. The public address must be yours: dabadata adds no routes for an app.

Writing: actions only the worker may call

Give the worker no write rule on a table. It writes through actions whose allow is its role, each step guarded by the state it expects, so a leaked password can do only what those actions allow and a repeated job changes nothing:

json
"machine_play": {
  "allow": { "role": "worker" },
  "params": { "round": { "type": "ref", "table": "rounds" }, "card": { "type": "ref", "table": "hands" } },
  "steps": [
    { "op": "check", "table": "rounds", "id": "$params.round", "expect": { "mover_b": "bot" }, "ref": "r" },
    { "op": "check", "table": "hands", "id": "$params.card", "ref": "h",
      "expect": { "owner": "bot", "alive": true, "match": "$step.r.match" } },
    { "op": "submit", "table": "rounds", "id": "$params.round", "participant": "$step.r.mover_b",
      "values": { "card": "$params.card", "kind": "$step.h.card" } }
  ]
}

A second run of this job gets 409 already_in (the machine's move is in) or round_over (the round closed): done. To settle a round alone, the worker is the authority of the match's agreement; a second settle gets already_settled. The full pattern is server-authoritative (optional; most games need no worker).

The worker kit (example code)

The dabadata repository holds a small worker kit, examples/bobicoin/worker-kit/, that does everything on this page except your app's logic. It stays in the repository as an example of the pattern; Bobi Coin's games do not use it (their machine opponents are the server's random picks). Copy it; it is not a package.

FileWhat
runner.tsrunWorker(...): reads the environment, picks the queue (BullMQ when REDIS_URL is set, else in memory), signs in, holds the subscriptions, passes changes to your event mapping and jobs to your handlers, lets running jobs finish on SIGTERM
live-source.tsLiveSource: signs in as the worker user, one socket with your subscriptions, replays each (re)load as events (reload: true), calls onConnected on every (re)open, signs in again when the refresh token dies, treats a refused sign-in or a 403 subscription as fatal
queue.tsThe Queue interface and JobOptions (delayMs, jobId, keepMs, debounce); MemoryQueue with the same semantics for tests and development, where several handlers on one queue stand for several processes
queue-bullmq.tsBullQueue: the same interface on BullMQ and your own Redis - delays in Redis, dedupe by id, debounce, retries with backoff (8 tries), a job of a dead process handed to another one
api.tsApi: rows, transactions, actions and round status over the HTTP API as the worker user (renews the token on a 401); alreadyDone(e) says whether a 409 means "done already"; guarded(step, stillDue) runs a guarded step and treats any other 409 as done only when stillDue(), a fresh read, says so
redis-check.tsChecks BullQueue against a real Redis: two processes, a delayed job, dedupe, debounce, a retry, a process killed mid-job

An app gives the runner its subscriptions and three functions:

ts
import { runWorker } from "./worker-kit/runner.ts";
import { EVENT_KEEP_MS } from "./worker-kit/queue.ts";
import { alreadyDone } from "./worker-kit/api.ts";

await runWorker({
  game: "duel",                                   // for the logs
  queue: "duel",                                  // its queue on Redis (WORKER_QUEUE overrides)
  subscriptions: [
    { table: "matches", where: { player_b: "bot", status: { $in: ["invited", "active"] } } },
    { table: "rounds", where: { player_b: "bot", settled: false } },
  ],
  worker: ({ api, queue }) => ({
    // A change -> jobs. Reads nothing.
    onEvent: async ({ table, op, row }) => {
      if (table === "rounds" && op !== "delete")
        await queue.add("round", { id: row.id }, { jobId: `round.${row.id}.${row.status}.${row.in_a ? 1 : 0}`, keepMs: EVENT_KEEP_MS });
    },
    // Every (re)open: look at every live match again.
    onConnected: () => queue.add("recover", {}, { jobId: "recover", debounce: true, delayMs: 1000 }),
    // One job: load, one step, write, next jobs, end.
    handle: async (name, data) => {
      if (name === "round") {
        const r = await api.get("rounds", data.id);
        if (!r || r.settled) return;
        if (r.status === "closed") return queue.add("settle", { id: r.id }, { jobId: `settle.${r.id}` });
        await queue.add("choose", { id: r.id }, { jobId: `choose.${r.id}`, delayMs: 1500 });
      }
      if (name === "choose") {
        try { await api.action("machine_play", { round: data.id, card: await pickCard(api, data.id) }); }
        catch (e) { if (!alreadyDone(e)) throw e; }   // already_in / round_over: done; anything else: retried
      }
      // "settle", "recover": the same shape.
    },
  }),
});

The environment it reads: DABADATA_URL (default https://dabadata.com), DABADATA_PUBLISHABLE_KEY, WORKER_EMAIL, WORKER_PASSWORD, REDIS_URL, WORKER_QUEUE, WORKER_CONCURRENCY (jobs one process runs at a time, default 4). Without REDIS_URL the queue is in memory: one process only, and jobs waiting at a restart are gone (the recover job on connect picks the work up again).

Testing. Run two or three runners on one MemoryQueue (sharedQueue) against a test environment or a local server, move the queue's clock, call runDue(), and assert that each step ran once. The kit's own queue.test.ts checks the queue this way: several handlers on one queue, a moved clock, replicas racing, guarded steps.

Deploying a worker stack

Run the workers the way you run any backend: here, one Docker Compose project with its own network, a Redis for the queue, and one service per worker. Nothing of it is published to the internet; it only connects out to https://dabadata.com. A trimmed version of examples/bobicoin/deploy/docker-compose.yml:

yaml
name: game-workers
services:
  redis:
    image: redis:7-alpine
    # append-only: delayed jobs survive a restart; noeviction: BullMQ must never lose a key
    command: ["redis-server", "--appendonly", "yes", "--maxmemory", "40mb", "--maxmemory-policy", "noeviction"]
    volumes: [redis-data:/data]
    healthcheck: { test: ["CMD", "redis-cli", "ping"], interval: 10s }
    restart: unless-stopped

  game-worker:                       # no container_name, so it can scale
    image: oven/bun:1.4.4
    working_dir: /app
    command: ["bun", "game-worker.js"]   # bun build worker.ts --target=bun --outfile=game-worker.js
    env_file: game-worker.env        # mode 0600: DABADATA_PUBLISHABLE_KEY, WORKER_EMAIL, WORKER_PASSWORD
    environment:
      DABADATA_URL: https://dabadata.com
      REDIS_URL: redis://redis:6379
      WORKER_QUEUE: duel
    volumes: ["./game-worker.js:/app/game-worker.js:ro"]
    depends_on: { redis: { condition: service_healthy } }
    restart: unless-stopped
    stop_grace_period: 30s           # SIGTERM: running jobs finish first
    mem_limit: 192m

volumes:
  redis-data:
  • Scale with docker compose up -d --scale game-worker=3. The copies are identical and keep nothing between jobs; each holds one socket and signs in on its own.
  • Upgrade by replacing the bundle and recreating the service. A stopping copy finishes its running jobs; waiting and delayed jobs stay in Redis and the new copies take them. A job cut short runs again elsewhere (it is guarded, so that is harmless).
  • Several apps can share one Redis, each with its own queue name and its own worker user and role (Many apps in one project).
  • Rotate the password by deleting the user and making it again with a new password (its old tokens stop working at once), then redeploying the env file. The project API sets a password only when it makes a user.

The repository's examples/bobicoin/deploy/ has the scripts behind this: ops/create-worker-user.ts makes the worker user with a random password through POST /v1/project/users and writes the env file (mode 0600, prints no secret), and ops/deploy-workers.ts bundles each worker, copies the stack to a host over ssh and runs docker compose up with --scale. They run on the operator's machine with the secret key; the key never reaches the host.

What a worker never needs from dabadata

A worker built this way is an ordinary client of the public API. If yours seems to need any of the following, the design has gone wrong:

  • No route or code of your app on dabadata's servers, and no inbound port of its own: events arrive over its own outbound socket.
  • No database connection. It reads and writes through /v1/db, /v1/actions, /v1/transact and /v1/rounds, under its role's rules, traced as the worker user.
  • No secret key at run time. The publishable key and its own user's password are enough; the secret key stays with whoever makes the user.
  • No special address. It calls https://dabadata.com like any other client, so it runs on any machine and moves without changes.

Pitfalls

  • An in-memory queue with several copies. Each copy then has its own queue and every copy runs every job. Several copies need one shared queue (Redis).
  • Random or time-based job ids for events. The dedupe stops working; see job ids.
  • setTimeout for timers. Lost on a restart and run by whichever copy set it. Use a delayed job.
  • Reading in the event handler. Every copy would make the same read for every event. Add a job; read in the job.
  • A write without a guard. A retried job pays twice. Put expect on the state the step starts from, and count the "done already" 409s as success.
  • Swallowing every 409. A 409 can also mean the row is not yet in the state the step needs, or a conflict worth retrying. Treat it as done only after a fresh read shows the step is no longer due.
  • No recover on reconnect. A change made while the socket was down still arrives in the fresh rows, but a timer whose job was lost does not. The recover job re-adds the timers of every live item.
  • A read rule that leaves the worker out. The subscription is refused with 403; give the worker's role a read rule on every table it follows.
  • The worker role reachable by sign-up or app admins. Keep it out of defaultRole and manageRoles.
  • Redis that evicts keys. Set maxmemory-policy noeviction; an evicted key loses a job or its dedupe.
dabadata documentation, written against API contract v2.