Acta. Durable execution for .NET

learn acta

?

Try

Every answer is a short how-to: the handler, the call that starts it, the command that runs it, and the lines it must print. The code is lifted from programs in the Acta repository, and each page says how its program is checked. Each page is also plain Markdown, so your coding agent learns from the page you read.

Read as
Build the first project About an hour. A report service that retries, records its progress, and finishes the same job after you kill the process. Start the tutorial Hand it to your coding agent Paste one prompt. The agent reads the same how-tos as Markdown and builds from them. See the prompts

which one when

When two how-tos look alike, this tells them apart.

Something has to happen later
Work must not happen twice
A job has to wait
Work repeats on a schedule
One job becomes many

the how-tos, section by section

Each section goes in order. Start at the top and stop when you have what you need.

Start jobs

Every way to start work: now, later, once only, by name, or many at a time.

  1. 1Enqueue by the input's typeEnqueueAsync takes the input alone: its type names the job, so there is no name string to get wrong
  2. 2Enqueue by the job's generated callThe manifest's generated call names the job and takes its handler's parameters, several of them as one input
  3. 3Enqueue a job by its nameAn EnqueueJobRequest names the namespace and the job as strings, for a caller that does not have the job's types
  4. 4Write a job that takes no inputA job with no input: a handler with no parameters, enqueued by its generated call
  5. 5Pass one plain value as the inputThe input can be one plain value, such as a string or a number, with no record around it
  6. 6Keep several jobs in one classA class can hold several [Job] methods. Each is a job of its own, with its own generated call
  7. 7Run a job once, laterScheduleAsync(input, delay) stores the job now and makes it due after the delay. No process has to stay alive until then
  8. 8Schedule, sleep, and reschedule to an exact instantPin work to an instant instead of a delay: ScheduleAsync(input, runAt) starts a job then, SleepUntilAsync pauses a handler until then, and RescheduleUntilAsync runs the handler again then
  9. 9Keep a repeated request from creating a second jobA deduplication key makes an enqueue idempotent: a second enqueue with the same key answers the job that is already there
  10. 10Allow one job per hour or per dayA deduplication key built from a time bucket lets one job in per bucket: DeduplicationKey.PerTimeBucket here, with PerHour and PerDay as its fixed sizes
  11. 11Save a record and start its job in one transactionEnqueueAsync takes your open transaction, so the order row and the job that fulfils it commit together, or neither exists
  12. 12Find a job by its deduplication keyJobLookup.ByDeduplicationKey finds a job by the key it was enqueued with, when you did not keep its ref
  13. 13Choose between starting a job and waiting for itEnqueueAsync returns as soon as the job is stored; CallAsync enqueues, waits, and returns the job's outcome
  14. 14Enqueue many jobs in one round tripEnqueueJobsAsync writes a whole list of jobs in one round trip to the database and answers their outcomes in request order
  15. 15Run urgent jobs firstA priority on the enqueue decides which of the jobs that are due at once a worker claims first
  16. 16Label jobs so you can find themTags are name and value labels set on the enqueue, for filtering and grouping jobs in queries and in the dashboard
  17. 17Pass a large file by referenceKeep a big file in blob storage and enqueue a reference to it, with its checksum and size, instead of the bytes
  18. 18Store a job's payload in a custom formatA job names the format its payload is stored in: JSON by default, or a format of your own. This program adds two custom formats, scalar-v1 and json-gzip, and runs the same echo job through eachLab

Run work on a schedule

Recurring work as one permanent job: by cron, by interval, in a time zone, or from a calendar.

  1. 1Run a job on a repeating schedule[Schedule] with a cron makes one permanent job that fires on that cadence, with nothing to enqueue
  2. 2Run a job every day at a set hour in your time zoneA cron with TimeZoneId fires at the same local hour all year: 0 8 * * * in Europe/Berlin is 08:00 in Berlin, in summer and in winter
  3. 3Replace a timer loop with an interval scheduleAn interval schedule, such as 10s, runs a job at a fixed gap, where a timer loop in a hosted service would otherwise stand
  4. 4Give one job several schedulesSeveral [Schedule] attributes on one job share one permanent job, and schedules that come due together fire it onceLab
  5. 5Decide what happens to runs a schedule missedMissed occurrences are a business decision, and MisfireStrategy on the schedule makes it. Three schedules miss the same stretch while paused: Skip, the default, passes over them and fires only a latest one less than a minute overdue, CatchUpOnce runs one firing that covers them all, and CatchUpAll runs every one in orderLab
  6. 6Pause and resume a scheduleoperations.Schedules pauses a schedule from outside the handler, for good or until an instant, and resumes it
  7. 7Drive a schedule from a published calendarA calendar is data that an operator publishes through operations.Calendars. A schedule binds it by name, and a later publication retimes every schedule bound to it in one transaction while workers run
  8. 8Keep a schedule inside office hoursAn availability calendar is the open time a schedule may fire in: windows by weekday, with a date closed or given other hours. A schedule names it, and an occurrence outside every window is left out, never moved
  9. 9Run a job on the last business day of each monthAn occurrence calendar is the list of instants a schedule fires at, where a cron cannot say them: the last business day of a month, minus the holidays you name. The schedule takes its occurrences from the calendar
  10. 10Skip public holidays on a daily scheduleA cron cannot name the days a country takes off. An occurrence calendar can: local times on the weekdays you list, minus the dates you exclude. The list is data an operator publishes, so next year's holidays need no deploy
  11. 11Make every occurrence its own jobScheduledDelivery = PerOccurrence makes each occurrence a root job of its own, with its own ref, retries, result, and retention. MaxOutstanding bounds how many may be unfinished at once
  12. 12Decide what a failed firing does to its scheduleA firing that spends its retry budget returns the permanent job to Idle. FiringFailurePolicy says what happens to its schedules then: Continue, the default, fires the next occurrence as usual, and Pause pauses them, with the reason, until an operator resumes them
  13. 13Start each firing of a recurring job cleanA permanent job keeps its variables and step results from one firing to the next. ResetStateAsync as the firing's last line clears them, so the next one starts blank

