Skip to main content

Hosts

Vox isn't a hosted service: it runs inside your own .NET application, against your own database. A host is one running instance of that application. This page goes from one host to several, and on to serve hosts for customer traffic, and says at each step what the new setup requires.

One host​

A single host serves the API and the admin UI, and runs Vox's background work: the calculations, events, search indexing and deliveries that a change causes, see background work. It keeps two sets of tables: Vox's, for entities and Vox's own records, and those of Nexus, which keeps the queues and jobs of imports and projection publications.

var vox = builder.AddVox(options => { /* model */ })
.AddSqlServerStorage() // ConnectionStrings:Vox, with Nexus's tables in the same database
.AddProcessing() // this host runs Vox's background work
.AddApi()
.AddAdminUI();

var app = builder.Build();
app.MapVox();
await app.RunVoxAsync(args);

builder.AddVox registers Nexus with the queues and jobs of the features the host has, and builds Vox and Nexus when the host is built, see add Vox to your application.

RunVoxAsync migrates at startup. Before the host serves, it migrates the database to the model in code, activates that model, and runs the startup initializers, eg creating a missing database or the first administrator. With vox migrate arguments, eg dotnet MyApp.dll vox migrate --plan, it runs the command instead and exits. In production, the pipeline can migrate instead and the hosts only check the model, see migrating in production. Since the same Program.cs runs for both, the code before RunVoxAsync only configures the application, see installation.

A database that can't be reached for a moment at startup, eg during a deployment, doesn't fail the start: Vox tries again for about 2 minutes. A permanent error, eg a model that can't be migrated, fails the start at once. When the start is done, the host logs how long it took, phase by phase, see the startup log line.

Nexus's database​

On SQL Server and PostgreSQL, Nexus's tables share Vox's database by default, so a small installation has one connection string. Their names never clash, and Nexus's maintenance only touches its own tables. A busy installation gives Nexus a database of its own with ConnectionStrings:Nexus, so Nexus's queue traffic doesn't share the transaction log and I/O of Vox's writes. Startup creates it when it's missing. On SQLite, Nexus always has a file of its own next to Vox's, eg vox-nexus.db beside vox.db, since one SQLite file has one writer at a time.

Web setup​

Compress responses​

Vox doesn't compress what it sends. Turn on ASP.NET's response compression before MapVox():

builder.Services.AddResponseCompression(options => options.EnableForHttps = true);

var app = builder.Build();
app.UseResponseCompression();
app.MapVox();

The admin UI reads the model of every entity type each time it starts, eg about 4 MB of JSON for a model of 237 entity types, which compresses to about 110 KB. Without compression an editor on a slow connection waits for it every time the admin opens. Whether to compress over HTTPS is the application's choice: a compressed response that holds both a secret and text an attacker controls can leak the secret, see BREACH.

Serve the Nexus admin​

Serve the Nexus admin to see and control imports and projection publications, see monitoring. The CommerceMind.Vox.NexusAdmin package serves it at /vox/nexus, which MapVox() maps behind its gate:

var vox = builder.AddVox(options => { /* model */ })
// ...
.AddApi()
.AddNexusAdmin();

Only users and API clients with the vox:Nexus permission get in, checked on every request. Users open it from Jobs and queues in the admin UI's Administration menu, signed in through the admin UI's session, so the admin UI and the Nexus admin must be served from the same origin, as Vox serves them. A host that serves the admin UI elsewhere serves the Nexus admin from there too, eg through a proxy. Scripts call its API at /vox/nexus/api with an API key. A host without user management serves it to anyone who can reach it, as it does Vox's API. An application that calls UseAuthentication() itself calls it before MapVox(), since the gate sets the user that a later authentication would replace.

An open Nexus admin counts the messages of every queue every two seconds, so a tab left open on queues that keep millions of processed messages adds steady load to the Nexus database.

More than one host​

A single host shares its CPU and database connections between API requests and background work, so a large recalculation slows down the admin and the imports. Give the API hosts of their own and move the background work to processing hosts, or scale the single host out behind a load balancer. Either way, hosts then run on more than one machine.

Host roles​

A host either processes Vox's work or only produces it. Every write produces work: it commits the work that the change causes together with the entity data, and wakes the processing hosts. Processing is opt-in, with AddProcessing() from the CommerceMind.Vox.Processing package: a host without it never runs Vox's background work.

CompositionReferencesRegistration
Combined API and processingCommerceMind.Vox.Api, CommerceMind.Vox.ProcessingAddApi(), AddProcessing()
API onlyCommerceMind.Vox.ApiAddApi()
Processing onlyCommerceMind.Vox.ProcessingAddProcessing()

