Flows and jobs
On this page

What follows a change runs after its commit, each step a plain function of
yours, at least once, retried as the design says, with every try on record.
Mail's archive starts archiveCleanup. Its second step's first try fails in the
demo, and the tools say so.
Try one without Redis
An inline flow needs no relay, worker or broker. On the quickstart's project,
give Notes.add an emits and add a flow and a job at the top level of
designs/my-api.service.json, beside entities and services:
"flows": [ { "id": "on-note", "type": "Flow",
"props": { "name": "onNoteAdded", "on": "note.added", "durability": "inline" },
"slots": { "steps": [ { "id": "on-note-log", "type": "Step", "props": { "name": "logIt", "retry": 1 } } ] } } ],
"jobs": [ { "id": "tidy", "type": "Job", "props": { "name": "tidyNotes", "retry": 1 } } ]"emits": "note.added" goes in the add command's props. Sync writes a
migration with the outbox and flow_run tables (0003_changes.sql) and
stubs in my_api_impl/flows.py and jobs.py that fail until written. Sync also
adds Python packages for the flows: run uv sync in backend/ (or start
everything through uv run, which syncs first). Put a
log.info(…) in log_it and tidy_notes, then:
$ GLOBETROTTER_ENV=local uv run python -m my_api_core.migrate
db: applied 0003
$ GLOBETROTTER_ENV=local uv run python -m my_api_core.jobs run tidyNotes
job tidyNotes: done
$ curl -s -X POST localhost:8000/notes/actions/add -H 'content-type: application/json' -d '{"text":"flowtest"}' # add -H 'X-Api-Key: dev-member-key' if sign-in is onThe server's log then holds INFO my_api_impl.flows: note added: {'id': '…', 'text': 'flowtest'}, and flow_run has one row per try, flow onNoteAdded,
step logIt, attempt 1, status done; the job's row has event_type
job. Not tried here: the relay, the worker, the scheduler, worker and
durable flows.
The path of an event
- A command that
emitswrites an event in the same transaction as its change. The event is a CloudEvent row in the outbox. - The relay claims waiting events and runs them or hands them on.
- A flow listening for that event runs its steps in order.
- Each try of a step is a
flow_runrow: done, failed and tried again, or dead after its last try.
A step done for an event is never run again. A step may run twice if its worker died mid-way; it never runs zero times.
Flows
A Flow names its event (on) and its steps. Its durability says where it
runs:
| Durability | Runs |
|---|---|
inline |
In the app, after the commit. Good for tests and a laptop. |
worker |
On a worker, after the relay hands the event over. Retried. |
durable |
Survives a restart mid-flow. |
A components file may lower a flow's durability for an environment, never raise
it. Each step has retry (0 to 20 more tries) and timeout (seconds, 30 by
default). Steps are methods in <app>_impl/flows.py (flow_steps.py when a
service is itself named Flows); see
Your code.
A try left running long after its step's timeout is said so by get_runs: the
worker stopped mid-way. Its event is handed on; that try is not run again.
The relay
$ uv run python -m <app>_core.relayThe relay claims what is waiting. One UPDATE decides who holds a row, so two
relays never hand on the same event (SKIP LOCKED on postgres). A claim is a
lease of five minutes: a row a dead worker left is handed on again after it.
Each event is one log line. Run the relay as its own process when the design has
flows.
The worker
$ GLOBETROTTER_BROKER_URL=redis://… uv run python -m <app>_core.workerPython's worker is Taskiq, on Redis when GLOBETROTTER_BROKER_URL names one.
Without a broker the relay runs the steps itself. Rust's flows use apalis on
the flow store's own database, so its queue needs no broker, and Redis as a
broker is Python's alone.
An event is done once its steps ran, not once it was handed over. A worker killed mid-step leaves the event held, and it is handed on again when the lease runs out.
When Redis is gone (run on 19 November: docker compose stop redis, a command pressed meanwhile, start; transcript), the worker says so once and waits for it (one line when it
is back). The relay says so once, lets go of what it could not hand on and
tries every pass. The events wait in the outbox and go the moment Redis is
back.
Jobs and schedules
A job's timeout (seconds, 1 to 86,400, default 300) is how long one try may run: past it the try is cut and fails with took longer than <n> s, and is tried again if the job has retries. A run still running ten seconds longer than the timeout (so 310 s by default, 1510 s for a nightly export that says timeout: 1500) is taken to have been left by a stopped process, and the next scheduler or worker marks it abandoned. Set it on the job, not in generated code. Lint warns (job-timeout-over-schedule) when a timeout you set is longer than the schedule's gap, because a run still going at the next due minute makes that minute skipped.
A Job is started by a Schedule (cron, in UTC) or by hand. A schedule's cron is five fields of numbers (minute hour day month weekday), each *, a number, a range 1-5, a list or a step */15; month and weekday names (JAN, MON, in any case) are accepted. The lint refuses what the two targets read differently: a day of the month together with a weekday, a weekday range ending in Sunday as 7 (0-7, 5-7, FRI-SUN: write 0, or list the days, 1-5,0), a step larger than the field's top value, @daily and the like, ?, L, #, seconds. It refuses a day that never comes too (31 February):
$ uv run python -m <app>_core.jobs run <name>
$ uv run python -m <app>_core.schedulerjobs run writes the same flow_run rows a scheduled run writes, says done or the way it died in one line, and exits 0 or 1. It takes no claim on the schedule's minute: when the job's schedule is due in the minute it began, it says so, and the scheduler runs it as well.
The scheduler is a process to keep running where you want cron to fire. At start Python's scheduler says which jobs it runs and when each is next due (scheduler ready: tickItems next at 04:31 UTC), and a local Python API says in one line that jobs run in the scheduler (Rust's worker says worker ready: tickItems next at 04:31 UTC on a line of its own after its ready for the jobs … line). Both targets fire at the top of the minute (:00, UTC), not at the second the process started, and a minute missed while nothing ran (stopped, asleep) is not caught up: a restarted scheduler or worker runs the job at the next due minute. Every due minute of every job is claimed first, so it runs once however many schedulers run and however often one restarts: in the broker's Redis when GLOBETROTTER_BROKER_URL names one, else in the first of the design's Redis stores that has a URL (<app>:schedule:<task>:<minute>, SET NX, 120 seconds; both targets look in this order), else in the database, a row of flow_run (event_type schedule, an id made from the same key, so a second insert of one minute adds nothing). Python's scheduler and Rust's worker use the same key and the same row, so one of each on one database or one Redis do not both run a job (run on 27 November on one sqlite file: a Rust worker and a Python scheduler, one run a minute, the Python one saying claimed by another scheduler; two Python schedulers, the same; earlier, on 19 November, two schedulers and a restart inside the minute on Redis, transcript). A claim that cannot be made lets the job run: a job is safe to repeat, a missed minute is not. A schedule that does not read, or can never come due, ends the scheduler (Rust: the worker) at start with one line and exit 1, nothing looping. Started ahead of its database it waits for the migrations, saying so once a minute. On SIGTERM or Ctrl-C the Python scheduler takes no new run, lets the one in flight finish for GLOBETROTTER_SCHEDULER_GRACE seconds (30), says Stopping: finishing <job> and scheduler stopped, and exits 0; a run still going when the grace ends is cancelled and marked abandoned. Rust's worker reads the same variable (GLOBETROTTER_SCHEDULER_GRACE, 30 s, though it is the worker there): after a stop it says Stopping: finishing <job> (up to 30 s: GLOBETROTTER_SCHEDULER_GRACE), and a job still going when the grace ends is marked abandoned (stopped before it finished), with job <job> did not finish in time: its run is marked abandoned, and the worker exits 0. A run left running by a process that was killed (SIGKILL, a power cut) is marked abandoned by the next scheduler, at its start and each minute, once it is older than the job's timeout plus ten seconds (get_runs shows the status); Rust's worker does the same for the jobs' rows, with the same words and bound (1 run was left running by a stopped process: marked abandoned; the bound is 310 s for a job's 300 s timeout); a job's schedule is not kept in a queue, so it is not run again for it, and its next due minute is the next run. A step of a flow left running by a killed worker is not marked (jobs only, as in Python): apalis's queue puts a dead worker's task back for another try, which writes a new row; that path was read in the crate, not run. The
job's body is a method in <app>_impl/jobs.py; until written it fails its run.
Jobs have retry and durability like a flow. When a service is itself named
Jobs, as fieldops' is, the jobs go in scheduled_jobs.py.
Fieldops' flagOverdue runs every 15 minutes and moves the open jobs past
their due time to Overdue, through the job's state machine. Finishing a job
emits job.completed, and the flow onJobCompleted runs tellDispatcher:
$ uv run python -m fieldops_core.jobs run flagOverdue
job flagOverdue: done
$ uv run python -m fieldops_core.jobs
flagOverdue */15 * * * * (UTC) last 2026-11-13 09:14:19: doneFrom work-transcript.txt.
Writing a job's body
A job's method takes ctx, as an operation of a service does: the repositories (ctx.db.<entity>) on one transaction that commits when the method returns and rolls back when it raises. Write through them: the audit and check_tenancy see a repository's writes, not a raw SQL statement's. A job runs outside any request, so under organisations it reads and writes every organisation's rows; every=True says so on purpose. A method written without ctx (async def mark_overdue(self) -> None) still runs, and reaches the data by engine("db").
from datetime import date
class Jobs:
async def mark_overdue(self, ctx: Context) -> None:
rows = await ctx.db.task.find(where=[("due_date", "lt", date.today())], every=True, unbounded=True)
for row in rows:
await ctx.db.task.update(row.id, overdue=True)The stub names the repository the job's name or words mention and shows this example for it. Run on sqlite in a scratch project: python -m <app>_core.jobs run markOverdue answered done.
What happened
Two tools, in the studio's Flows view and through MCP:
get_runs(design, flow?, event?, since?): each event's steps and their tries. A failed one lists what its event carried, and your file and line. Then the events still waiting for the relay, so "did anything get stuck overnight?" has its answer.look_at_traces(design, request?, trace?, since?): a request as a tree of spans with times: the route, its queries, and the flow steps its events ran. A request's trace and the worker'strace … on <event>line carry the same trace id.
A step whose last run died is a to-do in Status until a run of it succeeds. Your own log lines show in the app and the relay.
Locally the spans live in backend/.globetrotter/traces.jsonl, the newest
5,000 (GLOBETROTTER_TRACES_KEEP sets how many). Asked for a request older
than those, look_at_traces says it was pruned, with both times.
Observability
One switch in the design turns on traces, metrics and logs:
- OTel traces: each request's queries, and the flows its events start, in one trace.
- structlog JSON logs with the request id and who asked.
- The
redactfields never as values: not in a span's attributes or its events', before every exporter, OTLP too. - The console on a laptop (
designs/components.local.jsoncan say so), OTLP deployed.
Rust gives the same tree from tracing: the route, its queries and the flow
steps as spans with the request id and who asked, JSON logs, and redact fields
replaced before every exporter.
Cache, search, files and notices
These small primitives belong to the same worker-side picture.
- Cache: keeps a query's answers per person for its ttl, forgotten when a command writes the same database. Redis by the store's URL (a dropped connection, or Redis restarted, is made again once), else memory. Memory is each process's own: with two processes on one database (two workers, or the Python and Rust targets side by side) a write by one leaves the other's cached read stale for up to its ttl. A Redis store is shared and forgets for both.
- Search:
GET /search/<name>?q=. Every word is found in one of its fields, each a prefix ("rev" finds review). Ranked by the engine: sqlite FTS5 by bm25, postgres full-text byts_rank, over the table or index its migration writes;LIKEand newest first elsewhere. Row rules are kept. - File: an upload, and a download by a signed link that expires. On local
disk, or in a bucket (
backend: s3) each environment names; the bucket was only run against a fake one (see Limits). - Notify: a template filled and sent by SMTP (
GLOBETROTTER_SMTP_URL) or a webhook (GLOBETROTTER_WEBHOOK_URL) when the environment names one, else the console andbackend/.globetrotter/sent.jsonl. SMS and push have no provider wired and go to the console. The webhook notice was sent, and SMTP sent to a test sink.
Events from outside, and calls out
A webhook's handler may emit an event: it is written
to the outbox with the delivery's body as its data, in the same transaction as
the record of the delivery in Python, and a flow listening for it runs after
the commit like any other. A state machine's transition may emit too, with
the row's fields as its data. A step that calls an outside service uses a
client: its timeout, retries and
breaker are the client's, and the step's own retry is on top of them.
Several processes
Several API processes on one store are fine: a row two of them change in the same moment is a 409 for the one that lost, to try again. So are two relays and two workers: no event is doubled.
Next: Deploy and operate, Studio and agents, Your code.