Limits and reservations with Accumulators
An Accumulator is an authoritative balance of an entity that many checkouts change at the same time: the stock on hand of a stock position, the money on a gift card, or the uses of a discount code. Vox checks whether a change is allowed and applies it in one atomic step, so two concurrent checkouts can never both take the last unit, and keeps holds: amounts taken provisionally, eg two pairs of shoes held for fifteen minutes while a payment completes, that are later committed, released or expire by themselves.
For the team view, see Limits that hold under load.
When to use one
Use an Accumulator for a number that's changed concurrently by operations that must not pass a limit, eg checkouts, payments or stock receipts. Use an ordinary owned field for a number that editors set and review, eg a list price or a planned quantity: balances have no drafts, releases, history or contracts, so they can't be edited in a draft, reviewed before publishing or restored.
| Owned field | Accumulator | |
|---|---|---|
| Changed by | Editors and integrations, through actions | Application code, through IVoxAccumulators |
| Concurrent changes | Optimistic version check: the second save conflicts | Bounded atomic change: both apply while within bounds |
| Drafts, releases, history | Yes | No: every scope reads the same live value |
| Changes the entity's version | Yes | No |
| Read with the entity | Yes | No: read by key, eg one customer's uses |
Declare an Accumulator
Declare an Accumulator as a static field of the entity class. It isn't a property, so it's never in the entity's JSON, change detection, history or contracts:
public class DiscountCode : IVoxAuthoredEntity
{
// Counts committed uses up from zero. The limit is the code's own TotalUseLimit, passed with each claim.
public static readonly VoxAccumulator<DiscountCode> Uses =
VoxAccumulator.Define<DiscountCode>("uses", minimum: 0);
// One balance per customer key, created by the customer's first claim.
public static readonly VoxKeyedAccumulator<DiscountCode> UsesPerCustomer =
VoxAccumulator.DefineKeyed<DiscountCode>("usesPerCustomer", minimum: 0);
public required virtual string Id { get; set; }
public virtual int? TotalUseLimit { get; set; }
public virtual int? UseLimitPerCustomer { get; set; }
}
public class StockPosition : IVoxEntity
{
// Tracked, so an availability calculation can read it and be refreshed.
public static readonly VoxAccumulator<StockPosition> OnHand =
VoxAccumulator.Define<StockPosition>("onHand", minimum: 0, tracked: true);
public required virtual string Id { get; set; }
}
The name identifies the stored balances, so renaming it leaves them behind; declaring the old name again brings them
back. Names are unique within the entity type. A display name for the admin can be passed with displayName.
Accumulators are stored by Entity Framework storage. An entity type with one stored by a provider that can't store them, eg Redis, fails at startup with an error that names the Accumulator and the storage.
Balances and bounds
A balance is a value with two held amounts next to it:
- Value: what has actually happened, eg 6 pairs on hand.
- Held out: the sum of open holds that lower it, eg 2 pairs held for checkouts.
- Held in: the sum of open holds that raise it, eg 3 uses claimed by checkouts that haven't finished.
A change is checked pessimistically: lowering by 1 needs Value - HeldOut - 1 >= minimum, and raising by 1 needs
Value + HeldIn + 1 <= maximum. With 6 on hand and 2 held, at most 4 more can be held. With a use limit of 40, 37
committed uses and 3 claimed, the next claim is refused.
A bound can be declared on the Accumulator, eg a minimum of 0 for stock, and passed with each change, eg the code's current use limit; the tighter one applies. Use limits count up from zero towards a limit the application reads from the entity, so raising a code's limit from 1,000 to 2,000 applies at once to every balance. Vox doesn't read the limit itself: a change that doesn't pass it gets only the declared bounds.
Bounds limit changes, not reality: a stock count can set the value below what's held, see set. A balance that has never been changed reads as zero with nothing held, and has no stored row.
Every balance is a decimal stored with four decimal places, which fits both money and whole counts. An amount, a value
or a bound with more decimals is refused with an ArgumentException.
Read a balance
Resolve IVoxAccumulators from dependency injection:
VoxBalance balance = await accumulators.GetAsync(StockPosition.OnHand, positionId, cancellationToken);
// balance.Value 6, balance.HeldOut 2, so 4 can still be held: balance.AvailableAbove(0)
IReadOnlyList<VoxBalance> customer = await accumulators.GetManyAsync(
DiscountCode.UsesPerCustomer, code.Id, [customerKey], cancellationToken);
// Support tooling: a page of a code's customers in key order, never more than the page
VoxBalancePage page = await accumulators.ListKeysAsync(DiscountCode.UsesPerCustomer, code.Id, afterKey: null, take: 50, cancellationToken);
Balances are read from the authoritative storage every time; they aren't cached.
Keyed balances
A keyed Accumulator holds one balance per key, eg per customer or per warehouse. A code used by 200,000 customers has 200,000 small balances, and a customer who never uses it costs nothing: a key's row is created by its first change. Each key is read and written by its key only, and reading the entity reads none of its balances.
Keys are compared the way the database compares text, like entity ids: with SQL Server's default collation,
customer-4711 and Customer-4711 are the same balance, while PostgreSQL and SQLite tell them apart. Use keys in one
form, eg the customer's id rather than an email address as typed.
Holds and operations
A hold has an id the caller chooses, eg order:1234, one or more lines and an optional expiry. Each line is a change of
a balance, made with Change on the Accumulator. All balances of a hold are stored by the same provider. Lines of the same
balance are merged; a hold can't both raise and lower one balance.
| Operation | What it does |
|---|---|
ReserveAsync(hold) | Adds every line to the held amounts within its bounds, or refuses and changes nothing. |
CommitAsync(id) | Moves everything held to the value and finishes the hold. |
CommitAsync(id, lines) | Commits part of each line, eg one pair of two or 250 kr of 300 kr, gives back the rest and finishes the hold. A balance of the hold without a line is given back. |
ReleaseAsync(id) | Gives back everything the hold holds and finishes it. |
ExtendAsync(id, expiresAtUtc) | Moves the expiry of an open hold, or removes it with null. |
ApplyAsync(hold) | A reserve and a commit in one step, eg a stock receipt, loading a gift card or a refund, checked against the bounds. |
SetAsync(id, value) | Sets the value to an absolute number, eg a stock count, keeping the held amounts, also when the value is below them. |
A checkout holds every line of an order for fifteen minutes:
var hold = await accumulators.ReserveAsync(new VoxHold
{
Id = $"order:{order.Id}",
ExpiresAtUtc = now.AddMinutes(15),
Lines = order.Lines.Select(line => StockPosition.OnHand.Change(line.StockPositionId, -line.Quantity)).ToList(),
}, cancellationToken);
if (hold.Outcome == VoxHoldOutcome.Refused)
{
// hold.RefusedLine.EntityId is the position that ran out, hold.RefusedLine.Available how many are left
}
// Two pairs were held, the warehouse found one: one is committed and the other given back
await accumulators.CommitAsync($"order:{order.Id}", [StockPosition.OnHand.Change(positionId, -1)], cancellationToken);
A discount code claim raises the code's total and the customer's balance under one hold, and expires after two hours so an abandoned checkout gives its use back:
var claim = await accumulators.ReserveAsync(new VoxHold
{
Id = $"code-claim:{checkoutId}:{code.Id}",
ExpiresAtUtc = now.AddHours(2),
Lines =
[
DiscountCode.Uses.Change(code.Id, +1, maximum: code.TotalUseLimit),
DiscountCode.UsesPerCustomer.Change(code.Id, customerKey, +1, maximum: code.UseLimitPerCustomer),
],
}, cancellationToken);
If the customer's limit is reached, neither balance changes and claim.RefusedLine is the customer's line.
Outcomes and retries
A refusal is a result, not an exception, since it's a normal outcome of a checkout: VoxHoldResult.Outcome is
Refused and RefusedLine names the line, how much its balance could still change, and whether it passed a bound or its
entity doesn't exist in published content. Nothing of a refused operation is kept, so the same id can be tried again later.
Every operation is idempotent by its id. Repeating one changes nothing and returns AlreadyCommitted,
AlreadyReleased or AlreadyApplied. A repeated reserve returns what has become of the hold: AlreadyReserved while it's
open, or AlreadyCommitted, AlreadyReleased or Expired. So a reserve that's delivered again after its hold expired,
eg 20 minutes later for a 15-minute hold, says Expired rather than letting the checkout go on as if the stock were
held. Reusing an id with other lines, other
commit amounts or for another kind of operation throws a VoxHoldMismatchException. Two concurrent operations with the
same id wait for each other, and only the first applies.
A commit, release or extend of a hold whose expiry has passed returns Expired and commits nothing; the hold's amounts are
given back then, if the expiry work hasn't already. Vox doesn't take the amount again: the application decides, eg to
apply a late gift card capture with ApplyAsync if the balance still allows it.
Expiry
Processing hosts release the holds whose expiry has passed, on every processing host, a batch at a time, reported by the
vox_accumulator_expiries health check. A hold is released within about the processing's idle check interval of its
expiry, 30 seconds by default. A hold committed just before its expiry stays committed. An application without a
processing host, eg one that only serves deliveries, can reserve, and its holds expire once a processing host runs.
Transactions
Accumulator operations join a Vox transaction with the caller's entity writes in the same storage provider: a claim and the application's own record of it commit together, or neither does.
await transactions.ExecuteAsync(async token =>
{
var claim = await claims.ClaimAsync(code, customerKey, checkoutId, token);
if (claim.Outcome == VoxHoldOutcome.Refused)
{
return;
}
await updater.CreateAsync(new CodeUsageActions.Create
{
Id = $"{checkoutId}:{code.Id}", Code = code.Id, CustomerKey = customerKey, HoldId = claim.HoldId,
}, cancellationToken: token);
}, cancellationToken);
A refused operation inside a transaction leaves the transaction's other writes as they were. A transaction that combines an Accumulator change with a write of an entity in Redis is refused, like any transaction across providers.
Outside a transaction, each operation is atomic on its own, and is tried again when the database picks it as a deadlock victim, since it's idempotent. Inside one, a deadlock fails the transaction like any other conflict.
An action handler's operation doesn't join the action's save: it commits when the handler runs. The handler may run again when the save meets a newer version of the entity, and the scoped part of authorization runs after it, so key the hold by the request and treat finding it already applied by the same request as done. See Effects outside the entity.
Busy balances
The balance rows an operation changes stay locked until its transaction ends. Changes of one balance, eg the total uses of a busy public code, wait for each other: keep transactions that change a busy balance short, and do slow work, eg a call to a payment provider, outside them. The lines of a hold are always changed in the order of their balances, so two orders that hold the same positions in a different order don't deadlock each other.
Calculations that read a balance
A calculation, an assessment or a projection publication reads tracked balances through its context, which records a dependency per balance, per key for a keyed one:
public class VariantStockCalculation : IVoxCalculation<ProductVariantBase>
{
public async Task CalculateAsync(ProductVariantBase variant, ProductVariantBase result,
IVoxCalculationContext context, CancellationToken cancellationToken)
{
var positions = await context.LoadRelatedAsync<StockPosition>(variant, cancellationToken);
var balances = await context.GetBalancesAsync(StockPosition.OnHand, positions.Select(position => position.Id), cancellationToken);
result.InStock = balances.Any(balance => balance.Value - balance.HeldOut > 0);
}
}
A committed change of a tracked Accumulator, also an expiry, evaluates those consumers again; a change that rolls back signals nothing.
The batch step of a projection reads the balances of the entities of its batch with its own overload, which makes each balance a dependency of its own entity only, so a stock change of one position publishes only that position's document again:
var onHand = await context.GetBalancesAsync(StockPosition.OnHand, positions, cancellationToken);
For the balances of other entities, eg the positions of each variant in a product's batch step, it declares each
balance for the entity whose document shows it with
accumulators.ReadTracked(context.For(product).Dependencies, StockPosition.OnHand, positionId), through an injected
IVoxAccumulators, and reads them with accumulators.GetManyAsync. context.ForAll.GetBalancesAsync works in
a batch step too, but there its balances are dependencies of every entity of the batch.
Only Accumulators declared tracked: true signal anything: Vox can't know whether anybody reads a balance without a read
per change. A change of an untracked one writes its balance and hold and nothing else: no history, search indexing, entity
change or dependency journal row. Reading an untracked Accumulator in a calculation fails with an error that says to
declare it tracked: true. A tracked Accumulator needs storage that tracks dependencies.
Choose what a calculation derives with the cost in mind. A calculated value that doesn't change isn't published, so a calculation that derives a coarse value, eg in stock or not, publishes its entity only when the last unit is held or stock returns. One that copies the exact quantity publishes its entity on every change, with what that costs in indexing and events. Totals over time, eg a usage dashboard, belong in reporting or a derived summary.
Threshold reads
A read like the one above is an exact read: the consumer gets the whole balance and is evaluated again on every change of it. A busy stock position changes hundreds of times an hour, and a calculation that derives "few left" finds the same answer for almost all of them. A threshold read passes an expression that turns the available amount into the value the consumer needs, and Vox evaluates the consumer again only when a change takes the amount across one of the expression's thresholds:
// Evaluated again only when a position's available stock crosses 0 or 5, never for 100 -> 99
var levels = await context.GetBalancesAsync(StockPosition.OnHand, positions.Select(position => position.Id),
stock => stock <= 0 ? StockLevel.Out : stock <= 5 ? StockLevel.FewLeft : StockLevel.Plenty, cancellationToken);
result.StockLevel = levels.Max();
GetBalanceAsync takes one id and returns one value, the keyed overload takes an id and keys, and the batch step has the
same two forms for the entities of its batch. A batch step reads the balances of other entities with
accumulators.GetTrackedAsync(context.For(product).Dependencies, StockPosition.OnHand, positionIds, expression): a
threshold read declares and reads in one call, since what it records depends on the amount it read.
The expression gets the available amount, Value - HeldOut: what can still be held or sold. With 6 on hand and
stock <= 5:
| Change | Value | Held out | Available | Evaluated again? |
|---|---|---|---|---|
| A checkout holds 1 | 6 | 1 | 5 | Yes: 6 to 5 crosses 5 |
| The checkout commits | 5 | 0 | 5 | No: the available amount didn't change |
| A stock receipt of 10 | 15 | 0 | 15 | Yes: 5 to 15 crosses 5 |
| A checkout holds 2 | 15 | 2 | 13 | No |
| A stock count sets 3 | 3 | 0 | 3 | Yes: 15 to 3 crosses 5 |
An exact reader of the same balance is evaluated on every one of those changes, the commit included. Both kinds can read the same Accumulator, even the same balance. A threshold read can't return the amount, so a consumer that shows it, eg "5 left", uses an exact read and accepts that the number lags the balance by however long the processing takes.
The amount may only be one side of a comparison (<, <=, >, >=, ==, !=) whose other side doesn't use it. The
values of those comparisons are the thresholds, and everything else is free: ?:, &&, ||, !, enums, strings and
method calls that don't take the amount. More than two levels are nested ?:, since C# allows no switch expressions or
patterns in expression trees.
stock => stock > 0has one threshold, at 0.stock => stock <= variant.LowStockLimit ? "few-left" : "many-left"evaluates the captured value when it reads, eg 5. The calculation depends onLowStockLimitthrough its read of the variant, so changing the limit to 3 evaluates it again, and from then on its threshold is 3. An optional limit, eg anint?, works as it is: while it's null the comparison is false for every amount and adds no threshold. So does one behind a null check, egvariant.LowStockLimit != null && stock <= variant.LowStockLimit.Value.stock => stock == 1 ? "last one" : "more"has thresholds just below and just above 1.<=and<differ at the boundary:stock <= 5flips between 5 and just above it,stock < 5between just below 5 and 5. With whole countsstock <= 4andstock < 5behave the same.
A read fails, with an error that names the expression, when the amount is returned (stock => stock), used in
arithmetic or a method call (stock => stock - 2 <= 3, stock => Math.Floor(stock / 10) > 1) or converted
(stock => (int)stock <= 5, where 5.5 would compare as 5): its answer could change between thresholds. Write the
comparison on the amount itself, eg stock <= 5, or use an exact read. A threshold read of an untracked Accumulator fails
like an exact one.
A consumer that reads one balance twice has one dependency on it: two threshold reads keep the amounts that are within both, and an exact read with a threshold read is evaluated on every change.
A threshold applies to one balance. "The total across warehouses is 5 or less" can't be told from the positions one at a time: A going from 3 to 2 while B stays at 3 takes the total from 6 to 5 without either crossing anything. Read the positions exactly for such a total, or keep the total as an Accumulator of its own.
Each change of a balance still visits every reader of it, to skip those whose answer it can't change. That costs nothing
for a stock position that a variant, a product and a projection read, but a balance that very many consumers read, eg a
campaign budget that each of 500,000 products reads to show "free shipping while the budget lasts", would visit all of
them on every checkout that spends from it. Give such a balance one reader instead: a calculation on the campaign derives
a field, eg BudgetLeft from money => money > 0, and the products read the field like any other, so they're reached
only when it changes.
Reading balances over HTTP and in the admin
Support staff can see balances, never change them: they're changed by application code only. The entity type model,
GET api/entity-types, lists each type's Accumulators with their declared bounds, and the API reads balances with the
same read permission as the entity:
GET /vox/api/gift-cards/GC-1001/accumulators
GET /vox/api/discount-codes/SUMMER25/accumulators/usesPerCustomer/keys?take=50
GET /vox/api/discount-codes/SUMMER25/accumulators/usesPerCustomer/keys?continuation=customer-0050
GET /vox/api/discount-codes/SUMMER25/accumulators/usesPerCustomer/keys?key=customer-4711
A singleton has the routes without an id, eg GET /vox/api/settings/accumulators. A page has 50 balances by default and
at most 200, in key order, and the keys endpoint never reads more than a page however many keys the entity has.
In the admin, an entity with Accumulators has a Balances section in its rail with the value, the held amounts and
what's available above the declared minimum, and a Balances tab with a page of each keyed Accumulator and a lookup of
one key. They show the same live values in every draft, release and perspective. A limit passed with each change, eg a
code's TotalUseLimit, isn't known to Vox; it's shown with the entity's other fields.
Retention and deleted entities
Finished holds and immediate changes are kept for VoxOptions.Retention.FinishedHoldAge, 30 days by default, so a late
retry still gets its first outcome. The vox_accumulator_maintenance work removes older ones a batch at a time on one
processing host. A retry that arrives later than that is applied as a new operation.
Deleting an entity deletes its balances: the first 500 in the transaction that deletes it, and the rest a page at a time in the background by the same work, eg a code used by 200,000 customers. Its open holds keep their lines; committing or releasing a line whose balance is gone does nothing for that line. An entity created again with the same id before the cleanup finishes keeps what's left of the old balances, and the cleanup stops. An open hold of the deleted entity that's released, committed or expires after the entity is created again changes the new entity's balance, eg a gift card's old authorization that expires gives back 300 kr the new card never held. Release or commit the open holds of an entity before deleting it, and don't reuse the ids of deleted entities that had open holds. Removing an entity type in a model migration removes its balances and hold lines.
A change of a balance of an entity that doesn't exist in published content is refused, eg of a code that's only a draft or has been unpublished.