Any other application that writes through Vox, eg a console import tool, is a producer too. All hosts share the Vox database, the Nexus database and the same model, and every host logs its role at startup.

Every host has the import queues, so that it can enqueue imports; only a processing host has the jobs. The API host has no processing, and the processing host no API:

// API host
builder.AddVox(options => { /* model */ })
.AddSqlServerStorage()
.AddApi()
.AddAdminUI();
builder.Services.AddNexus().AddDatabasePollingInstanceEvents(); // or another cross-machine broker

// Processing host
builder.AddVox(options => { /* model */ })
.AddSqlServerStorage()
.AddProcessing();
builder.Services.AddNexus().AddDatabasePollingInstanceEvents();

An API write is durable even when every processing host is offline: the work it causes commits with the data, and the processing hosts do it when they're back. Every host that writes evaluates the saved entity's own calculations in the save, see settled saves, so an API-only host registers the application's calculation types and their dependencies like a processing host.

Add-ons with tables of their own​

Some add-ons keep tables in the Vox database, eg Studio its proposals. Every host that shares the database migrates its schema at start, so every host registers those add-ons, also a processing host that never serves them: AddVoxStudio() goes on the API host and on the processing host. A host without the add-on sees its tables as no longer used. With AllowDestructiveMigrations it drops them, and every proposal with them, and without it each start of either host compares the whole schema again.

What more than one machine requires​

A cross-machine broker​

Vox uses Nexus's instance events to wake the processing hosts after a write, and to invalidate caches, schemas and live subscriptions, so every host both produces and consumes them. When the application registers no broker, Vox registers a single-server one, which only reaches its own process. Hosts on more than one machine register a broker that reaches them all, eg database polling, Azure Service Bus or RabbitMQ, on Nexus's registration, which Vox then uses:

builder.Services.AddNexus().AddDatabasePollingInstanceEvents();

Nothing fails without one: other hosts serve stale models and caches, and work waits for the idle check.

Shared Data Protection keys​

Hosts behind a load balancer, and hosts that restart, must share and persist their ASP.NET Core Data Protection keys, eg with PersistKeysToDbContext or a shared directory. Image preview URLs, the signed content URLs of assets and preview grants are protected with them. With the default keys, which a container keeps in memory, a draft thumbnail made by one host answers 404 on another, and every preview URL stops working when a host restarts. This applies to a single container that restarts too. On Azure App Service, each deployment slot has keys of its own by default, see Data Protection keys.

Worker ids​

Each host has a worker id that identifies it within its deployment and survives a restart of its process. It defaults to the app's name and WEBSITE_INSTANCE_ID on Azure App Service, eg shop-api-7f3a…, and to the machine name otherwise. Give each host its own when several run on one machine: a host that starts with the same worker id as another replaces it, and the replaced host stops processing and running jobs for good, logs why, and reports it in its vox_deployment health check. Set it with VoxOptions.Deployment.WorkerId, eg from Vox:Deployment:WorkerId, at most 256 characters.

Synced clocks​

Processing hosts take turns on work with leases that each host judges by its own clock. A host whose clock runs more than the lease duration (2 minutes) ahead takes work that another host still holds. Keep the processing hosts' clocks in step with time synchronization, as hosted platforms do by default.

Serve hosts​

Vox Serve serves customer traffic, eg product pages, cards and CMS content, from a projection store, eg Redis, that Vox's publications write. Serve hosts behind a load balancer share neither hosts nor database reads with the backend that runs the admin, the imports and the processing, so large imports and recalculations don't slow down customer traffic, and customer traffic scales by adding serve hosts.

Vox Serve doesn't require the rest of Vox, Vox core. An application combines them as it needs:

CompositionVox core in the serve hostTypical use
One applicationYes, with the API and processingSmall sites, development
Backend plus serve hostsYes, as a producer, without the API or processingThe typical production setup
Serve hosts reading only projectionsNoExtra regions or an edge, far from the main database

What each costs:

  • One application runs everything in one host. Its publications can write the SQL projection store, eg in the application's own database, which keeps its documents across restarts. The SQL store also serves a serve host or two beside a small backend; use Redis when the traffic calls for it. Served pages only keep working while Vox's database is unavailable, as described below, when the projection store isn't in that database.
  • A serve host with Vox core reads and writes authoritative entities in process, eg gift card balances and payments, orders or usage claims. Those stop while the Vox database is unavailable, though its served pages keep working, which is right for a payment: it needs the authoritative answer. Such a host has the same model as the backend and deploys with the backend's release, with the same deployment id. It doesn't migrate the database and has no Vox API, so its own endpoints check their callers themselves. Reading product data from the entity stores there is as easy as reading a gift card, and defeats the purpose of the serve host: Vox Serve records the entity store reads of every request, see metrics.
  • A serve host reading only projections references CommerceMind.Vox.Serve and a store, nothing of Vox core. It deploys on its own and needs no Vox database. Writes that need an authoritative answer go to a host that has the entity stores, eg the backend.

