How a Plugin Framework Makes Uninstall and Collaboration Default Behavior
A plugin system does more than organize code into modules. It gives one answer to four runtime problems: installation, configuration, uninstall, and collaboration. This article explains why the framework should own resource cleanup through per-plugin scopes, how services replace direct imports, how configuration can be applied without a restart, and which trade-offs and checks matter when adopting the approach.
Modularization Solves Code Organization, Not Runtime Behavior
Splitting a chatbot from a single file into several modules makes the code easier to read and change. Modularization only answers “where the code lives.” It does not answer runtime questions. As features grow, a system faces four runtime problems at once:
- Installation. How a new feature joins a running system, who loads it, and in what order.
- Configuration. The same feature uses different parameters in test and production. Where that configuration lives, and who reads it.
- Uninstall. When a feature is taken offline, who cleans up the timers, event listeners, and network connections it registered. Incomplete cleanup leaks resources: memory keeps growing, the same message is handled more than once, or the process cannot exit cleanly.
- Collaboration. Feature A depends on a capability from feature B. B may not have started yet, or it may be replaced by another implementation while the system is running. A needs a reliable way to obtain that dependency and to react when it changes.
The value of a plugin system is that it gives one consistent answer to all four problems.
Why the Framework Should Own Uninstall
Most plugin systems leave cleanup to the plugin author. The author must remember to close every resource in an unload callback. That convention is fragile: miss one close call, and the process can fail weeks later in a way that is hard to trace.
A more reliable approach is for the framework to record the resources each plugin creates and reclaim them together on unload. The core idea is a scope for each plugin. Side effects registered inside that scope—timers, listeners, and child tasks—are attached to it. When the plugin is disabled, the framework releases those resources in reverse registration order.
The following sketch shows the idea:
class Scope {private disposers: Array<() => void> = [];onDispose(fn: () => void) {this.disposers.push(fn);}dispose() {// Release in reverse order: resources created later are reclaimed first,// so dependencies between them are not broken.while (this.disposers.length > 0) {const fn = this.disposers.pop()!;try {fn();} catch (err) {// Failure to release one resource must not block the others.console.error("resource release failed", err);}}}}function setupPlugin(scope: Scope, bus: EventBus) {const timer = setInterval(syncData, 60_000);scope.onDispose(() => clearInterval(timer));const off = bus.on("message", handleMessage);scope.onDispose(off);}
Two points matter. First, registration and release stay paired, and the framework schedules release. Plugin authors do not have to remember every cleanup detail. Second, reverse order and error isolation are necessary. Later resources often depend on earlier ones, so reverse release avoids touching objects that are already gone. If one disposer throws, the remaining resources must still be reclaimed.
Collaborate Through Services, Not Implementations
If feature A imports feature B’s module directly, the two stay tightly coupled. Replace B’s implementation and A must change. A better approach is for B to register a capability as a service. A only declares that it needs that capability. The framework decides which implementation provides it.
This pattern usually has three parts:
- Service registration. The provider registers an interface and an implementation in a shared registry.
- Dependency declaration. The consumer names the required service or interface and does not hold the implementation directly.
- Lifecycle coupling. The consumer is notified when the service becomes available, and again when it is replaced or revoked.
The names below are only illustrative:
// Provider: register a storage capabilityctx.provide("storage", {get: async (key) => db.get(key),set: async (key, value) => db.set(key, value),});// Consumer: declare the dependency and run when it is availablectx.require("storage", (storage, scope) => {const cache = createCache(storage);scope.onDispose(() => cache.flush());});
The consumer callback runs when the dependency is available and receives resources bound to its own scope. When the provider is unloaded or replaced, dependent callbacks are notified, and related resources are released or rebuilt. Startup order is no longer a hard constraint: A can start first and wire itself automatically once B appears.
This design has a cost. Startup order becomes implicit. Diagnosing “why this feature did not activate” means inspecting a dependency graph rather than reading the entry point. The framework therefore usually needs a way to query dependency state—for example, which services each plugin is still waiting for, and which services are already ready.
Why Configuration Can Take Effect Without a Restart
“Change configuration without restarting” sounds obvious, but it depends on several conditions.
Step 1: Validate. New configuration must pass schema validation before it is applied. If the type is wrong, a required field is missing, or a value is out of range, reject the change and keep the previous configuration running. This step is the basis of safe hot updates.
Step 2: Compute the difference. The framework compares the old and new configuration and finds what actually changed. Only the affected plugins or settings are reprocessed. Everything else stays as it is.
Step 3: Rebuild locally. For each changed plugin, the framework disposes the old scope and creates a new scope with the new configuration. Because resources hang off the scope, the old ones are fully reclaimed. Duplicate timers or listeners are not left behind.
Step 4: Roll back on failure. If rebuild throws, the framework should return to the last known-good configuration instead of stopping halfway.
A simplified view of that flow:
function applyConfig(next: unknown) {const result = configSchema.validate(next);if (!result.ok) {throw new Error(`config validation failed: ${result.message}`);}const changed = diff(currentConfig, result.value);const snapshot = currentConfig;try {for (const plugin of changed.affectedPlugins) {plugin.scope.dispose();plugin.scope = createScope();plugin.setup(plugin.scope, result.value);}currentConfig = result.value;} catch (err) {rollback(snapshot);throw err;}}
Not every setting is a good candidate for a hot update. Changing a listen port, switching a database address, or rotating a key often requires new connections, and sometimes the old connections must be closed safely first. The configuration schema should mark which items support hot update and which require a restart, and the framework should say so clearly when a change is applied.
Design Trade-offs
Automated lifecycle management improves stability, but it has clear costs.
- Extra overhead. Every scope keeps a resource list. With a large number of resources, memory use and dispose time matter.
- Implicit dependencies. Dependency injection decouples code, but call relationships are no longer obvious. Good logs and a dependency-graph query are more useful than reading the code alone.
- State migration. Rebuilding a plugin drops in-memory state. Data that must survive should live in a storage service, not in the plugin’s local variables.
- Misuse. If a plugin attaches resources to a global scope instead of its own, the framework cannot reclaim them. The framework should detect that and warn.
When choosing an approach, compare along these dimensions:
| Dimension | Manual management | Framework-owned scopes |
|---|---|---|
| Cleanup reliability | Depends on the author | Guaranteed by the framework |
| Learning cost | Low | Requires understanding scopes and dependencies |
| Diagnosis | Relatively direct | Needs a dependency graph and logs |
| Fit | Small projects | Systems with many features and frequent change |
Adoption Checklist
When applying this model to a project, check the following in order:
- Every plugin resource is registered on a scope, not scattered in module-level globals.
- Unload has been verified to bring the resource count back to zero, for example with a counter or a test.
- Plugins communicate through service interfaces, not by referencing each other’s implementations.
- A missing dependency produces a clear status, not a silent failure.
- Configuration has a schema, and items that support hot update are marked.
- A failed hot update rolls back automatically to the last usable configuration.
- A load, unload, and reload cycle test exists to catch resource leaks.
A plugin system is not valuable because of how many features it hosts. It is valuable if features can be brought online, taken offline, and replaced safely. Moving uninstall and collaboration from author discipline to a framework guarantee is the most important design decision in this kind of system.
