Concurrency and consistency

How reads, writes, conflicts and retries behave when several requests, script runs and triggers work on the same data at once, and which mechanism to use for each job. The rules are the same over the REST API, in a script run with POST /v1/scripts/execute, in a script run as an agent tool, and in a trigger execution, except where a section says otherwise. The API details are in the data model reference, which each section links to.

Start here

When two things change the same data at the same moment, a read can be a moment out of date and two writes can each assume they were first. Two people book the last seat of an event at once: each run reads one seat left, and without the right mechanism both bookings go through.

The model in six points:

  • A write commits at once, and everything one script run writes is committed together, or nothing is.
  • Most reads, and every index behind lookups, lists and search, can be a moment behind a write.
  • You can ask for a strongly consistent read of one record by id when you need the latest version.
  • When two runs change the same item, the platform decides when the run commits: the run that loses writes nothing and is run again (a trigger) or answered 409 for you to send again (execute).
  • An update can check the version you read (expectedVersion), so a change made from a stale read is refused instead of overwriting another.
  • Counters, unique values and retries have their own mechanisms (the atomic increment, externalId and unique fields, the Idempotency-Key), so you do not build them from reads.

How to read this page: the first time through, read this section, Why most reads are eventually consistent and one example from the patterns. To look something up, start from the table below or the patterns.

Choose the mechanism

Find your job in the left column; each row points to the section that explains it.

You needUseSection
A read that reflects every write that has completedrecords.get(id, { consistent: true }), or GET /v1/records/{id}?consistent=trueWhat each read guarantees
To change several fields from what you readexpectedVersion set to the version of a consistent read, with a bounded retryVersioned updates
A counter or a capacity that many writers change at oncerecords.increment with a where limit, on its own lean record type (indexMode NONE, the counted field inline: true)Counters and capacity
A value only one item may holdan externalId, or a lookup field declared unique(e) Unique values
Retries and repeated runs that do no harman Idempotency-Key for a client's retry, vectros.retry to ask for a run again, and trigger runs that decide from input.recordConflicts, retries and repeated runs
To find a record by its content right after writing itexpect a delay; to act on a record you just wrote, read it by idSearch just after a write

Never count records with a lookup, a list or search to enforce a rule or to keep a total exact: an index can be behind by the very records that matter.

Why most reads are eventually consistent

Records live in storage whose reads are eventually consistent unless a read asks otherwise: a write is committed at once, and the default read by id, and the indexes that serve lists and lookups, catch up with it a moment later. This is a design choice. Lookups and lists run on indexes built so that a lookup returning a few records takes about the same time however many records the type holds; the price is that an index is updated just after the write commits, so it can briefly lag behind it. The platform uses a strongly consistent read where correctness needs it (such as an update's own read of the item it changes), and offers one on request when you need to see a write that has just completed (a record read by id).

The same choice keeps writes cheap. An index that is always exactly current has to be updated inside the same transaction as every write, so each write would cost more, and wait on other writes more, the larger and busier that index is. Here a write commits the record and its own entries without waiting on the rest of the index, and the indexes catch up afterwards, so what a write costs does not depend on how many records the type holds; reads and writes both keep their cost as a type grows. What a write does cost grows with the number of lookups its type declares, since each declared lookup is maintained on every write.

Design so that a read which has not caught up yet is harmless, using the patterns below.

What each read guarantees

ReadConsistencyWhat it can show just after another write
GET /v1/records/{id}, vectros.records.get(id)Eventually consistent (the default).The previous version of the record, a record that was just deleted, or a 404 for one that was just created.
GET /v1/records/{id}?consistent=true, vectros.records.get(id, { consistent: true })Strongly consistent.Every write that completed before the request. By id only, records only (consistent on any other endpoint is a 400); metered as one ordinary read.
A document, folder or entity by id, and POST /v1/records/batch-getEventually consistent; there is no consistent option.As for a record read by id.
The read an update makes of the item it changes (PATCH, PUT, vectros.<namespace>.update)Strongly consistent.The latest committed item. The update applies to it, and is written only if the item has not changed since that read: see Versioned updates.
Equality lookups (value/values) on a lookup field or on externalIdAn index, eventually consistent.A record missing that was just created, a record that was just deleted, or an older version of a record.
The externalId check a create makesThe index first; when the index finds nothing, a strongly consistent read of which record holds the value (0.51+; an item stored before 0.51.0 is checked by the index alone).A record that was just deleted, found by the index (see (e)).
Range and prefix lookups, and equality lookups on a rangeEnabled field or on a lookup beyond the first 7 equality lookups (allowOverflow)An index chooses the records; each record is then read by id, eventually consistently.A record missing that was just created or just changed to match, or a record that was just deleted. A record whose value, as of that read, no longer matches is left out, and each record carries its own version as of that read.
Lists (GET /v1/records, vectros.records.query)An index, eventually consistent.A record missing that was just created, a record that was just deleted, or an older version of a record.
Search (/v1/search, and the retrieval that grounds answers to questions)A separate search index, updated after the write commits.Content as it was before the write. A record's indexStatus tells you when its new content is searchable; the record.indexed webhook fires when indexing finishes and record.failed when it fails.

Inside one script run the run's own writes are visible to some reads and not others (see the run's own writes). A trigger's input.record is not a read at all (see a trigger's record).

