Skip to main content

Transient entities

Transient entities are short-lived working state, such as carts, checkouts, reservations and sessions. They're read by id or by a query that one index answers, and they can expire.

Some entity types hold working state rather than catalog data: carts, checkouts in progress, stock reservations and browser sessions. They're large, since anonymous and abandoned carts accumulate, eg to hundreds of thousands in a busy shop, and they're read in a few fixed ways: a cart by its id, the cart of a browser session, the carts of a logged-in customer. They aren't calculated over or edited in drafts, and most of them are obsolete after a month.

A transient entity type declares that it's such a type with [VoxTransientEntity] on its class. The attribute says what the type promises and what it gives up, not where it's stored: configuration chooses the storage, see Where transient entities are stored.

// A cart expires 30 days after its last change
[VoxTransientEntity(ExpiresAfterSeconds = 30 * 24 * 60 * 60)]
public class Cart : IVoxEntity
{
// The ordinary IVoxEntity built-in properties are omitted here.

// The shop looks up the carts of a customer, so this relation keeps an inverse index
[VoxRelation(InverseName = "carts", InverseIndexed = true)]
public virtual VoxReference<ApplicationUser>? Customer { get; set; }

// Nobody asks which carts are in a market, so this one doesn't
[VoxRelation(InverseName = "carts")]
public required virtual VoxReference<Market> Market { get; set; }

[VoxFilterable]
public virtual string? SessionId { get; set; }

[VoxFilterable]
public virtual CartStatus Status { get; set; } = CartStatus.Active;

public virtual List<CartLine> Lines { get; set; } = [];
}

What a transient entity type promises​

A transient entity type keeps the contract of an entity type: its ids, route, JSON, generated actions, validation, permissions, change events, change handlers and subscriptions, and references to and from it. In return for being fast to read and write however many entities it has, it promises the following. Build() checks the rules of its declaration with an error that names the type and the rule, and queries and relation reads are checked when they're made. The rules are the same whatever storage the type is in, so a model or a query that breaks one fails on a developer's machine without Redis exactly as it does in production with Redis.

  • It's read by id, or by a query that one index answers. A query never scans the type, see Queries.
  • It's read in the inverse direction only through relations declared with InverseIndexed, see Inverse relations are opt-in.
  • It's untracked, as if it were declared [VoxNoDependencyTracking], see dependency and change tracking. It has no calculated fields, calculations, projections, evaluated assessments, context memberships or cached references that refresh when what they refer to changes, and the calculations and projections of other entity types can't read it. Cached references that refresh when the entity is loaded, eg the variant summary of a cart line, work as usual.
  • It isn't search-indexed. It can't have [VoxSearchable] fields or an enabled [VoxSearchIndex].
  • It isn't light or kept whole in memory. It can't be [VoxLightEntity], use UseWholeTypeCache or have the expected count Small, which keeps a type whole by default. A transient type is large and read by index, while a light type is small and read from memory.
  • It can't be authored, keep history, have unique constraints or unique relations, be a context type or have values that vary by context.
  • Its filterable and sortable fields have values an index can order: strings, enums, booleans, integers, float, double, decimal, DateTime, DateTimeOffset, DateOnly and Guid, or a collection of those for a filterable field, the value types every entity type can be filtered and sorted by, which Vox checks when the model is built. Related entities are filtered by with a relation filter instead. A string that contains the zero character can't be indexed, and a write of one fails.
  • It's never migrated by walking it. A stored document is upgraded when it's read, and written in the current revision the next time it's written, see Model changes.
  • It may expire, see Expiration.

Inverse relations are opt-in​

A relation of a transient entity type is read in the inverse direction only when it's declared with InverseIndexed = true. In the example, Customer is and Market isn't, so "the carts of customer c1" works, and "the carts of market se" fails:

// Works: Customer keeps an inverse index
var cartsByCustomer = await relations.LoadAllAsync<ApplicationUser, Cart>([customer], "carts", cancellationToken);

// Fails with a VoxQueryCapabilityException: Market keeps no inverse index
var cartsByMarket = await relations.LoadAllAsync<Market, Cart>([market], "carts", cancellationToken);

