Autorun AI Docs

7. Sequences

Sequences hand out numbers that are guaranteed unique even when several processes run at the same time. Use them for invoice numbers, order references, ticket codes — anything that needs a gapless, human-readable counter.

They live on context.sequences, not on context.functions.

const number = await context.sequences.getNext("invoices-2026");
Why not count the records?

Reading totalCount and adding one looks equivalent but breaks the moment two records are created in the same instant — both read the same count and both produce the same number. Sequences are allocated atomically by the database, so every caller gets a distinct value.


getNext(name)

async · returns number

Returns the next value and advances the counter. If the sequence does not exist yet it is created on the spot and starts at 1.

Prop

Type

/** @event beforeCreate @entity invoices */
const seq = await context.sequences.getNext("invoices-" + new Date().getFullYear());
context.record.InvoiceNumber = "INV-2026-" + String(seq).padStart(5, "0");
// → "INV-2026-00042"
A consumed number is gone

getNext advances the counter immediately. If the process later throws, or the record is rejected, the number is not returned to the pool and you get a gap. Where gaps are unacceptable, allocate the number as late as possible.


getCurrent(name)

async · returns number

Reads the last value handed out, without advancing. Returns 0 when the sequence does not exist or has never been used.

const last = await context.sequences.getCurrent("invoices-2026");
log("Last invoice number issued: " + last);

Do not use this to work out the next number — between your read and your write another process may have taken it. Use getNext for that.


exists(name)

async · returns boolean

if (!(await context.sequences.exists("invoices-2026"))) {
  log("First invoice of the year");
}

reset(name, value)

async · returns true

Sets the counter so the next getNext returns value.

Prop

Type

/** @event scheduled @schedule 0 0 1 1 * */
await context.sequences.reset("invoices-" + new Date().getFullYear(), 1);

Resetting a live sequence backwards will reissue numbers that already exist on records. Reset only when starting a fresh series, such as a new financial year.


Naming

Sequence names are scoped to your application, so they only need to be unique within it. Encode the reset period in the name rather than resetting an existing sequence:

const year = new Date().getFullYear();
const seq = await context.sequences.getNext("orders-" + year);

This gives you orders-2026, orders-2027, and so on — each starting at 1 with no scheduled reset and no chance of reissuing an old number.