What moves a record's version

version goes up by one for every committed write of the record, including writes the platform makes itself:

  • Indexing. On a record indexed for search (its indexMode, set on the record or taken from its type's default, is not NONE), after a write that changes what is indexed (any change of the record's payload, a counter's included) the platform writes the record again when indexing finishes, to set indexStatus. That write also moves version. A record whose indexMode is NONE is never written this way.
  • Other platform-owned fields, such as a geo field filled from its address.

The indexing write and the write that fills a geo field from its address do not run your trigger rules.

So on an indexed record a version you read can be behind a moment later with no other writer. Keep a value you update with expectedVersion many times a second, such as a counter, on a record whose indexMode is NONE.

Versioned updates and the commit-time conflict

Every update reads the item it changes with a strongly consistent read, applies the fields you send, and is written only if the item has not changed since that read. Over REST the write happens at once, and a write that landed in between is answered 409 VERSION_CONFLICT, with or without expectedVersion; nothing is written. In a script, a trigger or an atomicity: all_or_nothing record batch (0.51+), the item must not change between the update call and the end of the run (or batch), whether by another request, by a delete, or by the platform's own write-backs such as an index status; otherwise the run fails as a conflict when it commits and nothing it staged is written.

expectedVersion adds a check at the call: that the item still has the version you read. Where another write to the same item lands decides what happens in a script:

The other write landsWith expectedVersionWithout expectedVersion
Between your read and your update callThe update is refused at the call with VERSION_CONFLICT, and nothing is staged for it.Not detected. The update applies to the newer item, and what you computed from your read overwrites the other write's value of each field you send.
After your update call, before the run commitsThe run fails when it commits.The run fails when it commits.

So a read-modify-write is protected from your read onward only when you pass the version you read as expectedVersion (pass the version you read before the run's first write to the item: a version taken from an earlier update's response in the same run is refused with a 400, not retried); without it, a write that lands between your read and your update call is still overwritten. Read the version with { consistent: true }, so that a version that is merely behind does not cost a retry.

A run that fails at commit wrote nothing, its other creates, updates and deletes included, and catching the update's error inside the script does not change this. It is a conflict like any other: POST /v1/scripts/execute answers 409 CONCURRENT_MODIFICATION, a trigger rule runs the script again from fresh reads (each run is billed), and an all_or_nothing batch is retried like any other commit-time conflict (see Conflicts, retries and repeated runs). An update never brings back an item deleted after the update read it, for an item that has a stored version (every item written since versions were recorded): the delete fails the run.

Because the platform's own writes count too (see What moves a record's version), a slow script that updates a frequently written or searchable item may be run again for a change it did not cause. Keep the time between such an update and the end of the run short, and keep values that change often on a type whose indexMode is NONE.