Every inverse read of a relation without InverseIndexed fails in the same way, whoever reads it: the relation loader, a lazy inverse collection, an inverse page, count or contains, the API's relation endpoints and expands, and a relation.market=se filter. The error names the relation and what to do:

Cart is a transient entity type, whose relation market keeps no inverse index, so carts can't be read from the Market side. Declare it with InverseIndexed = true to read it.

It never returns an empty list instead, since "this market has no carts" would be a wrong answer rather than a missing feature. The entity types endpoint and the MCP schema leave such a relation out of the other entity type, so a market's screen in the admin shows no carts tab or count, and an agent isn't offered them. Where Vox can tell at startup that something needs the inverse direction, Build() rejects the model instead: an InverseExpandable = true relation without InverseIndexed, and a [VoxMyRelation] without it, since a :My permission is answered from the inverse index.

InverseIndexed is an option of [VoxRelation], so a nested reference opts in with the attribute's Path, eg the variant of each cart line. It only matters for transient entity types: the relations of other entity types are always indexed in both directions. Forward reads, eg the market of a cart, always work.

Index-backed relations (IVoxRelationReferences<T>) of a transient type follow the same opt-in, and aren't allowed on a type that expires, see Expiration.

Queries​

People choose a transient type, and Redis, for speed, so a query of a transient type never scans. Every query must be answerable by reading at most one ordered index, only as far as its page, or by reading the entities it names by id. A query that can't be answered that way fails at once, before it reads any entity, with a VoxQueryCapabilityException that explains why and what to do instead. The check is the same in every storage and for every caller, so a query that works without Redis works with it.

UpdatedAtUtc is always indexed, and so is every [VoxFilterable] or [VoxSortable] field. The creation time is answered by the entity list and the id by the entities themselves. Version isn't indexed.

QueryExampleOrder
No condition, no sortGET /api/cartsCreation, then id
A sort by createdAtUtc, ascending or descending, or a range of itGET /api/carts?sort=-createdAtUtcCreation, then id
id equal to one or more ids, with any other conditions and the read scopeThe sensitive field check of a page of cartsCreation, then id
One equality of an indexed field, with up to 20 valuesGET /api/carts?sessionId=abcCreation, then id
One range of a single-valued indexed field, with at most one lower and one upper boundGET /api/carts?updatedAtUtc[lt]=2026-11-01The field, then creation, then id
A sort by one indexed field, without a condition or with a range of the same fieldGET /api/carts?sort=-updatedAtUtcThe field, then creation, then id
One relation filter of an InverseIndexed relation, with up to 20 idsGET /api/carts?relation.customer=c1Id in Redis, creation in Entity Framework
A restricted read scope from a :My permission, with no condition or sortA client that may read the carts of its own customerId in Redis, creation in Entity Framework
A count of any of the aboveincludeTotalCount=true

Some details of these shapes:

  • Ids bound the work. A query by id reads at most VoxReadBudgets.MaxItems entities, so its other conditions and the read scope are checked on them in memory without a scan. That keeps Vox's own id queries working, eg the check of sensitive fields on a page and the titles of picked references in the admin.
  • Several values of one equality or relation filter, up to 20, are each read only as far as the page and merged in the query's order. The total count is the sum of the parts: exact for a single-valued field or a relation, while a cart with two values of a filterable collection, eg two tags, is counted twice.
  • A query filtered by a relation is ordered by id in Redis, since its inverse index is, and by creation in Entity Framework storage. The same query works in both storages, with a different order. Sort the page in your code when the order matters.
  • A restricted read scope is the query's one condition. A client with :My access to carts gets them from the inverse index of the [VoxMyRelation], eg the carts of its customer. A filter or a sort next to the scope fails, since the scope already uses the query's one index: find the carts by the customer and check anything else, eg the session id, in your code.
  • Facets are left out of the result, as VoxQuery.Facets allows for a storage that can't count them, so the admin's cart list works without its choice counts.
  • Contexts are ignored, since a transient type has no values that vary by context, so the API's context selection changes nothing.
  • A transaction's changes are seen. A query in a transaction includes what the transaction wrote: a cart whose session id it changed from abc to xyz is found by xyz and not by abc, and the count agrees.
  • A scan (VoxQuery.Scan) keeps its creation-time boundary, see Pages, continuations and budgets.