Split work across child jobs

Fan out, join the results, and decide what a failed child means.

  1. 1Start child jobs and wait for themA parent starts child jobs by name, suspends without holding a worker until every child has finished, and reads their resultsLab
  2. 2Call another job and use its resultCallChildAsync starts another job as a child, waits for it without holding a worker, and returns its outcome, whose ValueOrThrow() is the result
  3. 3Fan out over a list and merge the resultsMapAsync starts one child job per item of a list, waits for them all, and hands back each item's result for the parent to merge
  4. 4Fan out to child jobs with Map or WaitChildrenTwo ways to fan out: EnqueueChildAsync with WaitChildrenAsync for a few named children, and MapAsync for one child per item of a list
  5. 5Find the child job that handles one itemA child's name on the reads is its deduplication key, {map}/{key} for a child that a map started. List the parent's children and pick the one that carries the item's key
  6. 6Handle child jobs that failA group of children never throws by itself. A failed child shows in the Failed list of the wait or the map, and ThrowIfAnyFailed is how the parent chooses to fail with it
  7. 7Start a child job in another namespaceA parent starts a child in another worker's namespace and waits across the boundary
  8. 8Enqueue many independent jobs from a handlerA handler takes IJobs and enqueues many independent jobs, each with a stable deduplication key. Nothing links them to the handler's job and nothing waits for them (compare 212's MapAsync)
  9. 9Chain jobs into a pipelineEach stage is a job of its own that enqueues the next one, with a deduplication key so a replayed handoff starts no second pipeline

Decide what happens when work fails

Retries, backoff, timeouts, deadlines, and ending a job on purpose.

  1. 1Limit how many times a job retriesMaxAttempts on the job is its retry budget. When the last attempt fails, the job ends as Failed
  2. 2Set how long a job waits between retriesBackoff on the job sets how the wait between retries grows: 1s..8s x2 exact starts at one second, doubles with each failure, and stops growing at eight
  3. 3Fail a job for good, with no retryFailAsync ends the job as Failed at once, whatever its retry budget. A thrown exception would be retried
  4. 4Cancel a job from inside its handlerCancelAsync in a handler ends the job as Cancelled: terminal, not a failure, so no retry and no alert follow
  5. 5Pause a job from inside its handlerPauseAsync in a handler parks the job as Paused until someone resumes it
  6. 6Cut off an attempt that runs too longExecutionTimeout caps one attempt: when the time is up, the handler's CancellationToken trips and the cut spends an attempt
  7. 7Stop cleanly when a job is cancelledA handler takes a CancellationToken and passes it to everything it awaits, so a cancel, a timeout, or a shutdown that outlasts the host's grace period ends it promptly
  8. 8Drop a job that is past its deadlineA Deadline is the whole job's budget, measured from its creation. Under the default, strict behaviour an overdue job is cancelled before its handler runs
  9. 9Run an overdue job in a reduced modeWith DeadlineBehavior = Advisory an overdue job still runs. The handler reads IsOverdue and chooses a reduced path

Watch and control running work