Reading right after a write

(a) Another request or run committed a moment ago

A default get can still return the previous version for a short time. If you then update with expectedVersion set to the version you read, the update's own strongly consistent read sees the new version and refuses with VERSION_CONFLICT. Nothing is written. The refusal is correct: what you computed came from a version that is no longer current.

  • Over REST: read the record again with ?consistent=true, re-apply your change, and send the update again with the new version. Retry a bounded number of times, with a short pause between attempts. (?consistent=true is for records; for another item, read it again by id.)
  • In a script: do not catch the conflict, and the run ends as described in Conflicts, retries and repeated runs. To handle it inside the run instead, re-read with { consistent: true } and retry, as in Change several fields from what you read; only a refusal at the call can be handled that way, never a conflict found at commit.
  • To avoid most of these conflicts, read with { consistent: true } (or ?consistent=true) when the value you read decides what you write, or what you answer (an answer such as "already booked" is only as current as the read it came from). A consistent read does not replace expectedVersion: a write that lands between your read and your update is still caught only by the version check.

(b) A run's own writes

Inside one script run, a get returns what the run itself has written: its own created, updated and deleted records (a record the run deleted is a 404). A list, query or lookup never shows a record the run deleted, shows a record it updated with the updated content as long as the updated record still matches, and does not show a record it created, or one it updated so that it now matches. Keep the id that create returns and use it, rather than finding the record again with a lookup.

A record the run created has no version until the run commits, so expectedVersion cannot be used on it in the same run; see Writing from a script.

(c) A write, then a lookup or a list

A lookup or a list made just after a write, by the same client or another, can miss the write. Never take a version from a lookup or a list to send as expectedVersion, and never take an exact count from one: read the record by id (with consistent: true where it matters) for its version, and keep counts on a record (see Counters and capacity).

(d) A trigger's input.record and a read of the same record

input.record holds the rule's declared fields from the write that fired the run, taken from that write's change event when it was committed. It is not read again when the run starts or when it is run again after a failure. Several writes of the same kind to one record (for example two updates) that reach a rule together can run it once: input.record is then the latest of them and input.previous the state before the first, so the pair describes the change across all of them (a record closed, re-opened and closed again in one such run shows no change of status). A firing can also be delivered more than once, so a run that has already committed can run again for the same write.

vectros.records.get(input.recordId) reads the record as it is now, eventually consistently. It can return an older version than input.record (the read has not caught up with the write that fired the run) or a newer one (another write has committed since). There is no fixed limit on how long the older case can last.

So decide from input.record and input.previous: they describe the change the rule fired for. Read the record only when you need its current state, and then read it with { consistent: true }. Do not count runs to count writes.

(e) Unique values, and creating again under the same externalId

An externalId and a value of a lookup field declared unique (on records and documents), and a folder's slug under its parent, each belong to one item. The platform records which item holds each value in the same write as the item itself (0.51+), so two creates or updates racing for one value cannot both commit. A create sent straight after the same create (a retry, a re-apply) returns the existing item (200, created: false) or the same 400 as any duplicate. Two creates sent at the same moment can instead have one answered with a retryable 409; retrying it returns the existing item. A value stays taken until the item holding it is deleted or changes it; an item that disappears without its own delete (an expiry) frees its values shortly after, not at once. Items stored before 0.51.0 hold no such record for their values and are checked as before, by the index alone.

  • In the same script run or all_or_nothing batch, a value cannot change hands. Freeing a value (deleting the item, or updating or re-typing it to another value) and giving it to another item in the same run writes nothing: the run fails with a message that the value "cannot change hands inside one atomic write" (the batch reports batch_refused for every item). That includes deleting a record and creating a new one with its externalId. Free the value in one run or request and reuse it in the next, or update the existing item instead, which keeps its id.
  • In a later request or run: shortly after the delete, the create's first check, through an index, can still find the deleted record and return it as the existing one (created: false, the old id), and nothing is created. (If the caller cannot read the record the check finds, the create is refused with 400 instead.)
  • Size and capacity. A value longer than about 900 bytes once URL-encoded cannot be kept unique, and a create or update that sets one is refused with a 400 naming the field. Each held value is one more row in an atomic write, so fewer items fit in one all_or_nothing batch or script run: see Writing from a script.

