Skip to content

Running several processes

Most apps start as one process: a single dotnet run that serves the API and runs the background jobs (sending emails, pushing notifications, syncing data). That is the default, and it needs no extra setup.

When traffic grows, or you want zero-downtime deploys, you run several copies of the app behind a load balancer. This page explains what changes when you do that, what Genie does about it for you, and exactly what to configure. No prior experience with clusters is assumed.

Word Meaning
Process (or node, instance) One running copy of your app, e.g. one dotnet run, one container, one IIS site.
Load balancer A front door (nginx, IIS ARR, Azure Front Door, AWS ALB…) that sends each request to one of your API processes.
Background worker A loop that runs inside the app without a user request: the email sender, the app-notification sender, the warehouse sync, the workflow SLA check.
Redis A small, fast, shared in-memory database. Genie uses it as the place where processes share state.
Lease A “token” in Redis that only one process can hold at a time. Whoever holds it is in charge.

Here is a typical setup: two API processes behind a load balancer, two worker processes (one active, one waiting as a spare), and one Redis and one database shared by all of them.

Diagram
API processes Worker processes Users browsers Load balancer nginx, IIS, cloud LB API process 1 Roles: Api API process 2 Roles: Api Redis cache · locks · pushes Database SQL Server / PostgreSQL Worker 1 active: holds the lease Worker 2 standby: waits Every process runs the same code. Only its role (and one small config file) differs.

In words:

  • Users only ever talk to the load balancer. It picks an API process for each request, so two requests from the same user can land on different processes.
  • API processes answer HTTP requests: tables, forms, workflow buttons, sign-in.
  • Worker processes run the background jobs. Only one worker does the work at a time; the other is a spare that takes over automatically if the first one dies.
  • Redis is where processes share what used to live in each process’s memory.
  • The database is shared, exactly as before.

Why one process “just works” and several need care

Section titled “Why one process “just works” and several need care”

Inside a single process, a lot of state can safely live in memory. With several processes, each one has its own memory, and that causes real problems:

What lives in memory What goes wrong with several processes What Genie does
Sign-in data: refresh tokens, MFA codes You sign in on process 1, your next request lands on process 2, which has never heard of you → random sign-outs Keeps the cache in Redis (Genie:Cache)
Live push connections (the notification bell) The worker sends a notification, but your browser is connected to an API process → the toast never appears Relays pushes through Redis (Genie:SignalR)
“Am I the one sending emails?” Two workers both send the same email → duplicates One active worker (the lease), and every row is claimed before sending
Workflow state Two people click Approve at the same moment on different processes → the step runs twice A short lock per workflow instance (Genie:Workflow:Concurrency)
“Have I applied the model changes?” Two processes start together after a deploy and both migrate → errors in the startup log A startup migration lock (Genie:Migration:UseLock)

Each of these is on by default as soon as Redis is configured. The rest of the page explains them one by one.

Every Genie process has a role, set with Genie:Hosting:Roles:

Role What the process does Typical count
Api Answers HTTP requests, serves the React app and the live-update hub. Runs no background jobs. 2 or more, behind the load balancer
Worker Runs the background jobs and the Hangfire job server. Serves no application API (its /api/* paths return 404). 1, or 2 for a spare
Api,Worker Both. The default, and exactly how a single-process app behaves. 1

You do not need separate projects. It is the same app with a different setting:

appsettings.Api.json
{ "Genie": { "Hosting": { "Roles": "Api", "NodeName": "api-1" } } }
// appsettings.Worker.json
{ "Genie": { "Hosting": { "Roles": "Worker", "NodeName": "worker-1" } } }

NodeName is optional. It is the friendly name shown on the dashboard (the default is machine-name:process-id).

A few things run in every process whatever its role, because each process needs them for itself: the startup database setup, model migration, warm-up, and wizard provisioning (wizard screens are built in each process’s memory).

You can also choose which background jobs a worker runs with AddWorkers(...). See Backend → Background workers.

If two workers both ran the email loop, each would pick up the same pending emails. So Genie makes sure only one worker is active at a time, using a lease in Redis:

  • Every worker process tries to take the lease when it starts. The first one wins and becomes active.
  • The active worker renews the lease every 10 seconds.
  • The others are standbys. They keep checking, and do nothing else.
  • If the active worker stops renewing (it crashed, was redeployed, or lost its network), the lease expires after 30 seconds and a standby takes it.
  • On a clean shutdown, the active worker hands the lease back immediately, so the spare takes over at once.
Diagram
The lease is one Redis key, genie:worker:leader. Whoever holds it is the active worker. 1 · Worker 1 is active renews the lease every 10 s worker 2 keeps checking 2 · Worker 1 stops crash, deploy or network cut renewals stop 3 · The lease expires 30 s after the last renewal at once on a clean stop 4 · Worker 2 takes over starts the loops + Hangfire dashboard shows the change

The timings are configurable:

"Genie": {
"Hosting": {
"Worker": {
"SingleInstance": true, // only one active worker (default)
"LeaseSeconds": 30, // how long the lease lives without a renewal
"RenewSeconds": 10, // how often the active worker renews it
"SingleHangfireServer": true // Hangfire jobs also run only on the active worker
}
}
}

The lease covers the normal case. But there is a short window during a handover: the old worker may be in the middle of a batch at the moment the new one starts. To make duplicates impossible even then, every notification worker (app, email, SMS) claims its rows before sending them.

Diagram
Worker 1 (active) claims rows 1, 2, 3 Worker 2 (old leader) tries the same rows gets none NotificationStore pending rows 1, 2, 3 ClaimedBy · ClaimedUntil Send, then release Delivered = true claim cleared 1 · claim (one UPDATE) 2 · same UPDATE → 0 rows 3 · send

How it works:

  1. A worker marks a batch of pending rows as its own in one database update (ClaimedBy, ClaimedUntil on NotificationStore). The update only touches rows nobody has claimed.
  2. A second worker running the same update a moment later gets zero rows, because they are already taken.
  3. The owner sends its rows, marks them delivered, and clears the claim.

If a worker crashes mid-batch, its claim simply runs out after ClaimSeconds and the rows are picked up again:

"Genie": { "Notifications": { "ClaimSeconds": 300 } } // keep it longer than one batch takes

The two claim columns are part of the engine’s database model, so include them in your EF migration like any other schema change:

Terminal window
dotnet ef migrations add NotificationClaims --context YourContext

Polling stays cheap as the table grows. The claim reads a filtered index that holds only pending rows, failed rows back off instead of being retried every cycle, and finished rows are deleted after Genie:Notifications:RetentionDays. See notifications.

Genie pushes live updates to the browser over SignalR: the notification bell, import progress, sequence numbers. A push only reaches browsers connected to the process that sent it. With several processes the sender (often the worker) is usually not the process the browser is connected to.

The Redis backplane fixes this: every process publishes its pushes to Redis, and every process forwards them to its own connected browsers.

"Genie": {
"SignalR": {
"Backplane": "Auto", // Redis when ConnectionStrings:Redis is set (default)
"ChannelPrefix": "inventory" // set this if several apps share one Redis
}
}

Backplane can also be Redis (always; startup fails without a connection string) or None (pushes stay inside one process).

Refresh tokens, MFA codes, the shared JWT signing key and idempotency keys all go through Genie’s cache. With Genie:Cache:Provider = Auto (the default), the cache lives in Redis as soon as ConnectionStrings:Redis is set, so every process sees the same sign-in state.

"Genie": { "Cache": { "Provider": "Auto" } } // Auto | Redis | Memory

Data Protection keys (which encrypt cookies and the stored JWT key) are configured separately and must be shared too:

"Genie": {
"DataProtection": { "Enabled": true, "Provider": "Redis", "ApplicationName": "inventory" }
}

If a process runs with a single role while its cache or Data Protection keys are still per-process, it logs a warning at startup telling you which setting to fix.

Workflow buttons run inside the HTTP request, so any API process can start a workflow and any other can continue it. The risk is two requests for the same workflow at the same moment, e.g. two managers clicking Approve together. Without protection both would pass the “is it still at this step?” check, and the step’s emails, webhooks or SQL would run twice.

Genie takes a short lock on the workflow instance for every transition, approval and cancel:

Diagram
Request A Approve · user 1 Request B Approve · user 2 Instance lock workflow:instance:42 Runs the transition then releases the lock Waits up to 5 s then sees the new state or gets 409 Conflict gets it busy
  • The first request gets the lock and does its work.
  • The second waits (up to WaitSeconds). When the lock frees up it runs against the new state, which normally means a clear message such as “no pending approval” because the work is already done. If the first request is still busy when the wait runs out, the second gets 409 Conflict (“Reload and try again”).
  • Starting a workflow on a record locks that record too, so two simultaneous starts create one instance. Starts that deliberately allow several instances (allowMultiple) are not locked.
"Genie": {
"Workflow": {
"Concurrency": {
"Enabled": true, // default
"LockSeconds": 120, // safety net if a process dies holding the lock; longer than your slowest step
"WaitSeconds": 5 // how long a second request waits before 409
}
}
}

When you deploy new model files, every process starts and runs model migration. Genie takes a lock around it: the first process migrates, the others wait, then see that every file is already applied (content-hash check) and skip it.

"Genie": { "Migration": { "MigrationExecution": "Yes", "UseLock": true, "LockTimeoutSeconds": 300 } }

Use MigrationExecution: "Yes" in production so unchanged files are skipped. If a process waits longer than LockTimeoutSeconds, it logs a warning and continues.

Watching it: the hosted-services dashboard

Section titled “Watching it: the hosted-services dashboard”

Each process reports itself to Redis every 5 seconds. The Hosted Services dashboard reads those reports, so it shows every process whichever one your browser happens to reach:

  • each node’s name, role and whether it is online;
  • which worker is active and which are standby;
  • every background job on every node, with live metrics;
  • Pause and Resume per node or for all nodes, and the pause survives a restart;
  • a Details window per service with its live state and up to seven days of run history (each run with a step-by-step trace), shared through Redis.

The API behind it is GET /api/v1/genie/hosted-services/cluster. See Background jobs & hosted services.

This sets up two API processes and one worker for an app called inventory.

1. Shared settings in appsettings.json (every process reads this file):

{
"ConnectionStrings": {
"SqlServer": "Server=db;Database=Inventory;User Id=app;Password=…;TrustServerCertificate=True",
"Redis": "redis:6379,password=…"
},
"Genie": {
"DataProtection": { "Enabled": true, "Provider": "Redis", "ApplicationName": "inventory" },
"SignalR": { "ChannelPrefix": "inventory" },
"Migration": { "MigrationExecution": "Yes" }
}
}

Cache, backplane, workflow locks, migration lock and the worker lease all switch on by themselves because ConnectionStrings:Redis is set.

2. One small file per role:

appsettings.Api.json
{ "Genie": { "Hosting": { "Roles": "Api" } } }
// appsettings.Worker.json
{ "Genie": { "Hosting": { "Roles": "Worker", "NodeName": "worker-1" } } }

3. Program.cs needs nothing role-specific. Use your normal Genie setup and add one line early in the pipeline, so a worker process refuses API traffic:

var app = builder.Build();
app.UseGenieExceptionHandler();
app.UseGenieRoleGate(); // Worker-only process: /api and /hubs return 404 (except the dashboard API)
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapGenieHubs(); // skipped automatically on a Worker-only process
app.Run();

(Hosts using MapGenieApp get the role gate automatically.)

4. Start the processes. The environment name selects the role file:

Terminal window
# two API processes (put these behind the load balancer)
ASPNETCORE_ENVIRONMENT=Api ASPNETCORE_URLS=http://0.0.0.0:5001 dotnet MyApp.dll
ASPNETCORE_ENVIRONMENT=Api ASPNETCORE_URLS=http://0.0.0.0:5002 dotnet MyApp.dll
# one worker (not behind the load balancer)
ASPNETCORE_ENVIRONMENT=Worker ASPNETCORE_URLS=http://0.0.0.0:5100 dotnet MyApp.dll

If you already use the environment name for something else (Production, Staging), set the role with an environment variable instead: Genie__Hosting__Roles=Worker.

The same thing with Docker Compose:

services:
api:
image: myapp
deploy: { replicas: 2 }
environment:
Genie__Hosting__Roles: Api
worker:
image: myapp
environment:
Genie__Hosting__Roles: Worker
Genie__Hosting__NodeName: worker-1
redis:
image: redis:7

5. Check it. Open the Hosted Services dashboard: you should see api-… nodes with no background jobs, and worker-1 marked Active worker running the notification and sync jobs. To try failover, start a second worker (NodeName: worker-2): it shows as Standby. Stop worker-1 and watch worker-2 become active.

Setting Default What it does
ConnectionStrings:Redis (none) Turns on everything below that says Auto.
Genie:Hosting:Roles Api,Worker What this process does.
Genie:Hosting:NodeName machine:pid Name on the dashboard and in Hangfire.
Genie:Hosting:Worker:SingleInstance true Only one active worker.
Genie:Hosting:Worker:LeaseSeconds / RenewSeconds 30 / 10 Lease lifetime and renewal interval.
Genie:Hosting:Worker:SingleHangfireServer true Hangfire jobs run only on the active worker.
Genie:Cache:Provider Auto Auto / Redis / Memory.
Genie:SignalR:Backplane Auto Auto / Redis / None.
Genie:SignalR:ChannelPrefix (none) Separates apps sharing one Redis.
Genie:Notifications:ClaimSeconds 300 How long a worker owns a batch it picked up.
Genie:Notifications:RetentionDays 90 Delete finished notifications after this many days (0 = keep).
Genie:Workflow:Concurrency:Enabled true Lock workflow changes per instance.
Genie:Workflow:Concurrency:LockSeconds / WaitSeconds 120 / 5 Lock safety net, and how long a second request waits.
Genie:Migration:UseLock / LockTimeoutSeconds true / 300 Migrate one process at a time on startup.
Genie:DataProtection (off) Set Enabled: true, Provider: "Redis", ApplicationName.

Every section can also be set in code: UseRoles, ConfigureHosting, ConfigureCache, ConfigureSignalR, ConfigureNotifications, ConfigureWorkflow, ConfigureMigrations. See the configuration reference.

Users get signed out randomly. The cache or Data Protection keys are not shared. Check the startup log for a [CLUSTER] warning, set ConnectionStrings:Redis, and configure Genie:DataProtection with Provider: "Redis".

Notifications arrive late or the bell does not update live. Check that ConnectionStrings:Redis is set on every process and Genie:SignalR:Backplane is not None. Check the dashboard shows an Active worker.

Both workers say “Active”. SingleInstance is false, or one of them cannot reach Redis (it then logs “No Redis connection is registered”). Notifications are still never sent twice, because rows are claimed.

A worker returns 404 for every API call. That is intended: a Worker process serves no API. Send API traffic to the Api processes.

Two apps share one Redis and see each other’s data. Use a separate Redis database per app, and set Genie:SignalR:ChannelPrefix and Genie:DataProtection:ApplicationName per app. Genie’s lock, lease and cache keys are not prefixed per app.