Read what happened, find jobs, and cancel, pause, resume, or restart them.

  1. 1Inspect a job from the command lineThe app's own binary answers jobs info, events, explain, and the control verbs for any job, read from the same databaseLab
  2. 2See your jobs in the dashboardMapActa serves the dashboard and its JSON API from your own app. Its controls are off until you turn them onLab
  3. 3Show where each job is on your own pageIJobs reads one job for a page of your own: its status, a value the handler keeps for the screen, and a sentence that says why the job is where it is
  4. 4Read why a job did what it didThe append-only event ledger answers why a job did what it did. ListEventsAsync with LineageRoot reads the timeline of a job and of every child it started
  5. 5List and page through jobsoperations.Ledger lists jobs with filters, pages through them by cursor, counts them, and answers the health counters an operator's screen opens with
  6. 6Cancel a running job from outsideCancelAsync on a job's handle cancels it from outside its handler. Any process that holds an IJobs can do it, and a running handler's CancellationToken trips
  7. 7Pause and resume a job from outsideIJobs.PauseAsync and ResumeAsync pause and resume a job from outside its handler. Each answers whether it was applied or rejected, and its reason lands on the job's timeline
  8. 8Restart a failed job and keep its historyRestartAsync runs a finished job again under the same identity. The failure budget is reset, the history is appended to, steps that succeeded are not run again, and the bare lines of the handler areLab
  9. 9Control jobs over HTTPMapActaApi mounts the operator API without the dashboard. Its controls are off until EnableControls is set, answer local requests only by default, and a control request has to confirm itself
  10. 10Require permissions on the HTTP APIRequirePermissions has every route of the HTTP API check the host's policy named for its permission: read, enqueue, control, or admin. A caller with no credential gets 401, and one that lacks the permission gets 403 naming it
  11. 11Put the dashboard behind your sign-inThe dashboard and its API sit behind the host's own sign-in. The host maps its roles to Acta's four permissions; with no session a page goes to the sign-in, and an API call answers 401
  12. 12Record which tenant a job is forTenantName on the enqueue records which tenant a job is for. Its children inherit the tenant, the job list filters by it, and an enqueue for an unknown or a suspended tenant is refusedLab
  13. 13Carry a correlation key from parent to childA CorrelationKey set on the enqueue travels with the job and with every child it starts. It is on the job row, in each handler's log scope, and a filter of the job list
  14. 14Wrap every handler in your own middlewareAn IJobPipelineBehavior wraps every handler call, the way middleware wraps a request
  15. 15Choose how many events a job recordsEventRecording on the job decides which events it writes. Audit, the default, records every event. Failures records the failed and orphaned attempts, the success that recovers from a failure, what an enabled alert profile reads, a caller's controls of the job, and a schedule's pauses and manual triggers

Deploy and scale

Split the API from the worker, add workers, and tune them.

  1. 1Enqueue from a process that runs no workerReference<TManifest>() lets a process enqueue a namespace's jobs by type without running a worker for it. Run<TManifest>() is the process that executes them
  2. 2Run two namespaces in one processEach Run starts a worker for one namespace. Two of them in one process share the process and the database, and never each other's jobs
  3. 3Restart a crashed app on SQLite and get its work backOn SQLite a starting worker releases the work of processes on the same machine that have ended, so a restarted app takes a lost job back at once. Nothing has to be written for it; the crash spends one attempt
  4. 4Recover the work of a killed workerA worker process is killed in the middle of a job, and another worker reclaims the job once its lease has lapsed. The program runs on PostgreSQL or SQL ServerLab
  5. 5Give Acta a JSON context for Native AOTA source-generated JsonSerializerContext given to UseJsonPayloads serializes payloads with no runtime reflection, and JobPayload.Json(value, typeInfo) builds a raw payload the same way. The program runs on the JIT: it shows the registration an AOT publish needs, and the publish itself is proven by the repository's own gate
  6. 6Wake workers across processes with RedisUseRedisWakeup announces each enqueue over Redis, so a worker in another process starts the job within milliseconds instead of at its next poll
  7. 7Set how many jobs a worker runs at onceMaxConcurrentExecutors caps how many jobs one worker runs at once, and SafetyPollInterval bounds how long an idle worker sleeps between looks at the database
See workers share work and recover it in the interactive explainer

Looking for a how-to that is not here? Tell us what you were trying to do, and it becomes the next one.

for coding agents

Your coding agent reads the same how-tos.

An agent does not need this page's design. It needs the smallest working example of the task, the rules that go with it, and a way to tell that it worked.

Every how-to is also Markdown

Add .md to a how-to's address and it answers as plain text: the same steps, code, rules and checks. Switch any page to "an agent" to see it.

One index lists them all

/learn/index.md names every how-to by task, section by section, each with one line on what it teaches.

The output is the answer key

A how-to names the lines its program must print. The release check reads the same lines, so the page and the code cannot drift apart.

Prompt: build from the how-tos
Read https://useacta.net/llms.txt, then https://useacta.net/learn/index.md. Pick the how-tos that match this task and read each one as Markdown: [describe the task]. Build it, run it once, and show me its job ref and its jobs explain output.
Prompt: teach me
Read https://useacta.net/learn/index.md and take me through the short tour, one how-to at a time. After each one that has a check question, ask me the question before you show the answer.

keep going

Explainers you can play with, and the guides behind the how-tos.