Skip to main content

The application lifecycle: who does what

An application on Isoplane goes through five stages, and Isoplane decides when each one happens. For each stage, this page says what Isoplane takes care of and what is left to your application.

StageWhenIsoplaneYour application
Template initializationWhen creating a template, before requestsRuns Program.cs and saves the application's memory as a templatePrepares shared state, and closes every connection it opened
Instance startEach time an instance startsCopies the template and reseeds random generatorsReplaces copied state that has to be unique to each instance, such as an identifier
Handling a requestEach requestDelivers the request, suspends the instance while it waits, enforces limitsAwaits its work, and forwards the request's cancellation token to the asynchronous calls it makes
Between requestsWhenever an instance has no requestKeeps the instance and its pending timers for later, or discards itExpects nothing to run on time and nothing to survive
A new build or changed settingsWhen you change the application or its settingsPrepares a new template when needed; matching captured state may be reusedKeeps what must outlive a build somewhere else

An instance is one running copy of the application. Isoplane runs as many as the traffic needs, up to the application’s instance limit. The template is the memory every instance starts from.

Template initialization​

Isoplane runs initialization while creating a template, ahead of requests. In an ASP.NET application it runs Program.cs up to RunAsync, then raises Template.Initializing. When the callbacks have finished it saves the application's memory as the template. Each preparation of a template runs the callbacks again, so make their external work safe to repeat. An unchanged local session can reuse an already prepared template, which runs no initialization callbacks.

var app = builder.Build();
app.MapGet("/todos", (TodoStore store) => store.All());

// Runs during template preparation; retries can run it again.
Template.Initializing += async () =>
{
await app.WarmupAsync("/todos");
};

await app.RunAsync();

Isoplane

  • Runs Program.cs during preparation, with the application's settings and the network available to it.
  • Awaits the Initializing callbacks one at a time, in the order they subscribed.
  • Saves everything left in memory, and starts every instance from it.
  • Refuses to start the application if initialization throws, or if a connection or stream is still open when the callbacks have finished.
  • Saves timers and BackgroundService loops still running when the callbacks have finished with the template, and carries them on in each instance between requests. A timer counts from when that instance starts.

Your application

  • Does its expensive one-time work here, so that no request pays for it: load reference data, build lookup tables, and serve itself a request with WarmupAsync so that routes, serializers and database models are ready. Given a path it sends a GET; given an HttpRequestMessage it sends any method, with headers and a body, for a route such as a search that takes a POST. Preparation attempts can serve these requests again, so send requests safe to repeat. Reusing a prepared template sends none.
  • Awaits all I/O, and closes every connection and stream before the callbacks return. An open connection cannot be saved in the template, so Isoplane refuses to start an application that leaves one. A database driver's connection pool keeps connections open after use, so turn pooling off, as Connect to PostgreSQL does.
  • Creates nothing that should be unique to an instance. Whatever initialization leaves in memory, including a random value or an identifier in a static field, is the same in every instance.
  • May leave timers and BackgroundService loops running, on the terms Background work describes. A timer with 30 s left when initialization ends becomes eligible 30 s after an instance starts.

What can go wrong

In each case the application does not start, and the terminal shows the reason.

ConditionWhat you see
Program.cs or an Initializing callback throwsThe exception that was thrown
A connection, stream or DNS result is still open when the callbacks finishA message that names the kind, such as initialization retains a TCP socket; dispose it before capture. For a socket or a DNS lookup, it also gives the stack trace of the code that opened it. For a connection in an HttpClient pool, the trace is of the code that created the client's handler
Code waits synchronously or starts a threadPlatformNotSupportedException, which fails initialization unless the code catches it
Initialization runs longer than Isoplane allowsInitialization is stopped
The entry point calls Run, or does not await RunAsyncA build error, ISOPLANE1020 or ISOPLANE1021, before anything runs

A setting read during initialization is saved in the template with everything else, and every instance has the same settings.

An application without ASP.NET has no Program.cs, and marks one method [TemplateInitializer] instead.

Instance start​

An instance starts as a copy of the template. Before it handles its first request, Isoplane raises Instance.Starting.

var instance = Guid.Empty;

// Runs in each instance, before its first request.
Instance.Starting += () =>
{
instance = Guid.NewGuid();
return Task.CompletedTask;
};

Isoplane

  • Gives the instance its own copy of the template's memory.
  • Reseeds Random.Shared, every Random that was created without a seed, the generator behind Activity trace and span identifiers, and the one behind SQLite's random() and randomblob(). Cryptographic randomness needs no reseeding: every call draws fresh bytes.
  • Awaits the Starting callbacks one at a time, in the order they subscribed. Background work saved in the template waits until these callbacks finish. A callback can still await its own I/O or timer. An exception from one fails the request the instance was started for.