What fails​

Anything that would need more than one index, or a scan, fails before anything is read:

  • Two or more conditions, eg carts?sessionId=abc&status=active or carts?relation.customer=c1&status=active, except next to an id filter. Choosing between indexes would mean guessing which one finds fewer carts: one session holds a single cart, while 80,000 carts may be active. Your code knows which condition is selective, so it chooses:

    Cart is a transient entity type, which is queried by one index. This query filters by sessionId and status. Filter by the one that finds the fewest Cart entities and check the others in your code.

  • A sort by another field than the filtered one, eg the carts of a session sorted by updatedAtUtc. Sorting needs every match in memory first, so sort the few carts of a session in your code:

    Cart is a transient entity type, which is read in the order of the one index it's queried by, so a query filtered by sessionId can't be sorted by updatedAtUtc. Sort the matching entities in your code.

  • A condition and a restricted read scope, eg carts?sessionId=abc by a client with :My access to carts.

  • A condition an index can't answer: an or or not filter, a filter by a field that isn't indexed, a sort by several fields, a range of a filterable collection (a cart with two tags would appear twice), more than 20 values or ids, a filter by references, assessments or draft status, and a relation filter with descendants or in the inverse direction.

  • A relation filter of a relation without InverseIndexed:

    Cart is a transient entity type, which is filtered by a relation only from its inverse index, which market doesn't keep. Declare it with InverseIndexed = true.

The query operators are equality and the greater-than and less-than comparisons, so there's no case-insensitive or starts-with filter to refuse.

Strings compare differently in the two storages. Redis compares them ordinally, byte by byte, while Entity Framework storage compares them as its database does, case-insensitively with SQL Server's default collation. So carts?sessionId=ABC finds the cart of session abc on SQL Server, and not in Redis. The values a transient type is queried by, eg session ids, are usually written and queried by the same code, so this rarely matters; don't rely on the case-insensitive match.

Where transient entities are stored​

Transient entity types are stored in the transient storage, EntityStorage.TransientStorageName. Registering Redis entity storage sets it when none is set:

vox.AddSqlServerStorage();

// Sets options.EntityStorage.TransientStorageName to "redis" when none is set
vox.AddRedisEntityStorage("redis", options =>
options.ConnectionString = redisConnectionString);

So with Redis registered, carts are stored in Redis and products in Entity Framework storage, without a selection per type. Without a transient storage, transient types are stored in the default storage, eg Entity Framework, under the same contract: a developer can run the shop without Redis and meet the same rules. UseStorage<TEntity>(name) still selects a storage for one type, eg a second Redis for sessions. Redis stores only transient types, see Redis for transient entities.

In Redis, each indexed field of a transient type is one sorted set, which the write maintains in its Redis transaction: a write that changes no indexed field, eg adding a cart line, touches only the UpdatedAtUtc index. Redis keeps an inverse index only for the relations declared InverseIndexed, and none of the forward direction, which it reads from the entities' own documents. So a cart in Redis is its hash, its member of the entity list, its index members and one member of its customer's inverse index, and nothing for its market, its channel or the variants of its lines. Entity Framework storage keeps its query storage and both directions of every relation in SQL as for any entity type; the rules above are what make a transient type behave the same there.

A Vox transaction can't combine Redis and Entity Framework entities, see Update several entities atomically. A transient type in Entity Framework storage can share a transaction with products, so an application developed without Redis can write a transaction that fails in production with it. Keep the writes of carts and of ordinary entities in separate transactions.

What's immediate and what follows in Redis​