Whatever reads only the projection store survives an outage of Vox core, a model migration or a failover of its database, as long as the store is up. Publications stop meanwhile, so served documents keep their last values until Vox core is back and catches up.

The registrations of each composition, previews through a serve host included, are in Vox Serve.

Regions​

Vox writes to one primary store. Other regions, eg Frankfurt beside Stockholm, run serve hosts that read a copy of it, made with the store's own replication, eg Redis replicas or an active-active Redis. A new region starts as a replica: the documents, the manifest and the catalog are all in the store, so it needs nothing from a backend. Don't add a publication sink per region: each would need its own full build and its own published state, where a replica just synchronizes. A serve host with Vox core in a region reads and writes the main Vox database, wherever it is.

Composing a host yourself​

builder.AddVox, MapVox() and RunVoxAsync cover an ordinary host. The building blocks under them stay available to a host that needs more control.

Nexus registrations of the application. Vox registers Nexus when the host is built, with the contributions of Vox and its features. The application adds its own with vox.ConfigureNexus(...), whose callbacks run in the order they were added, so one added after AddProcessing() sees the jobs that processing generates, eg to add a mutex to them:

vox.AddProcessing()
// The route publications share one route store, whose commits must not compete with each other
.ConfigureNexus(nexus => nexus.AddJobs(options =>
{
foreach (var job in options.GeneratedScheduledJobs.Where(job =>
job.GetParameters() is VoxEntityProjectionPublicationJobParameters publication &&
publication.Publication.EndsWith("/routes", StringComparison.Ordinal)))
job.Mutexes.Add("routes");
}));

An application's own builder.Services.AddNexus() registration, eg with a broker or queues of its own, is the one Vox uses. Vox builds it: a host composed with builder.AddVox that calls Nexus's .Build() itself fails at startup and says so. That's where several hosts register their cross-machine broker, see a cross-machine broker. Nexus in a database of its own, which a busy installation wants, needs no code: set ConnectionStrings:Nexus, see Nexus's database. A storage package's ConfigureNexusConnection = false leaves Nexus's connection to the application, eg to set Nexus's own connection options, with vox.ConfigureNexus(nexus => nexus.AddSqlServerConnection(...)).

Another container. Vox builds itself, after the application's last registration, through the host's service provider factory. An application that uses another container, eg Autofac with builder.Host.UseServiceProviderFactory(...), replaces it, and calls vox.Build() itself after its last registration, before builder.Build(). A host that forgets fails at start and says so.

Another pipeline. MapVox() maps the middleware and endpoints of every registered feature. A host whose pipeline differs from its registrations, eg a serve host that registers images for the sinks of its publications but serves no images, maps its pipeline with the features' own methods instead: UseAuthentication(), UseAuthorization(), UseVoxAdminUI(), UseVoxNexusAdmin() (after authentication), UseVoxServePreview(), MapControllers(), MapVoxImages(), MapVoxImageRoutes(), MapVoxRoutes(pattern), MapVoxServe(), MapVoxMcp(name, pattern) and MapVoxMcpIssuer().

Without a host builder. services.AddVox(...) on a service collection reads nothing from configuration and doesn't touch Nexus, eg for a test or a tool that composes Vox itself. The application then registers Nexus with Vox's contributions, AddVox(vox) on the Nexus registration, and builds Vox after Nexus, since Vox takes over the start of Nexus's job loop:

var vox = services.AddVox(options => { /* model */ })
.AddSqliteStorage(storage => storage.ConnectionString = "Data Source=/data/vox.db")
.AddProcessing()
.AddApi();

services.AddNexus()
.AddSingleServerInstanceEvents()
.AddVox(vox) // the queues, jobs and connection of Vox and its features
.AddVoxNexusAdmin(vox, environmentName)
.Build();
vox.Build();

On this path the options that read configuration or the content root need their values in code, eg UseAssets(rootPath), the storage's ConnectionString, the images' RenditionRootPath, the Azure Blob settings of AddVoxAzureBlobAssets and AddVoxAzureBlobRenditions and UseDevelopmentApiKey(environment). A host without RunVoxAsync calls IVoxDatabaseInitializer.MigrateAsync() before it serves.