Your application

  • Subscribes during initialization. Subscriptions are saved in the template, so every instance runs them.
  • Replaces any value copied from the template that has to be unique to the instance, such as an identifier or a token.
  • Reseeds what Isoplane cannot: a Random constructed with a seed, even when that seed was itself random, and a generator that is not a System.Random, such as one inside a library.
  • Reloads shared state that may have changed since preparation. For example, in Instance.Starting or an [InstanceStart] method, await a read of your application's protection keys and revocations. Keep earlier unrevoked keys available to read data they protected. If revocations must reach running instances within a deadline, check freshness when using the keys. A background timer can be delayed.

What can go wrong

ConditionWhat happens
A Starting callback throwsThe request the instance was started for fails, and the instance is not used again. The next request starts another instance, which runs the callbacks again.
Initialization left more in memory than an instance is allowedNo instance can start. Reduce what initialization keeps.

An application without ASP.NET marks one method [InstanceStart] instead.

Handling a request​

Isoplane hands a request to one instance. While the request waits on an asynchronous operation, other requests and eligible background work can run on the same instance. When nothing is ready to run, the instance parks without occupying a worker thread.

Isoplane

  • Delivers the request and returns the response.
  • Gives each ASP.NET request its own HttpContext.TraceIdentifier.
  • Cancels the request's token, HttpContext.RequestAborted or RequestHead.Aborted, when the client goes away before it has the whole response, or the request has used its running time.
  • Discards whatever the request writes or returns after its client has gone away. A write still completes, unless the token passed to it is cancelled, and then it throws OperationCanceledException.
  • Enforces the resource limits. It stops an instance whose request has not finished 5 seconds after its token was cancelled, and the other requests on that instance fail with it.
  • Ends the request once its response is complete, and hands any work the request left pending to the instance's background work.

Your application

  • Awaits everything the request needs before it responds. Work started and not awaited may never finish.
  • Uses asynchronous APIs throughout; see how .NET differs on Isoplane.
  • Forwards the cancellation token to the asynchronous calls it makes.
  • Disposes what it opens. Do not leave cleanup to a finalizer.
  • Can use IHttpClientFactory with normal connection pooling and handler lifetimes; see Outgoing connections.
  • Saves anything that must last to a database or another external service before it responds.

What can go wrong

ConditionWhat happens
An ordinary handler exception is not handledThat request receives status 500 if its response has not started; otherwise its response is aborted. The instance and other requests remain available.
Code waits synchronously or starts a threadThe call throws PlatformNotSupportedException
The client goes away before it has the whole responseThe request's token is cancelled
The request uses up its running timeThe token is cancelled. If the request has not finished 5 seconds later, Isoplane stops the instance and the request fails.
The request starts more operations than its pending-operation cap allowsThe extra operations wait their turn and start as earlier ones complete. Nothing fails.
The response is complete while work the request started is still pendingThe request ends and the work becomes the instance's background work. A pending request-body read fails.

Between requests​

An instance may run background callbacks and retain connections between requests. Isoplane may discard it at any time. Successive requests can reach different instances.

Isoplane

  • Decides how many instances run and which one gets a request, within the application's instance limit, including instances finishing cancelled requests.
  • Discards instances without a shutdown callback or guest cleanup.
  • Runs ready background work within the instance's background allowance, and delays it while the allowance is exhausted.
  • Retains connections until the application or the peer closes them, or the instance is discarded. Retained connections still count against the outbound connection limit.
  • Evicts an idle instance five minutes after its last request finishes, whatever it still holds, unless another request arrives. Background work does not count as use.

Your application

  • Relies on no loop or queue consumer to run in the background, and on no timer to run on time. A BackgroundService carries on between requests only while its instance exists.
  • Treats memory as a cache. Static fields and IMemoryCache belong to one instance and vanish with it.
  • Expects a connection kept from an earlier request to be stale, and opens another when it is.
  • Sizes any database pool for one instance. An external pooler can cap database connections across the application.

What can go wrong

ConditionWhat happens
Isoplane discards the instanceNothing is reported. Its memory is gone, and the next request reaches an instance that starts from the template.
A connection kept from an earlier request has gone staleIts next use fails as a dropped connection does anywhere. Open a new one.
Isoplane discards an instance whose BackgroundService is still runningThe service stops where it was. Its stopping token is not cancelled and StopAsync does not run.
A timer comes due while the instance is idleIts callback runs as background work when the allowance permits. It never runs if the instance is discarded first.

A new build or changed settings​

When preparation inputs change, Isoplane prepares a new template. Local development may reuse matching captured state after a restart or rebuild, without rerunning initialization callbacks.

Isoplane

  • Runs initialization when a new template is needed; reusing captured state runs no callbacks.
  • Starts instances from the selected template.

Your application

  • Keeps what must outlive a build outside the instance.
  • Does not depend on data protected by ASP.NET Core Data Protection outliving a build, unless it keeps its keys across builds. By default, a fresh preparation can generate a different key. Configured secrets take effect when a template is prepared with those settings. An external store registered with the SDK supplies the current keys and revocations each time an instance starts, including from a reused template.

What can go wrong

ConditionWhat happens
The rebuild fails under isoplane devThe terminal says why, and the last working application stays available
Initialization fails for the new buildThe same as under Template initialization
The instance's key ring lacks the key used to protect a cookie or tokenThe instance cannot read that cookie or token