A write to Redis commits the entity, its version, its index entries and, when something needs it, a durable change in one Redis transaction. One processing host then moves the change into the Vox database (vox_entity_storage_outbox), right after the write returns.

  • Immediate: reads by ID, version checks, index queries and relation lookups in Redis.
  • Durable but eventual: subscriptions and side effects, which follow once the change reached the Vox database.
  • Only what's needed: a change carries its event only when something subscribes to or has side effects of its entity type, see events, and deletions always. A write of a cart that nothing needs leaves no change at all, so it's one read and one Redis transaction.
  • Change handlers get the published changes from the instance that wrote them, right after the Redis transaction commits, as for Entity Framework, see in-process handlers.

Several Redis entity changes can share one Vox transaction, with optimistic version checks when it commits. Within it, the forward links held in an entity, eg a cart's customer or its lines' products, are read from what the transaction wrote. Index-backed links and inverse links are read as they were before the transaction: an action that adds a line to a cart doesn't find the cart among the product's inverse links yet. Entity Framework reads its own uncommitted links in both directions, so read links you've just written from what you wrote rather than from a read.

Model changes​

Transient entity types are never walked as a whole to migrate them, in either storage. A stored document is read in the revision it was written in, upgraded when it's read, as every document is, and written in the current revision the next time it's written. That has consequences, which follow from transient entities being short-lived:

  • No convergence. A model change that raises the revision of a transient type, eg a ConvertProperty on Cart.lines, finishes without touching its data, see Model evolution.
  • Migration classes are needed as long as documents written before them can exist. With no convergence, Vox considers the migration of a transient type complete at once, so it doesn't stop you from deleting the migration class. But a cart written before the migration keeps its old form until it's written again, and an abandoned cart never is. Say a cart line's Quantity changes from int to decimal with a ConvertProperty, and the class is deleted a week later: reading a cart abandoned before the change then fails, with an error that names the migration and asks to restore it. Keep the class until no document written before it can exist: for a type with a lifetime, that's the lifetime after the migration was applied, eg 30 days for carts; for a type without one, until its data is reset.
  • No index backfill. A field or relation that starts being indexed in Redis covers the entities written after the change. Entities written before it aren't in the index until they're written again. For carts the gap closes as old carts are updated, ordered or expire; an application that needs a complete index at once resets the storage.
  • No index cleanup. A field or relation that stops being indexed leaves its index in Redis. Nothing reads it, and it's removed with the entity type or by resetting the storage.
  • A changed value format of an indexed field leaves old entries. When the type or value conversion of an indexed field changes, eg the Status value Active is renamed Open, a write removes the entry in the new format, open, which isn't there, and the entry active of a cart that existed at the change stays in the index. Queries check every entry against the entity they load and skip such entries, so results stay correct, and each costs a few tens of bytes until the storage is reset.

Entity Framework storage builds the query storage of a newly filterable or sortable field as for any entity type, see Partial results while capabilities build.

Moving a type between storages isn't handled. Marking an existing entity type transient, removing the attribute or changing the transient storage moves the type to another storage, while its data stays in the old one. A real move depends on the case, eg dropping abandoned carts or copying them, so the application moves its data or resets it.

Expiration​

A transient type can declare a lifetime instead of an application job that deletes the carts nobody has touched for a while. Its storage removes an entity once the lifetime has passed:

// A cart expires 30 days after its last change
[VoxTransientEntity(ExpiresAfterSeconds = 30 * 24 * 60 * 60)]
public class Cart : IVoxEntity

The lifetime is counted from the entity's UpdatedAtUtc. Every change through the API or the entity updater moves it forward, so a cart that's in use never expires, and an abandoned one expires 30 days after its last change. Vox's own refresh of cached references keeps UpdatedAtUtc as it is, so it doesn't extend the entity's life: an admin who looks through abandoned carts, which refreshes their line's variant summaries, doesn't keep them alive. The lifetime is in seconds and must be positive; a type without it never expires.

Expiry is silent​

An expired entity simply isn't there any more. Nothing records that it went: no change event, no subscription delivery, no change handler call and no operational log entry. Code that uses a transient type with a lifetime must expect any of its entities to disappear between two reads:

  • a read by id returns nothing;
  • an update through the entity updater fails as not found;
  • a write that expects a version fails with a version conflict, as for any entity that doesn't exist;
  • a write without an expected version, eg an import that upserts carts by id, creates a new cart rather than merging into the expired one.