Check created and the id the create returns. In a script, a refused call throws an error whose message starts Request failed with status <status>: . When created is false and the record must exist, read it by id with { consistent: true }: a 404 means it was deleted, so try again later (in a script, vectros.retry()). Where a key is reused after a delete on purpose, consider a new externalId for each new record instead (for example, the key plus a sequence number).

// Create a record under an externalId, and make sure it exists after a recent delete.
const seat = vectros.records.create({
  typeName: 'seat_hold',
  externalId: input.params.holdKey,
  payload: { eventId: input.params.eventId },
});
if (!seat.created) {
  try {
    vectros.records.get(seat.id, { consistent: true });
  } catch (e) {
    if (!String(e.message).includes('status 404')) throw e;
    vectros.retry({ reason: 'The previous hold under this key was just deleted.' });
  }
}
({ holdId: seat.id, created: seat.created });

Conflicts, retries and repeated runs

  • A conflict in a script ends the run with nothing written, classified CONCURRENT_MODIFICATION. POST /v1/scripts/execute runs the script once and answers 409 with that errorCode and a message that tells the caller to read again and retry (it can name the affected items, or carry the reason a script gave vectros.retry); your client sends the request again, a bounded number of times. A trigger runs the script again, a few seconds later and then on later deliveries; the full schedule and the other failure categories are in Writing from a script. A script that catches a refused update sees an error whose message contains "errorCode":"VERSION_CONFLICT".
  • vectros.retry({ reason }) ends the run the same way, when the script decides that what it needs is not there yet (as in (e)).
  • Decide from the status and the errorCode, never from the explanatory text, which can change. Over REST that is the HTTP status and the body's errorCode; in a script, a refused call's error message is Request failed with status <status>: followed by the refusal's body, which carries its errorCode where it has one.
  • An Idempotency-Key on POST /v1/scripts/execute (and on POST /v1/records/{id}/increment) makes a client's retry safe: the same key within 24 hours gets the first attempt's answer without running again. A failed attempt is not remembered, so a 409 can be retried under the same key.
  • A run can run again. A trigger firing can be delivered more than once, and a conflict runs the script again. A run's writes are all or nothing, but anything it does outside its writes, such as an outbound HTTP call, is not undone and happens again (see Outbound HTTP). Make a repeated run harmless: decide from input.record and input.previous, and give what a run creates an externalId derived from what it decided on.

Search just after a write

Search reads a separate index, updated after the write commits. Right after a write, a search can miss the record or show its previous content. A record's indexStatus and the record.indexed webhook tell you when its new content is searchable. To act on a record you have just written, read it by id.

Known limits

A record written again before its first search entry exists can get a second search entry. A search can then return the record twice, and the extra entry keeps the content and field values of the write it came from, so it can match a filter, a sort or text the record no longer satisfies, and an answer grounded on search can use that older content. Each entry is indexed and charged separately. A record written again only after its first write has been indexed (its indexStatus is INDEXED) is not expected to be affected.

Patterns

Counters and capacity

