Skip to content

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.

The two features are easy to confuse because they share a name, but they are unrelated in the code and serve different purposes:

Counter widgetAuto-increment sequence
PurposeShow a live summary number (how many entries match)Assign a unique running number to each new entry
Built onA view, optionally filtered by a saved queryThe Counters / CounterSequence data model
Where it livesThe interface (top bar, dashboards, pages)A data-entity field’s autoIncrementOptions
Changes over timeRecomputed as data changesAllocated 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.

The auto-increment feature is built on two pieces:

  • An auto-increment field option on a data-entity field (options.autoIncrementOptions, model FieldOptionsAutoIncrement), 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:

  1. A data-entity field carries options.autoIncrementOptions. When enabled is true, the field is an auto-increment field.
  2. When the entity is created or updated, DataEntityService reconciles a backing Counters document 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.
  3. When a data entry is created, DataEntryWriterService.handleAutoIncrementFields finds every enabled auto-increment field and allocates the next value for each (in parallel), writing it into entry.value.<fullNormalizedName>.
  4. Allocation goes through SequenceService.getNextValue, which resolves the counter, evaluates any conditional keys, then atomically bumps the matching CounterSequence via CounterSequenceRepository.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.)

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.

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.

FieldTypeDefaultNotes
idstring—Primary key; not generated. This is the counter key.
lastValuenumber—Deprecated. The live value now lives on CounterSequence, not here.
startAtnumber1First value handed out when a sequence has not been used yet.
incrementBynumber1Amount added on each subsequent allocation.
sharingLevelnumber (AutoIncrementSharingLevelEnum)0 (None)See Sharing levels.
referencedByCountersReferencedBy[]—Entity fields that point at this counter (config link).
usedByCountersUsedBy[]—Entity fields that have actually consumed a value. Gates config changes.
conditionalIncrementbooleanfalseWhen true, the counter runs multiple independent streams keyed by keys.
keysCountersKey[][]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.

FieldTypeNotes
idstringRandom UUID (v4), generated on first upsert.
counterIdstringThe owning counter’s id.
lastValuenumberThe 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.

Defines one key that segments a conditional counter into independent streams.

FieldTypeNotes
keyNamestringUnique; validated against NormalizedNameValidation (min/max length + normalized-name pattern). Becomes a property name on CounterSequence.
calculationMethodnumber (TokenSourceType)How value is interpreted. Schema default Expression. Only Expression is accepted.
valuestringThe 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.

Lives on a data-entity field at options.autoIncrementOptions.

FieldTypeDefaultNotes
enabledboolean— (required)Marks the field as auto-increment. FieldService.isAutoIncrementField returns !!options.autoIncrementOptions?.enabled.
keystring— (required)The counter key (== Counters.id) to draw from.
sharingLevelnumber0Copied to the counter, then removed from the field options at save time.
startAtnumber1Copied to the counter, then removed from the field options.
incrementBynumber1Copied to the counter, then removed from the field options.
conditionalIncrementbooleanfalseCopied to the counter and kept on the field.
keysCountersKey[][]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.

AutoIncrementSharingLevelEnum:

ValueNameMeaning
0NoneNot shared.
1ModuleShared at module level.
2SystemShared 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.

SequenceService.getNextValue(field, dataEntry):

  1. Reads key = field.options.autoIncrementOptions?.key. If absent, logs an error and returns undefined.
  2. Loads the counter with countersRepository.findById(key). If not found, logs and returns undefined.
  3. Calls evaluateConditionalKeys(counter.keys, dataEntry) — for each key whose calculationMethod === Expression, it replaces key.value with the result of ExpressionService.evaluateExpression(key.value, null, dataEntry). This turns the stored expression into the concrete value for this entry.
  4. Calls counterSequenceRepository.getNextValue(counter) to atomically obtain the next number.
  5. Records usage: an $addToSet on the counter adds { entityField: '<dataEntry.dataEntity>_<field.normalizedName>' } to usedBy, so the counter is now marked as consumed by this field.
  6. Returns the numeric value.

CounterSequenceRepository.getNextValue(counter) performs the atomic bump:

  • If counter.conditionalIncrement and counter.keys are present, it builds a keys object mapping each keyName -> key.value (the already-evaluated value). Otherwise keys is empty.
  • It runs a MongoDB findOneAndUpdate on _counters_sequence with:
    • filter: { counterId: counter.id, ...keys } — matches the stream for this counter and this exact key combination.
    • update (aggregation-pipeline $set):
      • _id: existing _id or a new UUID v4 (upsert case).
      • counterId: existing or counter.id.
      • the keys fields.
      • lastValue: if the current lastValue is null → counter.startAt; otherwise lastValue + counter.incrementBy.
    • options: { upsert: true, returnDocument: 'after' }.
  • 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.

Counter requestNumber with startAt = 100, incrementBy = 5, non-conditional:

Create #_counters_sequence.lastValueValue written to entry
1st(none) → 100100
2nd100 + 5 → 105105
3rd105 + 5 → 110110

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.

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.calculationMethod must be Expression; otherwise UnsupportedConditionalIncrementCalculationMethod is thrown.
  • If the counter has already been used (usedBy non-empty), you cannot change conditionalIncrement or change the keys set — 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.

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 Counters with id = key, the incrementBy/startAt/sharingLevel (defaulting 1/1/0), conditionalIncrement, keys, and a single referencedBy entry for this field. (Creation is wrapped in a try/catch that swallows errors; per the in-code TODO, 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.
  • Existing counter, same key → if the counter has not been used yet, update its sharingLevel/startAt/incrementBy (only when provided), conditionalIncrement, and keys, and clear usedBy. 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.

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.

Lists auto-increment counters. Defined in CountersController.find.

  • Auth: requires authentication via the Auth2 strategy (@authenticate), and authorization through entityVoterFactory() (@authorize).
  • Query: accepts a standard LoopBack filter for Counters (@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>
  • Two collections, split responsibility. _counters holds configuration; _counters_sequence holds the live running value(s). Counters.lastValue is deprecated — do not read or write it as the source of truth.
  • Atomicity is at the sequence level. The findOneAndUpdate upsert on _counters_sequence scoped by counterId + evaluated key values is the concurrency guarantee. Any change here must preserve that single-round-trip atomic increment.
  • Keys are evaluated per entry. evaluateConditionalKeys mutates the in-memory counter.keys[].value to 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 the referencedBy.length === 1 “junk” check drive whether config edits are allowed and whether an orphaned counter is deleted. The usedBy string format is <entityId>_<field.normalizedName>.
  • Value is written by full normalized name. incrementField does set(dataEntry, 'value.<field.fullNormalizedName>', nextValue). There is an in-code TODO noting 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