An application that needs to know about expiries listens to the change events of the writes and applies the same lifetime itself. A subscriber of such a type can't rely on relation revisions across an expiry either, since the expired entity's revisions are removed with its other entries.

Broken references to expired entities are expected. References to an expired entity aren't removed when it expires. An order that refers to the cart it came from keeps a reference to a cart that no longer exists, and reads treat it as a reference to a missing entity. For a type with a lifetime that's normal, unlike a broken reference between ordinary entities, eg a product and its category.

Ids are never reused​

The id of an entity of a transient type with a lifetime must never be given to another entity, also not after the first one expired. Transient entities almost always have GUIDs or other unique values as ids, and Vox generates a GUID when the application gives none. Vox doesn't enforce the rule, since it can't tell a reused id from a new one.

Here's what breaks: until the cleanup has run, what Redis kept of the expired entity in shared indexes points at the new entity with the same id. If cart cart-1 of customer c1 expires and the shop creates a new cart-1 for customer c2, "the carts of c1" returns the new cart, which belongs to c2.

No rich text or index-backed relations​

A transient type with a lifetime can't have rich-text fields or index-backed relations (IVoxRelationReferences<T>): Build() rejects them with an error that names the field or relation. Both keep entries in places shared with other entities, which nothing could find again once the entity has expired, and an index-backed relation can have thousands of links. Carts, checkouts, reservations and sessions need neither; use a reference property for a relation.

Cleaning up after expired entities​

In Redis, Redis's own key expiry removes the entity: every write sets the expiry of the entity's hash to its UpdatedAtUtc plus the lifetime, in the write's Redis transaction, so the cart is gone at exactly that moment without any job. In Entity Framework storage, which has no expiry of its own, Vox hides an expired entity from reads by id and queries, and their counts, from the same moment.

What's left behind is removed in the background, on one processing host at a time, every VoxOptions.TransientEntities.ExpiryInterval, 5 minutes by default (vox_transient_expiry, see background work):

  • In Redis, a trim removes the entries of expired entities from the keys they share with others, which Redis can't expire one member at a time: their members of the entity list, of the field indexes and of the inverse indexes, and their relation revisions. It reads no entity data and writes no events.
  • In Entity Framework storage, a purge deletes expired rows in batches, with their query storage, relation rows and relation revisions, without change events, history or recalculations.

Until that has run, relation reads can include expired entities: "the carts of customer c1" read through the relation loader or the API gets the id of a just-expired cart. Callers that load the related entities, eg the relation loader and the API's relation pages, find nothing for that id and leave it out. Relation counts, contains and the API's reference lists, which don't load the entities, include it until the trim in Redis or the purge in Entity Framework storage, usually within minutes. Queries of the entity store leave expired entities out at once.

While no processing host runs, leftovers pile up in Redis. A query skips them, at most VoxReadBudgets.MaxItems per page, and then returns a shorter page with HasMore and a continuation, so lists keep working with short pages. Page by HasMore and the continuation, not by "fewer than asked for means the end".

Changing the lifetime​

A changed lifetime, or a removed one, applies to an entity the next time it's written in Redis: until then, it keeps the expiry its last write gave it. In Entity Framework storage it applies to every entity at once, since the hiding and the purge use the type's current lifetime. So shortening a cart's lifetime from 30 days to 7 hides carts untouched for a week at once in Entity Framework storage, while in Redis they live until 30 days after their last write, unless they're written again meanwhile.

Redis must not evict​

Redis is the authoritative storage of transient types, so it must keep every entity until its lifetime has passed. Redis's volatile-* eviction policies evict the keys that have an expiry first when memory runs short, which would silently remove carts long before their lifetime, and the allkeys-* policies evict any key. Run the Redis of the entity storage with maxmemory-policy noeviction, and give it the memory it needs. Managed services often default to an evicting policy, eg Azure Cache for Redis to volatile-lru. Vox reads the policy from INFO memory when the Redis entity storage first connects, and logs an error when it isn't noeviction.