Keep a counter on its own lean record type that is not indexed for search (indexMode: NONE), with the counted field declared inline: true so it always stays on the record row (and a trigger rule can project it). A record that is updated often should almost never be a record you search. A counter on a searchable type works, but every write that changes the record, an increment included, indexes it again (for SEMANTIC and HYBRID, its embeddings may be computed again) and is charged for it, and moves its version once more when indexing finishes (see What moves a record's version); that cost is yours to accept.

Keep an exact number on one record, and change it with the atomic increment (0.51+): vectros.records.increment(id, { field, by, where }) in a script, or POST /v1/records/{id}/increment over REST. It is one conditional write: there is no version to match, so two increments do not refuse each other, and where limits the value it produces (lt, lte, gt, gte, or lteField / gteField against another field of the record, such as a capacity); the field's own schema validation.min and max always apply too, and the result must stay between -9007199254740991 and 9007199254740991 (the whole numbers a JSON number holds exactly). Never compute the number by counting records with a lookup, a list or search: an index can be behind by the very records that matter.

The event type of the next example: both numbers are kept on the record row and hold whole numbers, as lteField requires, and the type is not indexed for search.

{
  "typeName": "event",
  "displayName": "Event",
  "allowedSurfaces": ["record"],
  "indexMode": "NONE",
  "fields": [
    { "fieldId": "capacity", "fieldType": "number", "inline": true, "validation": { "multipleOf": 1 } },
    { "fieldId": "seatsTaken", "fieldType": "number", "inline": true, "validation": { "multipleOf": 1 } }
  ]
}
// Book one seat: add one to the count, as long as it stays within the capacity.
vectros.records.increment(input.params.eventId, {
  field: 'seatsTaken',
  by: 1,
  where: { lteField: 'capacity' },
});
const booking = vectros.records.create({
  typeName: 'booking',
  payload: { eventId: input.params.eventId, attendee: input.params.attendee },
});
({ bookingId: booking.id });

The increment and the booking are written together when the run commits, and the limit is checked then. If the event is full, nothing is written, neither the count nor the booking: the run fails with INCREMENT_CONDITION_NOT_MET (POST /v1/scripts/execute answers 409 with that errorCode), and it is not run again, since the count would still be at the capacity. A script that must take another path when the event is full, such as a waiting list, reads the record first and decides; the limit is still the guarantee. Within the run, a get of the event shows the count from before the increment, and the run cannot also create, update or delete the event: such a call is refused with 400 INCREMENT_COMBINED_WRITE.

Several places at once. Make one call with by set to the number of places and a limit that is a number, not another field: increment(id, { field: 'seatsTaken', by: n, where: { lte: capacity } }), with capacity read in the run (with { consistent: true }). The limit applies to the value after the change, so it is the capacity itself, not the capacity minus n. To cancel, use by: -n with where: { gte: 0 }. lteField admits only by: 1 (and gteField only by: -1), and a field limited by another field can be incremented once per run: a second such increment of it, or a write of the limiting field, in the same run fails the run when it commits, with 400 SCRIPT_ERROR and nothing written. Increments limited by a number can be repeated in one run; each is checked as if they were applied one after another, so if together they pass the limit, the whole run fails with INCREMENT_CONDITION_NOT_MET.

An increment changes the field and nothing derived from it, so it is refused with 400 INCREMENT_FIELD_NOT_ELIGIBLE for, among others, a field that is sensitive, searchable or filterable, a lookup field or the field a lookup is ordered by, the address source of a geo field, or listed in the type's public view; the same code covers a field that is not a declared number field, a by that is not a multiple of the field's multipleOf or step, and a record with no payload yet. That is one more reason to keep a counter on its own type: a number that must be shown publicly cannot be the counter itself, so keep the counter off the public view and copy its value to the public field with an ordinary update when it changes. On a large record only a field declared inline: true can be incremented (any other field is refused with 400 INCREMENT_PAYLOAD_EXTERNALIZED), and lteField needs both fields to hold whole numbers (validation.multipleOf: 1). Under heavy contention an increment can still be answered 409 (in a script, CONCURRENT_MODIFICATION): retry it, over REST with an Idempotency-Key so that a retry does not add twice. The limits, the refusals and the key are in Atomic increment.

Use a version-checked update instead when one write must change several fields from what you read, as in Change several fields from what you read.

Sign up once per email

// Sign up once per email: the externalId is the normalized address, so a second sign-up finds the first.
const email = String(input.params.email).trim().toLowerCase();
const member = vectros.records.create({
  typeName: 'member',
  externalId: email,
  payload: { email, name: input.params.name },
});
({ memberId: member.id, alreadySignedUp: !member.created });

The externalId is held by one record, so two sign-ups with the same address, even at the same moment, cannot both create one (see (e)). A later sign-up returns the first member (created: false). A sign-up that runs at the same moment as the first can instead fail when its run commits, with 409 CONCURRENT_MODIFICATION, since the create is only staged until then; sending it again returns the first member. Normalize the value before using it as the key, or two spellings of one address become two members.

Rules that span several records: keep them on one versioned row

A rule such as "a team keeps at least one admin" or "an account has at most one primary contact" cannot be checked by counting member records through a lookup, for the same reason. Keep the state the rule is about on one record, and change it only with a version-checked update of that record.

// Remove an admin, but never the last one: the rule is checked on the team record itself.
const team = vectros.records.get(input.params.teamId, { consistent: true });
const admins = team.payload.admins.filter((a) => a !== input.params.userId);
if (admins.length === 0) {
  throw new Error('A team keeps at least one admin.');
}
vectros.records.update(team.id, { payload: { admins }, expectedVersion: team.version });
({ admins });

Two runs removing the two last admins at the same time cannot both succeed: the second one is refused (its update with VERSION_CONFLICT, or its commit), and when it runs again (a trigger runs it again; a 409 from POST /v1/scripts/execute is your client's to resend) it finds one admin left and refuses.

Change several fields from what you read

When one write must change several fields from what you read, use a version-checked update. To handle a refusal at the call inside the run, so that POST /v1/scripts/execute answers 200 instead of 409, re-read with { consistent: true } and try again a bounded number of times:

// Move the first person on the waiting list into a free seat, re-reading and retrying up to three times.
function promote(id) {
  for (let attempt = 1; ; attempt++) {
    const s = vectros.records.get(id, { consistent: true });
    if (s.payload.waiting.length === 0 || s.payload.attendees.length >= s.payload.capacity) return s;
    try {
      return vectros.records.update(id, {
        payload: {
          attendees: s.payload.attendees.concat(s.payload.waiting[0]),
          waiting: s.payload.waiting.slice(1),
        },
        expectedVersion: s.version,
      });
    } catch (e) {
      if (attempt === 3 || !String(e.message).includes('"errorCode":"VERSION_CONFLICT"')) throw e;
    }
  }
}
promote(input.params.sessionId).payload.attendees;

A refused update stages nothing, so the run can continue after catching it. A write that lands after the update call still fails the run when it commits, as in Versioned updates; that conflict cannot be caught.

Recounts and repair jobs

A job that recounts from an index (a lookup or a list) can undercount records written moments earlier. It must never write its count over an exact total. Report the difference instead, and let a person or a later, quieter pass decide.

// Recount bookings for an event and report any difference; never write the count back.
const event = vectros.records.get(input.params.eventId, { consistent: true });
let counted = 0;
let cursor;
do {
  const page = vectros.records.lookup({ type: 'booking', field: 'eventId', value: event.id, startFrom: cursor });
  counted += page.data.length;
  cursor = page.nextCursor;
} while (cursor);
({ recorded: event.payload.seatsTaken, counted, differs: counted !== event.payload.seatsTaken });

Page until nextCursor is absent: a page can be shorter than limit, or empty, with more behind it.

Triggers: decide from input.record

// On UPDATE: act on the change this run was fired for, not on a fresh read of the record.
if (input.record.status === 'closed' && input.previous.status !== 'closed') {
  vectros.records.create({
    typeName: 'case_note',
    payload: { caseId: input.recordId, note: 'Case closed.' },
  });
}

The rule declares fields: ["status"], and status is kept inline on the schema (see Trigger execution). The run makes the same decision whatever has happened to the record since the write. Because a firing can be delivered more than once, this run can write its note twice; give the note an externalId derived from what the run decided on if once must mean once.

Where to go next