Auto-increment sequences and counter widgets: internals and API
Section titled “Auto-increment sequences and counter widgets: internals and API”This page is for integrators and platform engineers who need to know exactly how sequence numbers are allocated and stored, what the server enforces when an entity with a sequence field is saved, and what the counters endpoint returns.
Counter widgets vs. sequences
Section titled “Counter widgets vs. sequences”The two features are easy to confuse because they share a name, but they are unrelated in the code and serve different purposes:
| Counter widget | Auto-increment sequence | |
|---|---|---|
| Purpose | Show a live summary number (how many entries match) | Assign a unique running number to each new entry |
| Built on | A view, optionally filtered by a saved query | The Counters / CounterSequence data model |
| Where it lives | The interface (top bar, dashboards, pages) | A data-entity field’s autoIncrementOptions |
| Changes over time | Recomputed as data changes | Allocated once, on entry create |
A counter widget counts the entries in a bound data view, optionally narrowed
by a saved query (a DataQuery) — its counting criteria is a query reference,
not the dashboard’s separate, aggregation-capable StatisticQuery model used by
Number/summary cards.
Since 1.4 the end-user list of counter widgets reads the candidate widgets first
and checks only their views, instead of loading every view up front, so it no longer
slows down as a tenant accumulates views (also delivered to the 1.4, 1.6 and 1.8
lines as an update). See
Dashboards, Summaries & Counter Widgets
for the listing rules.
How auto-increment sequences work
Section titled “How auto-increment sequences work”The auto-increment feature is built on two pieces:
- An auto-increment field option on a data-entity field
(
options.autoIncrementOptions, modelFieldOptionsAutoIncrement), which declares that the field is fed by a counter and names the counter to use. - A counter (
Counters) plus one or more counter sequences (CounterSequence) stored in the data-service database, which hold the configuration and the current running value(s).
The number produced is a plain integer. There is no prefix/suffix/padding mask stored on the counter itself — formatting (zero-padding, prefixes) is not part of the counter model.
End to end:
- A data-entity field carries
options.autoIncrementOptions. Whenenabledistrue, the field is an auto-increment field. - When the entity is created or updated,
DataEntityServicereconciles a backingCountersdocument for each enabled field (creating, migrating, or updating it — see Counter lifecycle). The per-counter settings (startAt,incrementBy,sharingLevel) are copied onto the counter and stripped from the field options. - When a data entry is created,
DataEntryWriterService.handleAutoIncrementFieldsfinds every enabled auto-increment field and allocates the next value for each (in parallel), writing it intoentry.value.<fullNormalizedName>. - Allocation goes through
SequenceService.getNextValue, which resolves the counter, evaluates any conditional keys, then atomically bumps the matchingCounterSequenceviaCounterSequenceRepository.getNextValue.
Auto-increment values are allocated on create only — there is no
re-allocation on update or patch. (handleAutoIncrementFields is called from
the create path and from batch create; it is not called from updateDataEntry
or patchDataEntry.)
Failure behaviour
Section titled “Failure behaviour”handleAutoIncrementFields wraps its work in a try/catch that logs and
swallows any error. If counter allocation fails, the entry is still created —
the field is simply left without a generated number. Do not rely on entry
creation failing when a counter is misconfigured.
Inside the repository, if the atomic update throws, it is rethrown as a
GeneratingCounterSequenceException (GENERATING_COUNTER_SEQUENCE_ERROR), but
that still surfaces to the swallowing catch above.
Sequence data model
Section titled “Sequence data model”Counters (collection _counters)
Section titled “Counters (collection _counters)”One document per counter. The document id is the counter key — the same
string referenced by a field’s autoIncrementOptions.key. Stored in MongoDB
collection _counters.
| Field | Type | Default | Notes |
|---|---|---|---|
id | string | — | Primary key; not generated. This is the counter key. |
lastValue | number | — | Deprecated. The live value now lives on CounterSequence, not here. |
startAt | number | 1 | First value handed out when a sequence has not been used yet. |
incrementBy | number | 1 | Amount added on each subsequent allocation. |
sharingLevel | number (AutoIncrementSharingLevelEnum) | 0 (None) | See Sharing levels. |
referencedBy | CountersReferencedBy[] | — | Entity fields that point at this counter (config link). |
usedBy | CountersUsedBy[] | — | Entity fields that have actually consumed a value. Gates config changes. |
conditionalIncrement | boolean | false | When true, the counter runs multiple independent streams keyed by keys. |
keys | CountersKey[] | [] | Key definitions used to pick/segment the sequence stream. |
CountersReferencedBy (sub-model): module, entity, field — all UUIDs
identifying the field that references this counter.
CountersUsedBy (sub-model): a single string entityField, set the first
time the counter is actually used to produce a value for a field. Its format is
<entityId>_<field.normalizedName> (e.g. xyz-uuid_requestNumber). Once set it
is not changed. Presence of usedBy entries is what locks certain configuration
changes (see lifecycle rules).
CounterSequence (collection _counters_sequence)
Section titled “CounterSequence (collection _counters_sequence)”Holds the actual running value(s) for a counter. There can be many sequence
documents per counter when conditionalIncrement is on — one per distinct
combination of key values. Stored in MongoDB collection _counters_sequence.
| Field | Type | Notes |
|---|---|---|
id | string | Random UUID (v4), generated on first upsert. |
counterId | string | The owning counter’s id. |
lastValue | number | The most recently issued value for this stream. |
[key: string]: any | — | Dynamic key columns. When conditional, one property per CountersKey.keyName, holding that key’s evaluated value, used to match the correct stream. |
CountersKey
Section titled “CountersKey”Defines one key that segments a conditional counter into independent streams.
| Field | Type | Notes |
|---|---|---|
keyName | string | Unique; validated against NormalizedNameValidation (min/max length + normalized-name pattern). Becomes a property name on CounterSequence. |
calculationMethod | number (TokenSourceType) | How value is interpreted. Schema default Expression. Only Expression is accepted. |
value | string | The expression to evaluate (for the Expression method). |
TokenSourceType values: Fixed = 0, Field = 1, Expression = 2,
Pointer = 3. Counter keys must all be Expression. Any key with a
non-Expression calculationMethod causes
UnsupportedConditionalIncrementCalculationMethod
(UNSUPPORTED_CONDITIONAL_INCREMENT_CALCULATION_METHOD) to be thrown when the
entity is saved.
FieldOptionsAutoIncrement (field option)
Section titled “FieldOptionsAutoIncrement (field option)”Lives on a data-entity field at options.autoIncrementOptions.
| Field | Type | Default | Notes |
|---|---|---|---|
enabled | boolean | — (required) | Marks the field as auto-increment. FieldService.isAutoIncrementField returns !!options.autoIncrementOptions?.enabled. |
key | string | — (required) | The counter key (== Counters.id) to draw from. |
sharingLevel | number | 0 | Copied to the counter, then removed from the field options at save time. |
startAt | number | 1 | Copied to the counter, then removed from the field options. |
incrementBy | number | 1 | Copied to the counter, then removed from the field options. |
conditionalIncrement | boolean | false | Copied to the counter and kept on the field. |
keys | CountersKey[] | [] | Copied to the counter and kept on the field. |
After the entity is saved, the field’s autoIncrementOptions is rebuilt to keep
only enabled, key, conditionalIncrement, and keys — the numeric
tuning (sharingLevel, startAt, incrementBy) is authoritative on the
counter, not the field.
Sharing levels
Section titled “Sharing levels”AutoIncrementSharingLevelEnum:
| Value | Name | Meaning |
|---|---|---|
0 | None | Not shared. |
1 | Module | Shared at module level. |
2 | System | Shared at system level. |
sharingLevel is persisted on the counter and defaults to None. Note: the
code that would share one counter across multiple fields is not fully
implemented — counter creation is keyed strictly by key, and an in-code TODO
notes that creating a counter whose key already exists currently throws and that
sharing “should be handled later”. Treat cross-field sharing as
partial/unfinished.
Allocating the next value
Section titled “Allocating the next value”SequenceService.getNextValue(field, dataEntry):
- Reads
key = field.options.autoIncrementOptions?.key. If absent, logs an error and returnsundefined. - Loads the counter with
countersRepository.findById(key). If not found, logs and returnsundefined. - Calls
evaluateConditionalKeys(counter.keys, dataEntry)— for each key whosecalculationMethod === Expression, it replaceskey.valuewith the result ofExpressionService.evaluateExpression(key.value, null, dataEntry). This turns the stored expression into the concrete value for this entry. - Calls
counterSequenceRepository.getNextValue(counter)to atomically obtain the next number. - Records usage: an
$addToSeton the counter adds{ entityField: '<dataEntry.dataEntity>_<field.normalizedName>' }tousedBy, so the counter is now marked as consumed by this field. - Returns the numeric value.
CounterSequenceRepository.getNextValue(counter) performs the atomic bump:
- If
counter.conditionalIncrementandcounter.keysare present, it builds akeysobject mapping eachkeyName -> key.value(the already-evaluated value). Otherwisekeysis empty. - It runs a MongoDB
findOneAndUpdateon_counters_sequencewith:- filter:
{ counterId: counter.id, ...keys }— matches the stream for this counter and this exact key combination. - update (aggregation-pipeline
$set):_id: existing_idor a new UUID v4 (upsert case).counterId: existing orcounter.id.- the
keysfields. lastValue: if the currentlastValueis null →counter.startAt; otherwiselastValue + counter.incrementBy.
- options:
{ upsert: true, returnDocument: 'after' }.
- filter:
- Returns
result.value.lastValue.
Because the read-modify-write is a single atomic findOneAndUpdate scoped to
(counterId + key values), concurrent entry creation cannot hand out the same
number twice for the same stream. The first allocation for a stream yields
exactly startAt; each subsequent one adds incrementBy.
On any error the repository logs it and throws
GeneratingCounterSequenceException.
Worked example
Section titled “Worked example”Counter requestNumber with startAt = 100, incrementBy = 5,
non-conditional:
| Create # | _counters_sequence.lastValue | Value written to entry |
|---|---|---|
| 1st | (none) → 100 | 100 |
| 2nd | 100 + 5 → 105 | 105 |
| 3rd | 105 + 5 → 110 | 110 |
With conditionalIncrement and a key year (expression evaluating to the
entry’s year), each distinct year gets its own sequence document and its own
independent run starting at startAt.
Conditional (multi-stream) sequencing
Section titled “Conditional (multi-stream) sequencing”Turning on conditionalIncrement with one or more keys makes a single counter
maintain independent numbering streams. Each stream is identified by the
combination of evaluated key values, and each has its own CounterSequence
document. Common use: reset/segment numbering per year, per department, per
branch, etc., where the key expression derives the segment from the entry being
created.
Rules enforced at entity save time (validateConditionalIncrement):
- Every
CountersKey.calculationMethodmust beExpression; otherwiseUnsupportedConditionalIncrementCalculationMethodis thrown. - If the counter has already been used (
usedBynon-empty), you cannot changeconditionalIncrementor change thekeysset —CanNotChangeConditionalIncrementConfigurations(CAN_NOT_CHANGE_CONDITIONAL_INCREMENT_CONFIGURATIONS) is thrown. Conditional configuration is effectively frozen once numbers have been issued.
Interaction with uniqueness: a normal auto-increment field is forced
options.unique = true. When conditionalIncrement is on (on the incoming
options or on the existing counter), the field is set options.unique = false —
because the same number can legitimately recur across different streams.
Counter lifecycle at entity save-time
Section titled “Counter lifecycle at entity save-time”DataEntityService.handleAutoIncrementField(field, dataEntity) runs for every
field with autoIncrementOptions.enabled when an entity is created or updated.
It looks up the existing counter by referencedBy.field === field.id and then:
- No existing counter → create a new
Counterswithid = key, theincrementBy/startAt/sharingLevel(defaulting1/1/0),conditionalIncrement,keys, and a singlereferencedByentry for this field. (Creation is wrapped in atry/catchthat swallows errors; per the in-codeTODO, a duplicate key currently throws and sharing is not yet handled.) - Existing counter, key changed →
- If this entity-field has not consumed the old counter, create a fresh
counter for the new key, and if the old counter was referenced only by this
field (
referencedBy.length === 1, “junk”), delete it. - If this entity-field has consumed the old counter, throw
FailToAddFieldException(“can not update auto increment key after it is used”). The counter key is immutable once used.
- If this entity-field has not consumed the old counter, create a fresh
counter for the new key, and if the old counter was referenced only by this
field (
- Existing counter, same key → if the counter has not been used yet,
update its
sharingLevel/startAt/incrementBy(only when provided),conditionalIncrement, andkeys, and clearusedBy. If it has already been used, tuning is left as-is (the block is skipped).
In short: startAt, incrementBy, and sharingLevel are freely editable until
the first value is issued; after that the counter’s numbering is effectively
locked, and the key can never change.
Sequences API
Section titled “Sequences API”There is exactly one HTTP endpoint for counters, and it is read-only. Counters are created and mutated as a side effect of saving data entities, not through a dedicated write API.
GET /v1/auto-increment-counters
Section titled “GET /v1/auto-increment-counters”Lists auto-increment counters. Defined in CountersController.find.
- Auth: requires authentication via the
Auth2strategy (@authenticate), and authorization throughentityVoterFactory()(@authorize). - Query: accepts a standard LoopBack
filterforCounters(@param.filter(Counters)), so you can filter/limit/select/order over the counter fields documented above. - Returns:
Counters[](the raw counter documents).
There is no create/update/delete counter endpoint in this controller, and
no endpoint that exposes _counters_sequence values directly.
GET /v1/auto-increment-counters?filter={"where":{"conditionalIncrement":true}}Authorization: Bearer <token>Notes for engineers
Section titled “Notes for engineers”- Two collections, split responsibility.
_countersholds configuration;_counters_sequenceholds the live running value(s).Counters.lastValueis deprecated — do not read or write it as the source of truth. - Atomicity is at the sequence level. The
findOneAndUpdateupsert on_counters_sequencescoped bycounterId+ evaluated key values is the concurrency guarantee. Any change here must preserve that single-round-trip atomic increment. - Keys are evaluated per entry.
evaluateConditionalKeysmutates the in-memorycounter.keys[].valueto the evaluated result before building the stream filter; the persisted counter keeps the expression, while the sequence document stores the evaluated value. - Usage tracking gates edits.
usedBy(on the counter) and thereferencedBy.length === 1“junk” check drive whether config edits are allowed and whether an orphaned counter is deleted. TheusedBystring format is<entityId>_<field.normalizedName>. - Value is written by full normalized name.
incrementFielddoesset(dataEntry, 'value.<field.fullNormalizedName>', nextValue). There is an in-codeTODOnoting the value is not coerced to string for string-typed fields.
Platform 1.10.0 · Backend 1.11.0-alpha.11 · Frontend 1.11.0-alpha.6 · Mobile 1.10.2 · Chart 1.11.8 · Gateway 2.6.11 · MCP 0.2.0 · Grafana DS 1.2.0Docs build 2026-11-27