Skip to content

Microkernel / Plugin Architecture ​

"The microkernel architecture pattern consists of two types of architecture components: a core system and plug-in modules." — Mark Richards, Software Architecture Patterns, O'Reilly, chapter 3 "Microkernel Architecture"

Summary: A microkernel (plugin) architecture keeps a small, stable core that does the common work and moves everything that varies into plugins that implement a versioned contract and join through a registry, so new behaviour arrives without editing the core. Focus: Core versus plugins, contracts, registries and discovery, extension-point types (strategy, typed set, hooks, pipeline), isolation levels (in-process, RPC process, WASM, container), lifecycle, plugin dependencies and versioning, security, performance, anti-patterns, the style at service scale (gateway filters, sidecars, Envoy WASM), and one shipping-rate engine built in Go and Laravel with a third-party plugin added without touching the core. Learning goal: Given a product that must be customised per customer, tenant or integration, decide whether a microkernel fits, choose the extension-point type and the isolation level, design the contract and its versioning, and implement the registry, the lifecycle and a plugin in Go and Laravel.

This chapter belongs to the Architecture Styles group. The sibling styles are Layered Monolithic Architecture, Modular Monolith and Pipe-and-Filter; the difference between a style and a pattern is in Styles vs Patterns. Plugin boundaries at network scale continue in API Gateway, BFF and Service Mesh and Service Communication. The design principles behind a good contract are in Software Design: Dependency Inversion.

Page map ​

If you are looking forGo to
The style in a few tablesEverything in one minute
Why a core plus plugins at allWhy it exists
Operating systems, Eclipse, OSGi, WordPress, VS Code, go-pluginWhere it comes from
One block per conceptThe concept catalogue
Contract and versioning rules, error messages, knobsMechanics
The shipping-rate engine in Go and LaravelGo, Laravel
Plugins reaching into the core, god registry, dependency hellSolving the classic problems
Which isolation level, which extension pointChoosing
Plugins in a monolith, a modular monolith, microservices, at scaleIn architecture
Run it, add a third-party plugin, break itLab
Wrong beliefs, cheat sheet, self-check, terms, sourcesMisconceptions, Cheat sheet, Self-check, Glossary, References

Everything in one minute ​

The vocabulary. Every row is unpacked in the concept catalogue.

TermIn plain wordsTiny exampleWhat goes wrong without it
Core system (microkernel)The small part that every user needs and that rarely changesThe shipping Engine and RegistryThe core grows a branch per customer
PluginA separate piece that adds one capability through the contractfastbox carrierEvery new carrier edits core code
Plugin contractThe interface and rules the core promises to keepCarrier with Manifest() and Quote()Plugins depend on internals and break at each core release
RegistryThe core's list of installed plugins and their stateRegistry.Register, tagged container bindingsThe core hard-codes if name == "ground"
DiscoveryHow the registry learns what existsblank import, Composer extra.laravel, config listPlugins exist but nobody calls them
Extension pointA named place in the core where plugins attachstrategy, typed set, hook, pipelinePlugins patch core code
Isolation levelHow far a plugin is separated from the hostin-process, RPC process, WASM, containerOne bad plugin kills the host or steals secrets
LifecycleThe states a plugin goes throughregister, init, active, disabled, stopHalf-started plugins answer requests
Plugin versioningA rule for which plugin versions a core acceptsAPIVersion = 2, manifest checkA core upgrade silently breaks plugins

Four extension-point types, one table.

TypeThe core...Typical APIExample products
Strategy / driverpicks exactly one implementation by nameManager::driver('x'), sql.Open("pgx", ...)Laravel cache and mail drivers, Go database/sql
Typed setcalls all implementations and mergestagged bindings, slice of interfacesOur shipping engine, Terraform providers in one plan
Hook (action / filter)announces moments; plugins react or change a valueadd_action, add_filterWordPress, Composer plugin events
Pipeline / middlewarepasses the work through plugins in ordernext(ctx)HTTP middleware, Caddy handlers, Envoy filter chain

Four isolation levels, one table.

LevelMemory shared with the host?A crash...Speed of a callTypical use
In-process libraryYeskills the hostnanosecondsTrusted internal plugins, Go init() registration, Composer packages
In-process WASMNo (own linear memory)traps inside the sandboxmicrosecondsEnvoy WASM filters, wazero-hosted rules
Separate process, RPC/gRPCNothe host survives0.1 to a few msgo-plugin (Terraform, Vault, Nomad), VS Code extension host
Container or microVMNo, plus OS limitsthe host survivesnetwork hopUntrusted tenant code, hosted plugin platforms

Why it exists ​

Some products have a part that is the same for everyone and a part that differs for every customer, market or integration. A single codebase handles the second part either with growing if ladders in the core or with a separation: a small core that does not change, and plugins that do. Richards describes the target: "The microkernel architecture pattern allows you to add additional application features as plug-ins to the core application, providing extensibility as well as feature separation and isolation."

Without a plugin boundaryWith a plugin boundary
New carrier, new payment provider, new rule: edit the core and redeploy everythingNew carrier is a package that implements one interface
The core test suite grows with every variantThe core is tested against stub plugins; each plugin has its own tests
Customer-specific code sits in the main branchCustomer code lives outside; the core never sees it
Fast to startNeeds an up-front contract; slower to start
Good for: one product, one customerGood for: products, platforms, ecosystems
Core system (stable, small)Contract (versioned)Carrier: Manifest() + Quote(ctx, parcel)Registryname to pluginEnginefan-out, mergeLifecycle + hooksinit, enable/disable, close; filters, observerstimeouts, panic recoveryflatbuilt-in plugingroundbuilt-in, has configfastboxthird-party moduleremote carrierseparate process, RPCtenant ruleWASM, sandboxedrate filterhook pluginHow plugins join the registrystatic import (init) | config list | filesystem scan | Composer extra.laravel | Go module + xcaddyRule: plugins depend on the contract; the core depends on no plugin; plugins avoid each other.

The picture shows the shape: a core that holds a contract, a registry and an engine, and plugins around it. Arrows run from plugins to the core, never between plugins.

The analogy we reuse: a power strip and its appliances. The strip (core) supplies the same socket standard (contract) to a lamp, a kettle and a charger (plugins). You can add any appliance that fits the socket without rewiring the house. The strip does not know what a kettle is. If it had a special slot for the kettle only, it would no longer be a strip.

Three common misunderstandings, up front ​

  1. "A plugin architecture is a folder where you drop .so or .jar files." That is one discovery method and one isolation level. The style is the separation of a stable core from variation behind a contract. Caddy compiles its plugins into the binary; Terraform runs them as subprocesses.
  2. "Microkernel and microservices are the same idea with similar names." The name comes from operating systems. A microkernel app is usually one deployable with in-process plugins; microservices are many deployables. They combine (microkernel at service scale) but are different decisions.
  3. "Plugins make a system flexible for free." Richards rates the style's development ease low: "The microkernel architecture requires thoughtful design and contract governance, making it rather complex to implement." You pay for the contract, its versioning and the registry.

Where it comes from ​

Operating-system microkernels. The name comes from operating systems. Wikipedia defines a microkernel as "the near-minimum amount of software that can provide the mechanisms needed to implement an operating system", such as address-space management, thread management and inter-process communication (secondary source). The first microkernels, notably Mach, "proved to have disappointing performance" per the same article, and most large-scale Mach-based efforts moved services back into the kernel by about 2000. The cost of crossing a boundary is a lesson that returns in performance.

POSA, 1996. Pattern-Oriented Software Architecture, volume 1 (Buschmann et al.) lists Microkernel among its architectural patterns. We did not read the book; the architecture-style framing used here comes from Richards (below), and the reader should treat any "POSA says" claim in secondary sources as unverified.

Eclipse and OSGi, 2001 onwards. The Eclipse FAQ says: "A better question in the context of Eclipse is, What isn't a plug-in?" Nearly everything in Eclipse is a plug-in; a tiny launcher finds and starts them. The OSGi Alliance generalised this into a dynamic component system for Java. Its overview describes the layers: "Life-Cycle – The API to install, start, stop, update, and uninstall bundles", plus a service registry where "A bundle can create an object and register it with the OSGi service registry under one or more interfaces."

WordPress hooks. The WordPress Plugin Handbook defines hooks as "a way for one piece of code to interact/modify another piece of code at specific, pre-defined spots", in two kinds, actions and filters. The core ships many named hook points and also uses them itself; plugins and themes attach to them.

Richards, the style named. Mark Richards' Software Architecture Patterns (O'Reilly) and later Fundamentals of Software Architecture (Richards and Ford) name the style "microkernel (plug-in)". Richards says the pattern "is a natural pattern for implementing product-based applications" and that for products it "should always be your first choice as a starting architecture", with the reservation that scalability is low because most implementations "are implemented as single units". (We read the O'Reilly report text; we did not read the Fundamentals chapter, so the star ratings quoted later are the report's.)

Process-separated plugins, 2012 onwards. HashiCorp's go-plugin README says: "When we started using plugins (late 2012, early 2013), plugins over RPC were the only option since Go didn't support dynamic library loading." Terraform providers, Vault, Nomad and Packer use it. Go's plugin package arrived later, with limits its own documentation lists.

Compiled-in modules. Caddy v2 takes a third route: "A Caddy module is any named type that registers itself as a Caddy module when its package is imported", and the xcaddy tool "compiles Caddy with your plugin".

Editors and sandboxes, 2015 onwards. VS Code runs extensions in a separate extension host and loads them lazily through activation events. Envoy added an HTTP Wasm filter so that a plugin written in another language runs inside the proxy's sandbox, still marked experimental in the current docs.

text
     Year   Idea                                      What changed in practice
1    1970s  OS microkernels                            Small trusted core, services outside
2    1996   POSA Microkernel pattern                   Pattern named (book not read here)
3    2001   Eclipse: everything is a plug-in            Product = platform + extensions
4    2000s  WordPress actions and filters               Hook names as the public API
5    2012   HashiCorp plugins over RPC                  Process isolation, language-neutral
6    2015+  VS Code extension host, activation events   Lazy loading, crash isolation
7    2019+  WASM filters (Envoy), wazero                 Sandboxed in-process plugins

The concept catalogue ​

Core system and plugins Must-know ​

In plain words: The core is the part every user needs and that changes rarely; plugins are the parts that differ between users and that change often. The core knows only the contract.

Common misunderstanding: "The core must be tiny." It must be stable, not tiny. Richards says the core "traditionally contains only the minimal functionality required to make the system operational", but for a business application it is "the general business logic sans custom code for special cases".

Definition: The core is the set of components that implement the shared behaviour, own the contract, the registry and the lifecycle, and depend on no concrete plugin. A plugin is a component that implements the contract, is discovered by the registry and can be added or removed without changing the core's source.

text
     Actor        Step
1    Core         defines Carrier contract (API v2)
2    Plugin       implements Carrier, declares Manifest{APIVersion: 2}
3    Registry     Register(plugin): check name, check API version
4    Core         Engine.Quote(parcel): asks Registry for active carriers
5    Plugin       Quote(...) returns rates
6    Core         merges, filters, sorts; shows the result

Real scenarios: an IDE (editor core, languages as plugins); a CMS (content core, SEO and e-commerce as plugins); a CI system (job runner core, build steps as plugins); payment orchestration (checkout core, providers as plugins); a shipping engine (this chapter).

ProductCorePlugins
EclipseLauncher and runtimeNearly all features
VS CodeEditor shell, extension hostLanguage support, themes, debuggers
WordPressRequest lifecycle, hooks, data modelPlugins and themes
TerraformGraph walker, state, plan/applyProviders (AWS, Azure, ...)
CaddyConfig loader, module loaderHTTP handlers, TLS issuers, storage
LaravelContainer, kernel, eventsPackages via service providers
ComposerDependency resolverPlugins of type composer-plugin

Plugin contract Must-know ​

In plain words: The contract is the written promise between core and plugin: which functions exist, what they receive, what they return, what errors mean, and which version of the promise this is.

Common misunderstanding: "The contract is the interface." The interface is only the compile-time part. Behavioural rules (timeouts, idempotency, thread safety, who closes what, which errors are retryable) are also contract, and breaking them breaks plugins as surely as renaming a method.

Definition: A contract is the set of types, behaviours and constraints that the core guarantees to plugins within one major version. It has a shape (types), semantics (rules) and a version (identity).

PartExample in our engineWho breaks it
ShapeQuote(ctx, Parcel) ([]Rate, error)A removed or re-typed field
Semantics"Quote must respect ctx deadline; return ErrNotServed for unsupported parcels"A plugin that blocks forever
VersionAPIVersion = 2 in the manifestA core that changes semantics without bumping
Optional capabilitiesInitializer, Closer (Go); optional methodsA core that starts to require them

Go's idiom is a small interface plus optional capability interfaces discovered by type assertion (as io.Closer and http.Flusher are). PHP expresses the same with an interface plus a marker interface or an attribute. Both are shown in the code.

Real scenarios: Terraform splits compatibility into protocol versions: the docs say "Major versions of the protocol delineate Terraform CLI and Terraform Plugin compatibility. Minor versions of the protocol are additive." go-plugin offers "a very basic 'protocol version' ... that can be incremented to invalidate any previous plugins".

Registry Must-know ​

In plain words: The registry is the core's address book of plugins: name, version, state, and the object to call.

Common misunderstanding: "A registry is a global map." The default registry in Go (as in database/sql) is global for convenience, but the registry is also a type you instantiate in tests. A global map that every plugin mutates freely is the first step toward a god registry.

Definition: The registry stores entries keyed by plugin name, validates them at registration (unique name, contract version, required fields), tracks lifecycle state and answers queries such as "active carriers".

Registry flavourWhereWhat it adds
Map in memoryGo shipping.Registry, Caddy module registrySimple, fast, rebuilt at start
Service container tagsLaravel $app->tag([...], 'carriers')Lazy resolution, constructor injection
Manifest-drivenVS Code package.json, Eclipse MANIFEST.MFCore reads metadata without running plugin code
Service registry with callbacksOSGiDynamic: services appear and vanish while running
Database tableSaaS plugin switchboard (see the SQL)Per-tenant enabled flag and settings

Discovery Must-know ​

In plain words: Discovery answers "how does the core find out which plugins exist?"

Common misunderstanding: "Discovery means scanning a directory at runtime." That is one option. Compile-time discovery (Go imports, Caddy), package-manager discovery (Composer, Laravel) and configuration discovery are all common and often safer.

Definition: The mechanism that turns "this plugin is installed" into "this plugin is in the registry".

MethodHow it worksProsConsUsed by
Static registrationPlugin package calls Register in init(); main imports itCompile-time checked, one binaryRebuild to add or removeGo database/sql drivers, Caddy, our plugins.go
Config listA file names the plugins to loadExplicit, reviewableTypos found at startLaravel bootstrap/providers.php, WordPress active plugins
Package-manager metadatacomposer.json extra section read by the frameworkInstall equals discoveryHidden magic; disable needs dont-discoverLaravel package auto-discovery, Composer plugins
Filesystem scanCore lists a directory and loads eachDrop-in feelSecurity and ordering questionsWordPress wp-content/plugins, go-plugin binaries, VS Code extensions folder
Manifest scanRead package.json or plugin.xml without running codeSafe, lazy loading by eventNeeds manifest schemaVS Code, Eclipse
Registry service / marketplaceDownload and verify from a central indexEcosystem, versions, signaturesSupply-chain riskTerraform Registry, VS Code Marketplace

Laravel's package docs state the mechanism: "instead of requiring users to manually add your service provider to the list, you may define the provider in the extra section of your package's composer.json file so that it is automatically loaded by Laravel", and a consumer can opt out through a dont-discover list.

Extension point Must-know ​

In plain words: An extension point is a spot the core deliberately leaves open for plugins.

Common misunderstanding: "More extension points means a better platform." Each one is a promise you must keep for years. A hook name published once is hard to remove, because someone's plugin uses it.

Definition: A named, documented place in the core with a defined input, output and ordering, where plugin code is called.

1. Strategy / driver2. Typed set3. Hooks4. Pipelinepick ONE by nameALL take partnamed points in coreeach wraps the nextcorecorecore: do_action / apply_filtersabcabcactionfilterplugin Aplugin Bplugin CcoreManager.driver("x")Laravel Manager::extendGo database/sql driversCaddy module by nametagged bindingsGo slice of CarrierTerraform providerspriority order:9 before 10 before 11WordPress add_actionadd_filter, VS Code eventsComposer plugin eventsHTTP middlewareCaddy handler chainEnvoy filter chainTyped contract = compiler checks it; hook = flexible but names are strings.
TypeContract styleTypingOrderingFailure handlingExample
Strategy / driverInterface, chosen by nameCompile-timen/a, one winsMissing name is an errorLaravel Manager::extend
Typed setInterface, all calledCompile-timeBy registry order or sortIsolate each pluginOur Engine.Quote
Action hookName plus args, returns nothingRuntime (strings)Priority, then registration orderUsually unhandledWordPress do_action
Filter hookName plus value, returns valueRuntimePriority, then registration orderOne bad filter corrupts the valueWordPress apply_filters
EventTyped event object, listeners reactCompile-time (class)Listener orderSync vs queuedLaravel events
Pipelinehandle(input, next)Compile-timePosition in chainShort-circuit or passHTTP middleware, Envoy filters
Macro / mixinAdd methods to a core classRuntimeLast registration winsName collisionsLaravel Macroable

Hook systems vs typed interfaces Important ​

In plain words: A hook says "something happened here, do what you like"; a typed interface says "implement exactly this method".

Common misunderstanding: "Hooks are the old way and interfaces the new way." They answer different questions. Hooks let many unrelated plugins tweak a flow they were not designed for; interfaces let the core call a capability it requires. WordPress defines the difference: actions "do not return anything back to the calling Action hook", whereas filters "accept a variable, modify it, and return it."

Definition: A hook system is a registry of callbacks keyed by string names, with priorities. A typed extension point is an interface (or class) with a compiler- or analyser-checked signature.

text
     Moment               Hook call                                 Plugin callbacks (priority)
1    request starts       do_action('init')                         A(9), B(10), C(11)  -> run 9, 10, 11
2    price computed       apply_filters('shipping_rate', $rate)     X(10) +50 ; Y(20) x1.1  -> (rate + 50) x 1.1
3    same priority        two callbacks at 11                       run in registration order

WordPress states the ordering rules: the default priority is 10, a callback at 11 runs after one at 10, and "if two callback functions are registered for the same hook with the same priority, they will be run" in registration order.

AspectHooks (WordPress style)Typed interfaces (Go, Laravel contracts)
DiscoverabilityGrep for hook namesCompiler and IDE find implementations
SafetyWrong argument count shows up at runtimeWrong signature does not compile (or fails static analysis)
EvolutionAdd args carefully; names are foreverAdd optional interfaces, bump major for breaking
Cross-plugin interferenceHigh: filters chain on shared valuesLower: each plugin returns its own result
Best forMany small tweaks by unrelated authorsA few well-defined capabilities

Isolation levels Must-know ​

In plain words: Isolation answers "how much damage can one plugin do to the host and to other plugins?"

Common misunderstanding: "Plugins are modular, so they are isolated." Modular code in the same process shares memory, file handles and credentials. A VS Code extension, for example, can read your files because "The extension host has the same permissions as VS Code itself."

Definition: Isolation is the degree of separation of a plugin's memory, failure, resources and privileges from the host.

In-process libraryIn-process WASMSeparate processContainer / microVMhost processplugin codesame memoryhost processwasm moduleown linear memoryhostplugincorepluginhost boxplugin boxcoreplugincrash: host dieslatency: ns (a call)trust: fullGo plugin pkg, PHP, init()crash: trap, host liveslatency: about ustrust: only granted APIswazero, Envoy WASMcrash: host liveslatency: 0.1-1 ms RPCtrust: OS user limitsgo-plugin, Terraform, VS Codecrash: host liveslatency: network hoptrust: cgroups, seccompLambda-style, hosted pluginsIsolation goes up, speed and simplicity go down. Pick the weakest level your trust model allows.
LevelMechanismMemoryFailurePrivilegesCost
0 In-process, no guardDirect callSharedPanic or leak hits hostSame as hostLowest
1 In-process, guardedrecover, timeout, per-plugin goroutine/try-catchSharedPanics contained; leaks and memory corruption notSame as hostLow
2 In-process WASMwazero, Envoy WasmSeparate linear memoryTrap, host continuesOnly imported host functionsMedium (marshalling)
3 Separate processgo-plugin, VS Code extension hostSeparateHost survivesOS user of the plugin processMedium (IPC)
4 Container / microVMDocker, Firecracker, hosted functionsSeparateHost survivescgroups, seccomp, network policyHighest

go-plugin states the benefit of level 3: "Plugins can't crash your host process: A panic in a plugin doesn't panic the plugin user", and "The plugin only has access to the interfaces and args given to it, not to the entire memory space of the process." wazero's pitch for level 2: "WebAssembly is a way to safely run code compiled in other languages."

text
     Choice rule
1    Is the plugin written and reviewed by your team?       yes -> level 0 or 1
2    Written by partners you contract with?                 yes -> level 3 (process) with checksum
3    Written by anyone, runs on your servers, sees tenants? yes -> level 2 (WASM) or 4 (container)
4    Needs the plugin to be in another language?            yes -> level 2 or 3 (gRPC)

Lifecycle Must-know ​

In plain words: A plugin is not just "there or not there"; it is discovered, registered, started, used, maybe paused, and stopped.

Common misunderstanding: "Loading is the same as starting." Loading puts code in memory; starting runs Init after dependencies are ready. OSGi separates INSTALLED, RESOLVED, STARTING and ACTIVE for exactly this reason.

Definition: The ordered states and transitions the core drives on every plugin: register (validate manifest), initialise (dependency order, with config), activate, optionally disable and enable, stop (reverse order), unload (rare).

Discoveredfound on disk/importRegisteredmanifest + API okInitialiseddeps ok, Init doneActivegets callsStoppedClose calledUnloadedgoneFailedisolated, reportedDisabledloaded, not calledInit error / missing depdisableenableUpgrade = stop old version, register new version, init, activate. Unload is rare outside OSGi and hosted runtimes.
text
     Step   Transition              Core action                                Failure policy
1    boot   discovered -> registered  check name, API version                    refuse plugin, report
2    boot   registered -> initialised  topological order by Requires; Init(cfg)  mark Failed, others continue
3    boot   initialised -> active      add to Active() set                        n/a
4    run    active -> disabled         flag off, no unload                        n/a
5    run    disabled -> active         flag on                                    n/a
6    stop   active -> stopped          Close in reverse order, time-boxed         log and continue
7    upgrade stopped(v1) -> active(v2) register new version, Init, switch         keep v1 if v2 fails Init
ConceptVS CodeOSGiGo (ours)Laravel
RegisterRead package.json manifestInstall bundleRegister in init()register() of the provider
Initialiseactivate() on an activation eventstart, BundleActivatorInit(ctx, cfg)boot() of the provider
DisableDisable in UI, reloadstop bundleRegistry.DisableRemove provider, dont-discover
Stopdeactivate()stopClose in reverse orderProcess ends (per request)
Hot unloadExtension host restartSupportedNot for compiled-in pluginsNot applicable

VS Code loads lazily: "VS Code lets extensions declare their Activation Events and loads them lazily. For example, the Markdown extension should only be loaded when a user opens a Markdown file." Composer's plugin API has activate and deactivate methods on PluginInterface.

Dependencies between plugins and versioning Important ​

In plain words: Plugin B needs plugin A, and both need core v2. Someone has to check that before anything runs.

Common misunderstanding: "Semantic versioning of each plugin is enough." Two versions matter: the plugin's own version (for users) and the contract version it targets (for the core). Richards also warns: keep "the communication between plugins to a minimum to avoid dependency issues."

Definition: A plugin manifest declares name, version, contract (API) version and required plugins; the registry refuses mismatches and starts plugins in dependency order.

RuleWhyWhere in our code
Plugin declares APIVersion of the contractCore can refuse incompatible plugins before calling themRegistry.Register
Contract major bumps only on breaking changePlugins pin one majorshipping.APIVersion
Minor/additive changes use optional interfacesOld plugins keep workingInitializer, Closer
Requires lists plugin names; no cyclesDefines init orderRegistry.Init
Prefer plugin-to-core over plugin-to-pluginAvoids dependency websfastbox requires only flat for the demo
Version ranges in package managerComposer and Go modules resolve it for youcomposer.json, go.mod
text
     Check                                   Result in our engine
1    plugin APIVersion 1, host 2             "plugin "old" built for API v1, host speaks v2"
2    duplicate name "ground"                 "plugin "ground" already registered"
3    Requires ["missing"]                    "required plugin "missing" is not registered" -> plugin Failed
4    A requires B, B requires A              "dependency cycle through "a"" -> both Failed

Security of plugins Must-know ​

In plain words: A plugin is someone else's code running with your privileges. Decide whom you trust, what it may touch, and how you know it is the file you expected.

Common misunderstanding: "It is open source, so it is safe." Supply-chain incidents come from compromised maintainers, typosquatted names and malicious updates, not from missing source. VS Code's security page lists "Extension publisher trust" as a user-facing decision for this reason.

Definition: Plugin security is the combination of trust (who wrote it), permission (what it can touch), isolation (what a bug or attack can reach) and provenance (checksums, signatures, review).

ThreatExampleMitigation
Malicious pluginReads tenant data, calls homeSandbox (WASM, container), network policy, no ambient credentials
Compromised updateTrusted plugin ships a bad releasePin versions, checksums, lock files, staged rollout
Typosquattingacme/fastbxo instead of acme/fastboxAllow-list of vendors, review on install
Over-privileged pluginA shipping plugin that can write ordersGive narrow interfaces, not the whole app container
Plugin loads pluginsBug lets an attacker choose the fileFixed plugin directory, verify checksum before exec
Host trustCore accepts any plugin by nameManifest signature, allow-list in config

go-plugin supports "Cryptographically Secure Plugins ... verified with an expected checksum and RPC communications can be configured to use TLS", and says Vault uses it "where dynamic library loading is not acceptable for security reasons". Go's own plugin package warns: "Bugs in applications that load plugins could be exploited by an attacker to load dangerous or untrusted libraries."

Performance Important ​

In plain words: A plugin call costs more than a direct call, and a plugin that starts slowly makes the whole product start slowly.

Common misunderstanding: "The indirection is free." An in-process interface call is nanoseconds; an RPC is hundreds of microseconds to milliseconds; a cold WASM instantiation can be milliseconds. The Mach microkernel story (above) is the classic warning. Richards: the style "does not naturally lend itself to high-performance applications" but "most applications built using the microkernel architecture pattern perform well because you can customize and streamline applications to only include those features you need."

Definition: Performance cost has three parts: call cost (indirection and marshalling), start cost (loading and initialising plugins) and memory cost (each loaded plugin).

CostIn-processWASMRPC processMitigation
Callnsus0.1 to a few msBatch calls, coarse-grained contract, cache
Startinit() costCompile and instantiate moduleFork and handshakeLazy activation (VS Code activation events)
MemoryShared heapOne linear memory per moduleOne process per pluginShare one process for many instances
Failure of slow pluginBlocks unless timeoutFuel or deadlineDeadline over RPCPer-call timeout, as Engine.Timeout

Design rule: make the contract coarse. Quote(parcel) -> rates is one call per carrier; GetBasePrice, GetSurcharge, GetTax would be three round trips for the same answer.

Anti-patterns Important ​

In plain words: The ways a plugin architecture quietly turns back into a tangled monolith.

Common misunderstanding: "We have an interface, so we have a plugin architecture." If plugins also reach into the core's database tables, singletons and private functions, the interface is decoration.

Definition: An anti-pattern here is a structure that keeps the vocabulary of plugins but removes the stability that justified them.

Anti-patternSymptomFix
Plugins reaching into core internalsPlugin imports core/internal or reads core tablesLanguage visibility (internal/), arch tests, narrow facade
God registryOne registry with every service, config and plugin typeOne registry per extension point; no service locator
Plugin dependency hellPlugin A needs B 2.x, plugin C needs B 3.xCore owns shared contracts; plugins avoid each other
Fat contract40 methods per pluginSmall interface plus optional capabilities
Chatty contractMany calls per user actionCoarse-grained operations
Unversioned contract"It worked on the last release"Manifest API version, compatibility tests
Hook soupHundreds of hooks, unknown orderDocument order, limit filters on shared values
Plugin as core forkCustomer edits copy of the coreMove the variation behind an extension point

Details and fixes are in Solving the classic problems.

When to use it Must-know ​

In plain words: Use it where the variation is real, recurring and owned by different people than the core.

Common misunderstanding: "Every system should be extensible." Most business applications have one owner and change in the core; extensibility there is speculation. The YAGNI argument (do not build for needs you do not have) applies.

Definition: A microkernel fits when variation is high and independent, the core is stable, and plugin authors differ from core authors.

SituationFitWhyExample
Product customisation per customerStrongVariation outside the coreRules engine for insurance claims (Richards)
SaaS tenant extensionsStrong with isolationTenants run own logicWebhooks, WASM rules, app marketplaces
IDEs and editorsStrongEcosystem is the productEclipse, VS Code
CMS and e-commerceStrongThird-party ecosystemWordPress, Magento
CI systemsStrongSteps are pluginsJenkins plugins, GitHub Actions as external units
Payment, shipping, notification providersStrongProvider list changes monthlyThis chapter's carriers
Infrastructure toolsStrong with process isolationMany providers, one engineTerraform, Vault, Packer
A CRUD app with one teamWeakNo independent variationUse a modular monolith
Extreme throughput coreWeakIndirection costKeep hot path in core

Mechanics ​

Registration, resolution and start order Must-know ​

The registry in our Go code runs three phases, each of which can reject a plugin without stopping the others.

text
     Phase          Input                          Rule                                         Output / error
1    Register       plugin object                  name unique; APIVersion == host              Registered | error
2    Resolve        Manifest.Requires              depth-first, no cycles, all names present    order | "dependency cycle", "not registered"
3    Init           per-plugin config section      call Init once, in dependency order          Active | Failed(err)
4    Quote (run)    parcel, ctx with deadline      per-call timeout, recover(), merge           rates + failures map
5    Shutdown       none                           Close in reverse registration order          joined errors

Hook execution order Important ​

RuleWordPressOur Go engineOur Laravel engine
Order keyPriority integer, default 10Slice order of FiltersTag resolution order
TiesRegistration ordern/aContainer tag order
Filter return valueRequired, passed onRequired, replacedRequired, passed on
Action return valueIgnoredObserver returns nothingEvent listeners (return ignored)
Error in a callbackFatal unless caughtA panic in a filter is not recovered; filters run in the hostException propagates

A design lesson: filters run in the host's process, so filters are level 0. Anything untrusted must be a carrier at level 2 or 3, not a filter.

The wire contract for out-of-process plugins Important ​

Itemgo-pluginTerraform plugin protocolVS Code
Transportnet/rpc over yamux, or gRPCgRPC (Protocol Buffers)Node IPC to the extension host
HandshakeMagic cookie plus protocol versionProtocol version negotiatedengines.vscode range in manifest
VersioningProtocolVersion integer, planned semantic versionMajor protocol versions (5, 6), additive minorsExtension API versions
LanguageAny language via gRPCAny language via gRPCJavaScript or TypeScript (and web)
VerificationOptional SecureConfig checksumRegistry signatures and provider checksumsMarketplace and publisher trust

The README says go-plugin "is currently only designed to work over a local [reliable] network"; it is for a plugin next to the host, not across a data centre.

Error messages and codes you will actually see Good to know ​

WhereMessage or codeMeaning
Go plugin.Openplugin was built with a different version of package ...Toolchain, build flags or dependency source differ between host and plugin
Go plugin.Openplugin: not implementedPlatform without plugin support (Windows)
go-pluginIncompatible API version with pluginHandshake ProtocolVersion mismatch
go-pluginUnrecognized remote plugin messageBinary ran but is not a go-plugin server (wrong magic cookie)
Caddymodule not registered: http.handlers.fooPlugin not compiled into the binary (use xcaddy)
ComposerPlugin class not found at activationextra.class points to a missing class, or the package is not installed
LaravelDriver [x] not supported. (InvalidArgumentException from Manager)extend('x') was never called or the name is misspelled
LaravelTarget [App\...\Carrier] is not instantiableInterface bound nowhere
WordPressWhite screen after activationA plugin fatal error at load; deactivate by renaming the plugin folder
Our Go engineplugin "old" built for API v1, host speaks v2Contract version refused at Register
Our Go engineplugin panic: ...A plugin panic caught per call

Only the Laravel Manager message was checked against source text we saved. The Go, go-plugin, Caddy and Composer rows are the usual phrasing from memory of those tools, not verbatim specs; search for the product's current message when debugging.

The SQL switchboard for a SaaS Important ​

When tenants choose their own plugins, the registry is partly in the database: the code is installed once, each tenant enables it and keeps its own settings.

sql
-- PostgreSQL: one row per tenant and plugin
CREATE TABLE plugin_installations (
    id          bigserial PRIMARY KEY,
    tenant_id   bigint       NOT NULL,
    plugin      varchar(64)  NOT NULL,
    version     varchar(32)  NOT NULL,
    api_version smallint     NOT NULL,
    enabled     boolean      NOT NULL DEFAULT false,
    settings    jsonb        NOT NULL DEFAULT '{}',
    checksum    char(64),
    UNIQUE (tenant_id, plugin)
);

-- Which carriers does tenant 42 use right now, and are they compatible?
SELECT plugin, version
FROM plugin_installations
WHERE tenant_id = 42 AND enabled AND api_version = 2;

The Laravel migration is database/migrations/2026_11_25_000000_create_plugin_installations_table.php; see Multi-Tenancy Strategies for tenant isolation of the data itself.

Go ​

The running example is a shipping-rate engine. The core (shipping) owns the Carrier contract, the Registry, the Engine and two hook types. Plugins are carriers: two built-in (flat, ground) and one third-party (fastbox). A third-party plugin joins by one blank import; nothing in shipping changes. The module passes gofmt, go vet and go test -race.

The core: contract, registry, engine ​

go
// Package shipping is the core (the "microkernel") of a shipping-rate engine.
// It knows nothing about any concrete carrier; carriers are plugins that
// satisfy the Carrier contract and register themselves.
package shipping

import "context"

// APIVersion is the major version of the plugin contract. A plugin built
// against another major version is refused at registration time.
const APIVersion = 2

// Parcel is the input every carrier receives. Money is integer cents.
type Parcel struct {
	WeightGrams int
	FromCountry string
	ToCountry   string
	ValueCents  int
}

// Rate is one priced shipping option returned by a carrier.
type Rate struct {
	Carrier    string
	Service    string
	PriceCents int
	Days       int
}

// Manifest describes a plugin to the core before any of its code runs.
type Manifest struct {
	Name       string   // unique registry key, e.g. "ground"
	Version    string   // plugin's own semantic version
	APIVersion int      // contract major version the plugin was built for
	Requires   []string // names of other plugins that must be registered
}

// Carrier is the extension-point contract: the only thing the core calls.
type Carrier interface {
	Manifest() Manifest
	Quote(ctx context.Context, p Parcel) ([]Rate, error)
}

// Config is the per-plugin settings map the core hands to Init.
type Config map[string]string

// Initializer is an optional capability: plugins that need settings or
// connections implement it; the registry calls it once, in dependency order.
type Initializer interface {
	Init(ctx context.Context, cfg Config) error
}

// Closer is an optional capability called on shutdown, in reverse order.
type Closer interface {
	Close(ctx context.Context) error
}
go
package shipping

import (
	"context"
	"errors"
	"fmt"
	"sort"
	"sync"
)

// State is a plugin's lifecycle state.
type State int

// Lifecycle states of a registered plugin.
const (
	Registered State = iota
	Active
	Disabled
	Failed
)

func (s State) String() string {
	return [...]string{"registered", "active", "disabled", "failed"}[s]
}

type entry struct {
	carrier Carrier
	state   State
	err     error
}

// Registry holds the plugins. It is the only place that knows which carriers
// exist; the engine asks it for the active ones.
type Registry struct {
	mu      sync.RWMutex
	hostAPI int
	entries map[string]*entry
	order   []string
}

// NewRegistry builds an empty registry for the given contract major version.
func NewRegistry(hostAPI int) *Registry {
	return &Registry{hostAPI: hostAPI, entries: map[string]*entry{}}
}

// Default is the process-wide registry that plugin packages join from init(),
// the same pattern as database/sql drivers and Caddy modules.
var Default = NewRegistry(APIVersion)

// Register is called by plugin packages from init().
func Register(c Carrier) { Default.MustRegister(c) }

// MustRegister panics on a bad registration; init() has nobody to return to.
func (r *Registry) MustRegister(c Carrier) {
	if err := r.Register(c); err != nil {
		panic(err)
	}
}

// Register adds a plugin after checking name, contract version and nil.
func (r *Registry) Register(c Carrier) error {
	if c == nil {
		return errors.New("shipping: Register carrier is nil")
	}
	m := c.Manifest()
	if m.Name == "" {
		return errors.New("shipping: plugin manifest has no name")
	}
	if m.APIVersion != r.hostAPI {
		return fmt.Errorf("shipping: plugin %q built for API v%d, host speaks v%d", m.Name, m.APIVersion, r.hostAPI)
	}
	r.mu.Lock()
	defer r.mu.Unlock()
	if _, dup := r.entries[m.Name]; dup {
		return fmt.Errorf("shipping: plugin %q already registered", m.Name)
	}
	r.entries[m.Name] = &entry{carrier: c, state: Registered}
	r.order = append(r.order, m.Name)
	return nil
}

// Init initialises plugins in dependency order. A failing plugin is marked
// Failed and skipped; the others keep working. The joined error lists them.
func (r *Registry) Init(ctx context.Context, cfg map[string]Config) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	var errs []error
	done := map[string]bool{}
	var visit func(name string, path []string) error
	visit = func(name string, path []string) error {
		e, ok := r.entries[name]
		if !ok {
			return fmt.Errorf("required plugin %q is not registered", name)
		}
		if done[name] {
			return e.err
		}
		for _, p := range path {
			if p == name {
				return fmt.Errorf("dependency cycle through %q", name)
			}
		}
		for _, dep := range e.carrier.Manifest().Requires {
			if err := visit(dep, append(path, name)); err != nil {
				done[name], e.state, e.err = true, Failed, fmt.Errorf("%s: %w", name, err)
				return e.err
			}
		}
		done[name] = true
		if in, ok := e.carrier.(Initializer); ok {
			if err := in.Init(ctx, cfg[name]); err != nil {
				e.state, e.err = Failed, fmt.Errorf("%s: init: %w", name, err)
				return e.err
			}
		}
		e.state = Active
		return nil
	}
	for _, name := range r.order {
		if err := visit(name, nil); err != nil {
			errs = append(errs, err)
		}
	}
	return errors.Join(errs...)
}

// Disable and Enable flip an initialised plugin without unloading code.
func (r *Registry) Disable(name string) error { return r.set(name, Active, Disabled) }

// Enable re-activates a disabled plugin.
func (r *Registry) Enable(name string) error { return r.set(name, Disabled, Active) }

func (r *Registry) set(name string, from, to State) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	e, ok := r.entries[name]
	if !ok {
		return fmt.Errorf("shipping: unknown plugin %q", name)
	}
	if e.state != from {
		return fmt.Errorf("shipping: plugin %q is %s, want %s", name, e.state, from)
	}
	e.state = to
	return nil
}

// Active returns the active carriers sorted by name for stable output.
func (r *Registry) Active() []Carrier {
	r.mu.RLock()
	defer r.mu.RUnlock()
	var out []Carrier
	for _, e := range r.entries {
		if e.state == Active {
			out = append(out, e.carrier)
		}
	}
	sort.Slice(out, func(i, j int) bool { return out[i].Manifest().Name < out[j].Manifest().Name })
	return out
}

// States reports every plugin's state, for an admin page or a health check.
func (r *Registry) States() map[string]State {
	r.mu.RLock()
	defer r.mu.RUnlock()
	out := make(map[string]State, len(r.entries))
	for n, e := range r.entries {
		out[n] = e.state
	}
	return out
}

// Shutdown closes plugins in reverse registration order.
func (r *Registry) Shutdown(ctx context.Context) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	var errs []error
	for i := len(r.order) - 1; i >= 0; i-- {
		e := r.entries[r.order[i]]
		if c, ok := e.carrier.(Closer); ok && (e.state == Active || e.state == Disabled) {
			if err := c.Close(ctx); err != nil {
				errs = append(errs, fmt.Errorf("%s: close: %w", r.order[i], err))
			}
		}
	}
	return errors.Join(errs...)
}
go
package shipping

import (
	"context"
	"fmt"
	"sort"
	"sync"
	"time"
)

// RateFilter is a "filter" hook: it receives the rates and returns the rates
// to use, like a WordPress filter. Order matters; the engine applies them in
// the order they were added.
type RateFilter func(p Parcel, rates []Rate) []Rate

// Observer is an "action" hook: it is told what happened and returns nothing.
type Observer func(carrier string, took time.Duration, err error)

// Result is what the engine returns: the best rates plus who failed and why.
type Result struct {
	Rates    []Rate
	Failures map[string]error
}

// Engine asks every active carrier for rates and merges the answers.
type Engine struct {
	Registry  *Registry
	Timeout   time.Duration
	Filters   []RateFilter
	Observers []Observer
}

// Quote fans out to the active carriers. One slow or panicking plugin costs
// only its own rates: it is cut off by the timeout and recovered.
func (e *Engine) Quote(ctx context.Context, p Parcel) Result {
	carriers := e.Registry.Active()
	res := Result{Failures: map[string]error{}}
	var mu sync.Mutex
	var wg sync.WaitGroup
	for _, c := range carriers {
		wg.Add(1)
		go func() {
			defer wg.Done()
			name := c.Manifest().Name
			start := time.Now()
			rates, err := e.call(ctx, c, p)
			for _, o := range e.Observers {
				o(name, time.Since(start), err)
			}
			mu.Lock()
			defer mu.Unlock()
			if err != nil {
				res.Failures[name] = err
				return
			}
			res.Rates = append(res.Rates, rates...)
		}()
	}
	wg.Wait()
	for _, f := range e.Filters {
		res.Rates = f(p, res.Rates)
	}
	sort.SliceStable(res.Rates, func(i, j int) bool {
		if res.Rates[i].PriceCents != res.Rates[j].PriceCents {
			return res.Rates[i].PriceCents < res.Rates[j].PriceCents
		}
		return res.Rates[i].Carrier < res.Rates[j].Carrier
	})
	return res
}

func (e *Engine) call(ctx context.Context, c Carrier, p Parcel) (rates []Rate, err error) {
	if e.Timeout > 0 {
		var cancel context.CancelFunc
		ctx, cancel = context.WithTimeout(ctx, e.Timeout)
		defer cancel()
	}
	type out struct {
		rates []Rate
		err   error
	}
	ch := make(chan out, 1)
	go func() {
		defer func() {
			if r := recover(); r != nil {
				ch <- out{err: fmt.Errorf("plugin panic: %v", r)}
			}
		}()
		r, err := c.Quote(ctx, p)
		ch <- out{r, err}
	}()
	select {
	case o := <-ch:
		return o.rates, o.err
	case <-ctx.Done():
		return nil, ctx.Err()
	}
}

Plugins: built-in and third-party ​

The built-in plugins use the same door as a third party. init() registers them, exactly as database drivers register with database/sql:

go
// Package flatrate is a built-in plugin: one fixed price, anywhere.
package flatrate

import (
	"context"

	"academy/microkernel-plugin/shipping"
)

func init() { shipping.Register(&Carrier{}) }

// Carrier charges 5.00 for any parcel, 5 days.
type Carrier struct{}

// Manifest implements shipping.Carrier.
func (*Carrier) Manifest() shipping.Manifest {
	return shipping.Manifest{Name: "flat", Version: "1.0.0", APIVersion: shipping.APIVersion}
}

// Quote implements shipping.Carrier.
func (*Carrier) Quote(_ context.Context, _ shipping.Parcel) ([]shipping.Rate, error) {
	return []shipping.Rate{{Carrier: "flat", Service: "standard", PriceCents: 500, Days: 5}}, nil
}
go
// Package ground is a built-in plugin with settings: a price per started kilo.
package ground

import (
	"context"
	"fmt"
	"strconv"

	"academy/microkernel-plugin/shipping"
)

func init() { shipping.Register(&Carrier{}) }

// Carrier charges base + perKg * started kilograms.
type Carrier struct {
	baseCents, perKgCents int
}

// Manifest implements shipping.Carrier.
func (*Carrier) Manifest() shipping.Manifest {
	return shipping.Manifest{Name: "ground", Version: "1.2.0", APIVersion: shipping.APIVersion}
}

// Init reads "base_cents" and "per_kg_cents" from the plugin's config section.
func (c *Carrier) Init(_ context.Context, cfg shipping.Config) error {
	var err error
	if c.baseCents, err = strconv.Atoi(cfg["base_cents"]); err != nil {
		return fmt.Errorf("base_cents: %w", err)
	}
	if c.perKgCents, err = strconv.Atoi(cfg["per_kg_cents"]); err != nil {
		return fmt.Errorf("per_kg_cents: %w", err)
	}
	return nil
}

// Quote implements shipping.Carrier.
func (c *Carrier) Quote(_ context.Context, p shipping.Parcel) ([]shipping.Rate, error) {
	kilos := (p.WeightGrams + 999) / 1000
	return []shipping.Rate{{Carrier: "ground", Service: "ground", PriceCents: c.baseCents + kilos*c.perKgCents, Days: 4}}, nil
}

The third-party plugin lives in another package (in real life another repository). It imports only the public API and declares a dependency on flat:

go
// Package fastbox plays a third-party plugin: it lives outside the core, uses
// only the public shipping API, and joins by being imported.
package fastbox

import (
	"context"
	"errors"

	"academy/microkernel-plugin/shipping"
)

func init() { shipping.Register(&Carrier{}) }

// Carrier offers next-day delivery inside one country, up to 2 kg.
type Carrier struct{}

// Manifest implements shipping.Carrier.
func (*Carrier) Manifest() shipping.Manifest {
	return shipping.Manifest{
		Name: "fastbox", Version: "0.3.1", APIVersion: shipping.APIVersion,
		Requires: []string{"flat"},
	}
}

// ErrNotServed tells the engine this carrier does not serve the parcel.
var ErrNotServed = errors.New("fastbox: parcel not served")

// Quote implements shipping.Carrier.
func (*Carrier) Quote(_ context.Context, p shipping.Parcel) ([]shipping.Rate, error) {
	if p.FromCountry != p.ToCountry || p.WeightGrams > 2000 {
		return nil, ErrNotServed
	}
	return []shipping.Rate{{Carrier: "fastbox", Service: "next-day", PriceCents: 1290, Days: 1}}, nil
}

The composition root ​

plugins.go is the plugin list. Adding or removing a plugin edits this one file; this is the Caddy model (xcaddy generates a main that imports the modules).

go
package main

// The plugin list is the only file that changes when a plugin is added or
// removed. Blank imports run each package's init(), which registers it.
import (
	_ "academy/microkernel-plugin/plugins/flatrate"
	_ "academy/microkernel-plugin/plugins/ground"
	_ "academy/microkernel-plugin/thirdparty/fastbox"
)
go
// Command shipd is the composition root: it wires the registry, the engine
// and the configuration, then prints rates for a sample parcel.
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"academy/microkernel-plugin/shipping"
)

func main() {
	ctx := context.Background()
	cfg := map[string]shipping.Config{
		"ground": {"base_cents": "400", "per_kg_cents": "120"},
	}
	if err := shipping.Default.Init(ctx, cfg); err != nil {
		log.Printf("some plugins failed to start: %v", err)
	}
	defer shipping.Default.Shutdown(ctx) //nolint:errcheck

	eng := &shipping.Engine{Registry: shipping.Default, Timeout: 2 * time.Second}
	res := eng.Quote(ctx, shipping.Parcel{WeightGrams: 1500, FromCountry: "DE", ToCountry: "DE", ValueCents: 8000})
	for _, r := range res.Rates {
		fmt.Printf("%-8s %-9s %6.2f EUR  %d day(s)\n", r.Carrier, r.Service, float64(r.PriceCents)/100, r.Days)
	}
	for name, err := range res.Failures {
		fmt.Printf("skipped  %-8s %v\n", name, err)
	}
}

Tests: the core with stubs, the plugin without the core's source ​

go
package shipping_test

import (
	"context"
	"errors"
	"strings"
	"testing"
	"time"

	"academy/microkernel-plugin/shipping"
)

// stub is a minimal plugin used to test the core without any real carrier.
type stub struct {
	m     shipping.Manifest
	quote func(context.Context, shipping.Parcel) ([]shipping.Rate, error)
	init  error
}

func (s *stub) Manifest() shipping.Manifest { return s.m }
func (s *stub) Quote(ctx context.Context, p shipping.Parcel) ([]shipping.Rate, error) {
	return s.quote(ctx, p)
}
func (s *stub) Init(context.Context, shipping.Config) error { return s.init }

func price(c string, cents int) *stub {
	return &stub{
		m: shipping.Manifest{Name: c, Version: "1.0.0", APIVersion: shipping.APIVersion},
		quote: func(context.Context, shipping.Parcel) ([]shipping.Rate, error) {
			return []shipping.Rate{{Carrier: c, PriceCents: cents}}, nil
		},
	}
}

func TestRegisterRejectsDuplicatesAndWrongAPI(t *testing.T) {
	r := shipping.NewRegistry(shipping.APIVersion)
	if err := r.Register(price("a", 1)); err != nil {
		t.Fatal(err)
	}
	if err := r.Register(price("a", 2)); err == nil || !strings.Contains(err.Error(), "already registered") {
		t.Fatalf("want duplicate error, got %v", err)
	}
	old := price("old", 1)
	old.m.APIVersion = 1
	if err := r.Register(old); err == nil || !strings.Contains(err.Error(), "built for API v1") {
		t.Fatalf("want version error, got %v", err)
	}
}

func TestInitFailureIsolatesOnePlugin(t *testing.T) {
	r := shipping.NewRegistry(shipping.APIVersion)
	bad := price("bad", 1)
	bad.init = errors.New("no credentials")
	_ = r.Register(bad)
	_ = r.Register(price("good", 2))
	if err := r.Init(context.Background(), nil); err == nil {
		t.Fatal("want joined init error")
	}
	st := r.States()
	if st["bad"] != shipping.Failed || st["good"] != shipping.Active {
		t.Fatalf("states = %v", st)
	}
}

func TestRequiresAndCycles(t *testing.T) {
	r := shipping.NewRegistry(shipping.APIVersion)
	a, b := price("a", 1), price("b", 1)
	a.m.Requires = []string{"b"}
	b.m.Requires = []string{"a"}
	c := price("c", 1)
	c.m.Requires = []string{"missing"}
	_ = r.Register(a)
	_ = r.Register(b)
	_ = r.Register(c)
	err := r.Init(context.Background(), nil)
	if err == nil || !strings.Contains(err.Error(), "cycle") || !strings.Contains(err.Error(), "not registered") {
		t.Fatalf("want cycle and missing errors, got %v", err)
	}
	if n := len(r.Active()); n != 0 {
		t.Fatalf("active = %d, want 0", n)
	}
}

func TestEngineIsolatesPanicAndTimeout(t *testing.T) {
	r := shipping.NewRegistry(shipping.APIVersion)
	boom := price("boom", 1)
	boom.quote = func(context.Context, shipping.Parcel) ([]shipping.Rate, error) { panic("bug in plugin") }
	slow := price("slow", 1)
	slow.quote = func(ctx context.Context, _ shipping.Parcel) ([]shipping.Rate, error) {
		<-ctx.Done()
		return nil, ctx.Err()
	}
	for _, c := range []*stub{boom, slow, price("cheap", 300), price("dear", 900)} {
		_ = r.Register(c)
	}
	_ = r.Init(context.Background(), nil)
	e := &shipping.Engine{Registry: r, Timeout: 50 * time.Millisecond}
	res := e.Quote(context.Background(), shipping.Parcel{})
	if len(res.Rates) != 2 || res.Rates[0].Carrier != "cheap" {
		t.Fatalf("rates = %+v", res.Rates)
	}
	if !strings.Contains(res.Failures["boom"].Error(), "plugin panic") {
		t.Fatalf("boom failure = %v", res.Failures["boom"])
	}
	if !errors.Is(res.Failures["slow"], context.DeadlineExceeded) {
		t.Fatalf("slow failure = %v", res.Failures["slow"])
	}
}

func TestDisableEnableAndHooks(t *testing.T) {
	r := shipping.NewRegistry(shipping.APIVersion)
	_ = r.Register(price("a", 100))
	_ = r.Register(price("b", 200))
	_ = r.Init(context.Background(), nil)
	var seen []string
	e := &shipping.Engine{
		Registry: r,
		Filters: []shipping.RateFilter{
			func(_ shipping.Parcel, in []shipping.Rate) []shipping.Rate {
				out := in[:0:0]
				for _, x := range in {
					x.PriceCents += 50 // handling fee added by a filter plugin
					out = append(out, x)
				}
				return out
			},
		},
		Observers: []shipping.Observer{func(c string, _ time.Duration, _ error) { seen = append(seen, c) }},
	}
	if err := r.Disable("a"); err != nil {
		t.Fatal(err)
	}
	res := e.Quote(context.Background(), shipping.Parcel{})
	if len(res.Rates) != 1 || res.Rates[0].PriceCents != 250 || len(seen) != 1 {
		t.Fatalf("rates=%+v seen=%v", res.Rates, seen)
	}
	if err := r.Disable("a"); err == nil {
		t.Fatal("disabling twice must fail")
	}
	_ = r.Enable("a")
	if len(r.Active()) != 2 {
		t.Fatal("enable did not re-activate")
	}
}
go
package fastbox_test

import (
	"context"
	"errors"
	"testing"

	"academy/microkernel-plugin/plugins/flatrate"
	"academy/microkernel-plugin/shipping"
	"academy/microkernel-plugin/thirdparty/fastbox"
)

// The third-party plugin is added to a fresh registry using only the public
// API. No file in package shipping is touched or even imported by name.
func TestFastboxJoinsWithoutChangingCore(t *testing.T) {
	reg := shipping.NewRegistry(shipping.APIVersion)
	for _, c := range []shipping.Carrier{&flatrate.Carrier{}, &fastbox.Carrier{}} {
		if err := reg.Register(c); err != nil {
			t.Fatal(err)
		}
	}
	if err := reg.Init(context.Background(), nil); err != nil {
		t.Fatal(err)
	}
	eng := &shipping.Engine{Registry: reg}
	domestic := eng.Quote(context.Background(), shipping.Parcel{WeightGrams: 900, FromCountry: "DE", ToCountry: "DE"})
	if len(domestic.Rates) != 2 || domestic.Rates[0].Carrier != "flat" || domestic.Rates[1].Service != "next-day" {
		t.Fatalf("domestic = %+v", domestic.Rates)
	}
	abroad := eng.Quote(context.Background(), shipping.Parcel{WeightGrams: 900, FromCountry: "DE", ToCountry: "FR"})
	if len(abroad.Rates) != 1 || !errors.Is(abroad.Failures["fastbox"], fastbox.ErrNotServed) {
		t.Fatalf("abroad = %+v / %v", abroad.Rates, abroad.Failures)
	}
}

func TestFastboxNeedsFlatRegistered(t *testing.T) {
	reg := shipping.NewRegistry(shipping.APIVersion)
	_ = reg.Register(&fastbox.Carrier{})
	if err := reg.Init(context.Background(), nil); err == nil {
		t.Fatal("fastbox requires flat; Init must report it")
	}
	if reg.States()["fastbox"] != shipping.Failed {
		t.Fatal("fastbox must be Failed")
	}
}
go
package main

import (
	"context"
	"testing"

	"academy/microkernel-plugin/shipping"
)

// The blank imports in plugins.go must have registered all three carriers.
func TestAllPluginsRegisteredByImport(t *testing.T) {
	cfg := map[string]shipping.Config{"ground": {"base_cents": "400", "per_kg_cents": "120"}}
	if err := shipping.Default.Init(context.Background(), cfg); err != nil {
		t.Fatal(err)
	}
	if n := len(shipping.Default.Active()); n != 3 {
		t.Fatalf("active plugins = %d, want 3", n)
	}
}

Out of process: the RPC adapter ​

rpcplugin shows the shape of level 3 with only the standard library: the host sees a normal shipping.Carrier, calls cross a connection, the handshake fetches the manifest before any parcel is quoted, and the client honours the caller's deadline. Real products add subprocess launching, a handshake cookie, logging and TLS, which is what go-plugin provides.

go
// Package rpcplugin moves a Carrier out of the host's process. The host sees
// an ordinary shipping.Carrier; calls travel over net/rpc. HashiCorp's
// go-plugin does the same with subprocess launching, handshake and gRPC.
package rpcplugin

import (
	"context"
	"net"
	"net/rpc"

	"academy/microkernel-plugin/shipping"
)

// QuoteArgs and QuoteReply are the wire types; they are the contract.
type QuoteArgs struct{ Parcel shipping.Parcel }

// QuoteReply carries the rates back.
type QuoteReply struct{ Rates []shipping.Rate }

// Server exposes a Carrier as an RPC service named "Carrier".
type Server struct{ Impl shipping.Carrier }

// Manifest is the RPC form of shipping.Carrier.Manifest.
func (s *Server) Manifest(_ struct{}, reply *shipping.Manifest) error {
	*reply = s.Impl.Manifest()
	return nil
}

// Quote is the RPC form of shipping.Carrier.Quote. The context does not
// cross the wire; the client enforces deadlines on its side.
func (s *Server) Quote(args QuoteArgs, reply *QuoteReply) error {
	rates, err := s.Impl.Quote(context.Background(), args.Parcel)
	reply.Rates = rates
	return err
}

// Serve answers RPC calls on one connection until it closes.
func Serve(conn net.Conn, impl shipping.Carrier) error {
	srv := rpc.NewServer()
	if err := srv.RegisterName("Carrier", &Server{Impl: impl}); err != nil {
		return err
	}
	srv.ServeConn(conn)
	return nil
}

// Client adapts an RPC connection back into a shipping.Carrier.
type Client struct {
	rpc      *rpc.Client
	manifest shipping.Manifest
}

// NewClient performs the handshake: it fetches the manifest once, so the
// registry can check the contract version before any parcel is quoted.
func NewClient(conn net.Conn) (*Client, error) {
	c := &Client{rpc: rpc.NewClient(conn)}
	if err := c.rpc.Call("Carrier.Manifest", struct{}{}, &c.manifest); err != nil {
		_ = c.rpc.Close()
		return nil, err
	}
	return c, nil
}

// Manifest implements shipping.Carrier from the cached handshake.
func (c *Client) Manifest() shipping.Manifest { return c.manifest }

// Quote implements shipping.Carrier and honours the caller's deadline.
func (c *Client) Quote(ctx context.Context, p shipping.Parcel) ([]shipping.Rate, error) {
	var reply QuoteReply
	call := c.rpc.Go("Carrier.Quote", QuoteArgs{Parcel: p}, &reply, make(chan *rpc.Call, 1))
	select {
	case <-call.Done:
		return reply.Rates, call.Error
	case <-ctx.Done():
		return nil, ctx.Err()
	}
}

// Close implements shipping.Closer.
func (c *Client) Close(context.Context) error { return c.rpc.Close() }
go
package rpcplugin_test

import (
	"context"
	"net"
	"testing"
	"time"

	"academy/microkernel-plugin/rpcplugin"
	"academy/microkernel-plugin/shipping"
	"academy/microkernel-plugin/thirdparty/fastbox"
)

// net.Pipe stands in for the socket/stdio link to a plugin subprocess.
func TestOutOfProcessCarrierBehavesLikeInProcess(t *testing.T) {
	hostEnd, pluginEnd := net.Pipe()
	go func() { _ = rpcplugin.Serve(pluginEnd, &fastbox.Carrier{}) }()

	client, err := rpcplugin.NewClient(hostEnd)
	if err != nil {
		t.Fatal(err)
	}
	defer client.Close(context.Background()) //nolint:errcheck

	reg := shipping.NewRegistry(shipping.APIVersion)
	if err := reg.Register(client); err != nil { // contract check uses the handshake manifest
		t.Fatal(err)
	}
	if got := client.Manifest().Name; got != "fastbox" {
		t.Fatalf("manifest name = %q", got)
	}
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	rates, err := client.Quote(ctx, shipping.Parcel{WeightGrams: 500, FromCountry: "DE", ToCountry: "DE"})
	if err != nil || len(rates) != 1 || rates[0].Days != 1 {
		t.Fatalf("rates=%v err=%v", rates, err)
	}
	if _, err := client.Quote(ctx, shipping.Parcel{WeightGrams: 500, FromCountry: "DE", ToCountry: "FR"}); err == nil {
		t.Fatal("remote error must cross the wire")
	}
}

The Go angle ​

OptionWhat it isVerdict
Interface + registry + blank importsCompile-time plugins, one binaryThe default choice; used by database/sql drivers and Caddy
Standard plugin packagego build -buildmode=plugin, plugin.OpenRarely chosen; see the limits below
hashicorp/go-pluginSubprocess plus net/rpc or gRPCThe mature level-3 option; Terraform, Vault, Nomad, Packer
WASM with wazeroPure-Go WASM runtime, host functionsLevel 2; sandboxed, language-neutral
gRPC servicePlugin is a network serviceService-scale; see Service Communication

Why most Go projects avoid the plugin package. The package documentation lists the reasons, among them:

"Runtime crashes are likely to occur unless all parts of the program (the application and all its plugins) are compiled using exactly the same version of the toolchain, the same build tags, and the same values of certain flags and environment variables." "Together, these restrictions mean that, in practice, the application and its plugins must all be built together by a single person or component of a system. In that case, it may be simpler for that person or component to generate Go source files that blank-import the desired set of plugins and then compile a static executable in the usual way."

It also notes that plugins are "supported only on Linux, FreeBSD, and macOS", are "poorly supported by the Go race detector", and "cannot be closed". The documented alternative is IPC, "despite the performance overheads". That sentence is the argument for the blank-import model and for go-plugin.

go-plugin sketch (not compiled here; it needs the external module). The host launches the plugin binary, checks a magic cookie and a protocol version, optionally verifies a SHA-256 checksum, then dispenses a Go interface:

go
var handshake = plugin.HandshakeConfig{
	ProtocolVersion:  2,
	MagicCookieKey:   "SHIPPING_PLUGIN",
	MagicCookieValue: "carrier-v2",
}

client := plugin.NewClient(&plugin.ClientConfig{
	HandshakeConfig:  handshake,
	Plugins:          map[string]plugin.Plugin{"carrier": &CarrierPlugin{}},
	Cmd:              exec.Command("./plugins/fastbox"),
	AllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC},
	SecureConfig:     &plugin.SecureConfig{Checksum: sum, Hash: sha256.New()},
})
defer client.Kill()
rpcClient, _ := client.Client()
raw, _ := rpcClient.Dispense("carrier")
carrier := raw.(shipping.Carrier) // a gRPC client behind the interface

wazero sketch (not compiled here). A tenant rule compiled to WASM runs inside the host with its own memory and only the host functions you import:

go
ctx := context.Background()
r := wazero.NewRuntime(ctx)
defer r.Close(ctx)
mod, _ := r.Instantiate(ctx, wasmBytes) // tenant-supplied rule
surcharge, _ := mod.ExportedFunction("surcharge").Call(ctx, uint64(parcel.WeightGrams))

Laravel ​

The same engine in Laravel 13 (PHP 8.4). PHP is not installed on the authoring machine, so the code was reviewed, not run. Files live under docs/snippets/architecture/microkernel-plugin/php.

The core: contract, engine, provider ​

php
<?php

declare(strict_types=1);

namespace App\Shipping\Contracts;

use App\Shipping\Parcel;
use App\Shipping\Rate;

/**
 * The extension-point contract. Plugins implement this and nothing else
 * from the core; the core never imports a concrete carrier.
 */
interface Carrier
{
    /** Major version of this contract. Bump it only for breaking changes. */
    public const API_VERSION = 2;

    /** Unique registry key, e.g. "ground". */
    public function name(): string;

    /** Contract major version the plugin was written for. */
    public function apiVersion(): int;

    /** @return list<Rate> */
    public function quote(Parcel $parcel): array;
}
php
<?php

declare(strict_types=1);

namespace App\Shipping;

final readonly class Parcel
{
    public function __construct(
        public int $weightGrams,
        public string $fromCountry,
        public string $toCountry,
        public int $valueCents = 0,
    ) {}
}
php
<?php

declare(strict_types=1);

namespace App\Shipping;

final readonly class Rate
{
    public function __construct(
        public string $carrier,
        public string $service,
        public int $priceCents,
        public int $days,
    ) {}
}
php
<?php

declare(strict_types=1);

namespace App\Shipping;

use App\Shipping\Contracts\Carrier;
use Closure;
use Illuminate\Container\Attributes\Tag;
use Psr\Log\LoggerInterface;
use Throwable;

/**
 * The core. It receives every carrier tagged "carriers" (the discovery
 * mechanism), refuses wrong contract versions, isolates failures, and runs
 * the tagged "rate-filters" in order (the filter hook).
 */
final class RateEngine
{
    /**
     * @param  iterable<Carrier>  $carriers
     * @param  iterable<Closure(list<Rate>, Parcel): list<Rate>>  $filters
     */
    public function __construct(
        #[Tag('carriers')] private readonly iterable $carriers,
        #[Tag('rate-filters')] private readonly iterable $filters,
        private readonly LoggerInterface $log,
    ) {}

    /** @return array{rates: list<Rate>, failures: array<string, string>} */
    public function quote(Parcel $parcel): array
    {
        $rates = [];
        $failures = [];
        $seen = [];

        foreach ($this->carriers as $carrier) {
            $name = $carrier->name();

            if ($carrier->apiVersion() !== Carrier::API_VERSION) {
                $failures[$name] = "built for API v{$carrier->apiVersion()}, host speaks v".Carrier::API_VERSION;
                continue;
            }
            if (isset($seen[$name])) {
                $failures[$name] = 'duplicate carrier name';
                continue;
            }
            $seen[$name] = true;

            try {
                array_push($rates, ...$carrier->quote($parcel));
            } catch (Throwable $e) {
                // One broken plugin must not take the checkout down.
                $this->log->warning('carrier failed', ['carrier' => $name, 'error' => $e->getMessage()]);
                $failures[$name] = $e->getMessage();
            }
        }

        foreach ($this->filters as $filter) {
            $rates = $filter($rates, $parcel);
        }

        usort($rates, fn (Rate $a, Rate $b) => [$a->priceCents, $a->carrier] <=> [$b->priceCents, $b->carrier]);

        return ['rates' => $rates, 'failures' => $failures];
    }
}
php
<?php

declare(strict_types=1);

namespace App\Providers;

use App\Shipping\CarrierManager;
use App\Shipping\Carriers\FlatRateCarrier;
use App\Shipping\Carriers\GroundCarrier;
use App\Shipping\Parcel;
use App\Shipping\Rate;
use Illuminate\Support\ServiceProvider;

/**
 * Core wiring. List it in bootstrap/providers.php. Plugins never edit this
 * file: they ship their own provider that tags more carriers.
 */
final class ShippingServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->mergeConfigFrom(__DIR__.'/../../config/shipping.php', 'shipping');

        $this->app->singleton(CarrierManager::class, fn ($app) => new CarrierManager($app));

        // Built-in plugins join through the same door a third party will use.
        $this->app->bind(FlatRateCarrier::class, fn ($app) => new FlatRateCarrier(
            (int) $app['config']->get('shipping.carriers.flat.price_cents', 500),
        ));
        $this->app->bind(GroundCarrier::class, fn ($app) => new GroundCarrier(
            (int) $app['config']->get('shipping.carriers.ground.base_cents', 400),
            (int) $app['config']->get('shipping.carriers.ground.per_kg_cents', 120),
        ));
        $this->app->tag([FlatRateCarrier::class, GroundCarrier::class], 'carriers');

        // A filter hook with a default of "no change" so tag() is never empty.
        $this->app->bind('shipping.filter.identity', fn () => fn (array $rates, Parcel $p): array => $rates);
        $this->app->tag(['shipping.filter.identity'], 'rate-filters');
    }
}
php
<?php

return [
    // Driver chosen by CarrierManager::driver() when no name is given.
    'default' => env('SHIPPING_DEFAULT', 'flat'),

    'carriers' => [
        'flat' => ['price_cents' => 500],
        'ground' => ['base_cents' => 400, 'per_kg_cents' => 120],
    ],
];

Built-in plugins ​

php
<?php

declare(strict_types=1);

namespace App\Shipping\Carriers;

use App\Shipping\Contracts\Carrier;
use App\Shipping\Parcel;
use App\Shipping\Rate;

/** Built-in plugin: one price for everything. */
final class FlatRateCarrier implements Carrier
{
    public function __construct(private readonly int $priceCents = 500) {}

    public function name(): string
    {
        return 'flat';
    }

    public function apiVersion(): int
    {
        return Carrier::API_VERSION;
    }

    public function quote(Parcel $parcel): array
    {
        return [new Rate('flat', 'standard', $this->priceCents, 5)];
    }
}
php
<?php

declare(strict_types=1);

namespace App\Shipping\Carriers;

use App\Shipping\Contracts\Carrier;
use App\Shipping\Parcel;
use App\Shipping\Rate;

/** Built-in plugin with settings: base price plus a price per started kilo. */
final class GroundCarrier implements Carrier
{
    public function __construct(
        private readonly int $baseCents,
        private readonly int $perKgCents,
    ) {}

    public function name(): string
    {
        return 'ground';
    }

    public function apiVersion(): int
    {
        return Carrier::API_VERSION;
    }

    public function quote(Parcel $parcel): array
    {
        $kilos = intdiv($parcel->weightGrams + 999, 1000);

        return [new Rate('ground', 'ground', $this->baseCents + $kilos * $this->perKgCents, 4)];
    }
}

Manager and extend: one implementation, chosen by name ​

php
<?php

declare(strict_types=1);

namespace App\Shipping;

use App\Shipping\Carriers\FlatRateCarrier;
use App\Shipping\Carriers\GroundCarrier;
use App\Shipping\Contracts\Carrier;
use Illuminate\Support\Manager;

/**
 * The Manager/driver pattern Laravel uses for cache, mail and queue:
 * built-ins are createXDriver() methods; third parties call extend().
 * Use it when ONE implementation is chosen by name; use tagged bindings
 * (RateEngine) when ALL implementations take part.
 */
final class CarrierManager extends Manager
{
    public function getDefaultDriver(): string
    {
        return $this->config->get('shipping.default', 'flat');
    }

    protected function createFlatDriver(): Carrier
    {
        return new FlatRateCarrier((int) $this->config->get('shipping.carriers.flat.price_cents', 500));
    }

    protected function createGroundDriver(): Carrier
    {
        return new GroundCarrier(
            (int) $this->config->get('shipping.carriers.ground.base_cents', 400),
            (int) $this->config->get('shipping.carriers.ground.per_kg_cents', 120),
        );
    }
}

Illuminate\Support\Manager keeps a customCreators array; extend($driver, Closure $callback) stores a creator and driver($name) calls createXDriver() for built-ins or the custom creator otherwise (we read Manager.php in the 13.x branch). A third-party package selects its driver in its provider's boot():

php
$this->app->make(CarrierManager::class)->extend('fastbox', fn ($app) => new FastboxCarrier());

A third-party package: discovered, no core edit ​

The package carries its own provider and lists it in composer.json. Installing it with Composer is the whole installation:

json
{
    "name": "acme/fastbox",
    "description": "Next-day domestic carrier plugin for the shipping engine",
    "type": "library",
    "require": {
        "php": "^8.4",
        "illuminate/support": "^13.0"
    },
    "autoload": {
        "psr-4": { "Acme\\Fastbox\\": "src/" }
    },
    "extra": {
        "laravel": {
            "providers": ["Acme\\Fastbox\\FastboxServiceProvider"]
        }
    }
}
php
<?php

declare(strict_types=1);

namespace Acme\Fastbox;

use App\Shipping\Contracts\Carrier;
use App\Shipping\Parcel;
use App\Shipping\Rate;
use RuntimeException;

/** Third-party plugin: depends on the contract, never on core internals. */
final class FastboxCarrier implements Carrier
{
    public function name(): string
    {
        return 'fastbox';
    }

    public function apiVersion(): int
    {
        return 2;
    }

    public function quote(Parcel $parcel): array
    {
        if ($parcel->fromCountry !== $parcel->toCountry || $parcel->weightGrams > 2000) {
            throw new RuntimeException('fastbox: parcel not served');
        }

        return [new Rate('fastbox', 'next-day', 1290, 1)];
    }
}
php
<?php

declare(strict_types=1);

namespace Acme\Fastbox;

use Illuminate\Support\ServiceProvider;

/**
 * Discovered through composer.json "extra.laravel.providers"; the core's
 * files are not edited. Tagging is the entire integration.
 */
final class FastboxServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->tag([FastboxCarrier::class], 'carriers');
    }
}

Macros, the lightest hook ​

php
<?php

declare(strict_types=1);

namespace App\Shipping;

use Illuminate\Support\Traits\Macroable;

/**
 * Macroable is Laravel's lightest extension point: a class using the trait
 * accepts new methods at runtime via ::macro(). Powerful and untyped; keep
 * it for conveniences, not for contracts.
 */
final class Shipments
{
    use Macroable;

    public function __construct(public readonly Parcel $parcel) {}
}

// In some plugin's provider boot():
//   Shipments::macro('isHeavy', fn (): bool => $this->parcel->weightGrams > 20000);
//   (new Shipments($parcel))->isHeavy();

Tenant switchboard migration ​

php
<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

// Per-tenant plugin switchboard for a SaaS: the code is installed once,
// each tenant enables it and keeps its own settings.
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('plugin_installations', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->index();
            $table->string('plugin', 64);
            $table->string('version', 32);
            $table->unsignedSmallInteger('api_version');
            $table->boolean('enabled')->default(false);
            $table->json('settings')->nullable();
            $table->char('checksum', 64)->nullable();
            $table->timestamps();
            $table->unique(['tenant_id', 'plugin']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('plugin_installations');
    }
};

Tests and architecture rules ​

php
<?php

declare(strict_types=1);

namespace Tests;

use App\Providers\ShippingServiceProvider;
use Orchestra\Testbench\TestCase as Testbench;

abstract class TestCase extends Testbench
{
    protected function getPackageProviders($app): array
    {
        return [ShippingServiceProvider::class];
    }
}
php
<?php

declare(strict_types=1);

use Acme\Fastbox\FastboxCarrier;
use App\Shipping\Contracts\Carrier;
use App\Shipping\Parcel;
use App\Shipping\Rate;
use App\Shipping\RateEngine;

// Tests\TestCase extends Orchestra Testbench and lists the providers: the
// "plugin list" of the test application.
uses(Tests\TestCase::class);

it('quotes with the built-in carriers', function () {
    $result = app(RateEngine::class)->quote(new Parcel(1500, 'DE', 'DE'));

    expect(array_map(fn (Rate $r) => $r->carrier, $result['rates']))->toBe(['flat', 'ground']);
    expect($result['failures'])->toBe([]);
});

it('accepts a third-party plugin by tagging it, without touching core', function () {
    $this->app->tag([FastboxCarrier::class], 'carriers'); // what FastboxServiceProvider does

    $result = app(RateEngine::class)->quote(new Parcel(900, 'DE', 'DE'));

    expect(array_map(fn (Rate $r) => $r->carrier, $result['rates']))->toContain('fastbox');
});

it('isolates a failing plugin', function () {
    $this->app->tag([FastboxCarrier::class], 'carriers');

    $result = app(RateEngine::class)->quote(new Parcel(900, 'DE', 'FR'));

    expect($result['failures'])->toHaveKey('fastbox');
    expect($result['rates'])->not->toBeEmpty(); // flat and ground still answer
});

it('refuses a plugin built for another contract version', function () {
    $old = new class implements Carrier {
        public function name(): string { return 'legacy'; }
        public function apiVersion(): int { return 1; }
        public function quote(Parcel $parcel): array { return []; }
    };
    $this->app->instance('legacy.carrier', $old);
    $this->app->tag(['legacy.carrier'], 'carriers');

    $result = app(RateEngine::class)->quote(new Parcel(900, 'DE', 'DE'));

    expect($result['failures']['legacy'])->toContain('built for API v1');
});

it('applies filter hooks in order', function () {
    $this->app->bind('handling.fee', fn () => fn (array $rates, Parcel $p): array => array_map(
        fn (Rate $r) => new Rate($r->carrier, $r->service, $r->priceCents + 50, $r->days),
        $rates,
    ));
    $this->app->tag(['handling.fee'], 'rate-filters');

    $result = app(RateEngine::class)->quote(new Parcel(1000, 'DE', 'DE'));

    expect($result['rates'][0]->priceCents)->toBe(550);
});
php
<?php

declare(strict_types=1);

// Pest architecture tests keep the core free of concrete plugins and
// keep plugins on the public contract.
arch('the core does not know any plugin')
    ->expect('App\Shipping\RateEngine')
    ->not->toUse(['Acme\Fastbox', 'App\Shipping\Carriers']);

arch('plugins depend on the contract, not on the engine')
    ->expect('Acme\Fastbox')
    ->not->toUse('App\Shipping\RateEngine');

arch('carriers implement the contract')
    ->expect('App\Shipping\Carriers')
    ->toImplement('App\Shipping\Contracts\Carrier');

The Laravel angle ​

Laravel featurePlugin roleNotes
Service providerThe plugin's entry pointregister() binds, boot() runs after all providers are registered
bootstrap/providers.phpThe explicit plugin listLaravel 13 provider docs describe it as the list of providers to load
Package auto-discoveryInstall equals discoveryextra.laravel.providers in composer.json; consumers opt out with dont-discover
Contracts (interfaces)The plugin contractThe container binds interface to implementation
tag() and #[Tag('x')]Typed-set extension pointContainer docs show tagged injection; the attribute is listed among the container attributes
Manager and extendStrategy extension pointUsed by cache, mail, queue managers; extend registers a custom creator
Events and listenersAction hookEvent::listen, subscribers; sync or queued
MacroableMixin extension pointmacro('name', closure) adds methods at runtime
Pest pluginsTest-tool pluginsPest documents a plugin system for extending the test runner
Composer pluginsBuild-tool pluginstype: composer-plugin, class implements PluginInterface, activate() receives Composer and IOInterface
PintCode formatterNot read for this chapter; treat it as a tool you configure, not as a documented plugin API

One subtlety of the Laravel model: PHP-FPM boots the application per request, so every request pays for all providers' register() and boot(). Package discovery keeps start-up cheap by caching the discovered provider list in a file (php artisan package:discover, which runs after Composer updates), but heavy boot() methods in plugins slow every request, which is the same lazy-activation lesson as VS Code. Under Octane, providers boot once per worker, so a plugin that stores request state in a singleton leaks between requests.

Solving the classic problems ​

Plugins reaching into core internals ​

SolutionHowAdvantageCost or limitation
Language visibilityGo internal/; PHP final classes and a separate Api namespaceThe compiler or analyser refusesPHP has no hard package privacy
Narrow facadeGive plugins a small HostAPI interface, not the containerPlugin can only do what the facade allowsMore design work
Architecture testsPest arch(); Go test that parses importsFails in CIOnly checks what you wrote down
Process boundaryMove the plugin out of processReach is impossible, not just forbiddenCost of IPC
text
     Rule enforced by test                                         Tool
1    core RateEngine must not use plugins or Carriers namespace    Pest arch()->expect(...)->not->toUse(...)
2    plugin package must not import core internal packages         Go: package internal/ + go vet in CI
3    carriers implement the contract                               Pest toImplement(...)

The architecture tests in tests/ArchitectureTest.php are the PHP version; in Go the internal/ rule gives the same enforcement for free (see Software Architecture vs Software Design for the fitness-test idea).

God registry ​

Symptom: one global registry holds carriers, filters, config, HTTP clients and the database; every plugin calls Registry.Get("anything"). This is a service locator with a plugin label.

Fix: one registry per extension point, typed (Registry[Carrier] or a tagged binding per interface), and constructor injection for everything else. The plugin receives what it needs through its Init(cfg) or constructor; it does not look things up.

Plugin dependency hell ​

CauseFix
Plugin A needs library X 1.x, plugin B needs X 2.x, both in one processProcess isolation (each plugin its own dependencies) or WASM; OSGi allows "multiple versions of the same library being used in a single VM"
Plugin A requires plugin BAllow it only through Requires in the manifest, resolve in order, forbid cycles
Core upgrade breaks pluginsContract major version; keep the old major for a deprecation period; run plugin compatibility tests in core CI
Everyone depends on everyoneMove the shared piece into the core contract

Lost state on upgrade ​

Problem: replacing a plugin version while the system runs drops in-flight work. Fix: (1) register the new version under a new name or version key; (2) initialise it; (3) switch the active pointer atomically; (4) drain and close the old version. The Go registry above switches by state; a production version would also keep both versions during the switch and release the old one after in-flight calls finish.

A slow or failing plugin ​

TechniqueWhere
Per-call timeout via contextEngine.Timeout, ctx.Done()
recover() around plugin callsEngine.call
Failure map returned to the callerResult.Failures
Circuit breaker per pluginAdd after repeated failures; see Circuit Breaker
Bulkhead: separate worker pool per pluginPrevents one plugin using all goroutines or threads
FallbackReturn a cached rate or a flat rate when a carrier fails

PHP has no goroutines, so a hung plugin in PHP-FPM holds a worker until max_execution_time or the HTTP client's timeout; set client timeouts in every plugin that calls the network.

Choosing: how to select style, extension point and isolation ​

Style decision ​

SituationPickReason
One team, one product, rare variationLayered or modular monolithContract overhead not repaid
Product with many integrations of one kind (carriers, gateways, exporters)Microkernel with typed setProviders change often, core does not
Product where customers need own logic, unknown at build timeMicrokernel with WASM or webhooksIsolation is required
Ecosystem product (CMS, IDE)Microkernel with hooks plus manifestsThousands of authors
Many teams shipping separate servicesMicroservices with extension points in the gatewayTeams deploy separately

Extension-point decision ​

You needUseExample
Exactly one implementation per settingStrategy / driver (Manager)Cache store
All implementations contributeTyped setCarriers
Observe or tweak a value in many placesHook (filter)Rate surcharge
Order-dependent processingPipelineAuth then rate limit
Add a convenience methodMacroCollection::macro
React to a factEventRatesQuoted

Isolation decision ​

Trust and needLevelMechanism
Team code, same repo0 or 1Interfaces, recover, timeouts
Contractor or partner code, reviewed3go-plugin, RPC, checksum
Tenant or public code on your servers2 or 4WASM (wazero, Envoy Wasm), containers
Different language required2 or 3WASM or gRPC
Latency under 1 ms per call0, 1 or 2Avoid RPC

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

Everyday example: the shipping engine of a small shop. Carriers are Go packages registered with init() or Laravel providers tagged carriers. One process, one database, one deploy. Adding a carrier means adding a package and one import or Composer require; the core is unchanged. Isolation is level 0 or 1: trust the code, add timeouts and recover.

text
     Request                                   Where it runs
1    POST /checkout                            Laravel / Go handler
2    RateEngine.quote(parcel)                  same process
3    each carrier.quote(parcel)                same process, in-process call
4    merge, filter, sort                       same process
5    response                                  one transaction boundary for the order

Modular monolith and multiple databases ​

Plugins and modules are different tools. A modular monolith splits the domain into modules with public APIs; a microkernel splits variation behind a contract. They compose: the Shipping module of a modular monolith can itself be a microkernel whose carriers are plugins, with the Shipping\Contracts namespace as the module's public API. The rule from the modular monolith applies unchanged: other modules call the module's facade, never a carrier.

Per-module databases make the plugin question sharper: a carrier plugin must not write to the orders tables. Give it a read-only Parcel DTO and return Rate objects; persistence stays in the core.

Microservices: boundary with a network ​

Production example (HashiCorp tooling, from the go-plugin README): Terraform, Vault, Nomad, Boundary and Waypoint use out-of-process plugins; the host talks to each over a local RPC link.

At service scale there are three common shapes:

ShapeWhat the plugin isIsolationExamples
Gateway with plugin filtersA filter in the proxy's chainIn-process (Lua, Go, WASM)Envoy HTTP filters, Kong plugins, Traefik middleware, Caddy modules
Sidecar extensionA separate process next to the serviceProcessEnvoy external processing, service mesh sidecars
Plugin as a serviceThe plugin is a remote service the core callsNetworkPayment orchestration calling provider adapters, webhooks
ClientGateway / proxy = the core (Envoy, Kong, Traefik, Caddy)authnrate limitWASM filtertenant rulessidecar / ext_procseparate processfilter chain = pipeline extension point; config pushed by a control planein-process filters: fast, share fate | WASM: sandboxed | sidecar: isolated, network hopUpstreamThe same shape as a single-process microkernel; the contract is now a filter API or a wire protocol.The registry becomes configuration (routes, plugin lists) delivered by a control plane.New risk: a bad plugin config can break every route at once, so roll out per route or per tenant.

Envoy documents the WASM option: "The HTTP Wasm filter is used to implement an HTTP filter with a Wasm plugin", and flags that it "is experimental and is currently under active development". Treat any "Envoy plugin" decision as one that needs a current-docs check. Gateways themselves are covered in API Gateway, BFF and Service Mesh.

text
     Request path with an Envoy WASM filter
1    client -> Envoy listener
2    authn filter (built-in)
3    rate-limit filter (built-in)
4    WASM filter (tenant rule): sees headers, may deny or tag
5    router -> upstream service

Across a network the contract becomes a protocol (gRPC schema, HTTP API, webhook payload). Everything in Service Communication applies: timeouts, retries with idempotency, versioned schemas. A webhook is the cheapest plugin protocol for tenant customisation: the core POSTs an event and uses the answer.

Distributed data: replicas, caches and shared state ​

ConcernWhat happens with pluginsHandling
Plugin list per nodeNodes run different plugin versions during a rolloutContract versions allow mixed fleets; roll out per node group
Plugin config in a databaseRead replica lag shows stale enabled flagsRead the switchboard from the primary or cache with a short TTL and accept the lag
Cached resultsA cached rate survives disabling its carrierKey the cache by plugin version and enabled set; evict on disable
Shared state between instancesPlugin keeps local countersPut shared state in Redis or the DB, not in plugin memory
Multi-regionA plugin that calls a regional APIPer-region configuration; plugin gets the region in its config

Scaling path: 1×, 10×, 100× ​

LoadDesignPlugins
1x: a shop with 3 carriersOne binary or Laravel appIn-process, init() or tagged providers
10x: many tenants, own settingsSwitchboard table, per-tenant enabled set, per-call timeouts and breakersStill in-process, tenant-specific configuration
100x: tenants bring codeWASM or process isolation, quota per plugin, plugin marketplace with review and signaturesLevel 2 or 3, plugin metrics per tenant
BeyondPlugin as a service with its own SLONetwork contracts, see SLAs, SLOs, SLIs

Lab: add a third-party carrier without touching the core ​

Everything runs offline. Go is required; Laravel steps are optional.

Setup.

bash
cd docs/snippets/architecture/microkernel-plugin/go
gofmt -l . && go vet ./... && go test -race ./...
go run ./cmd/shipd
# flat     standard    5.00 EUR  5 day(s)
# ground   ground      6.40 EUR  4 day(s)
# fastbox  next-day   12.90 EUR  1 day(s)

Step 1: remove a plugin. Delete the fastbox line from cmd/shipd/plugins.go and run again. Expected: the third line disappears; shipping/ is untouched. fastbox is gone because nothing imports it, so its init() never ran.

Step 2: add it back without touching the core. Restore the line. Run git diff --stat -- shipping/. Expected: empty, which proves the core did not change.

Step 3: break the contract version. In fastbox.go set APIVersion: 1. Run go run ./cmd/shipd. Expected: the program panics at start with plugin "fastbox" built for API v1, host speaks v2, because init() uses MustRegister. Discuss: is a panic at start the right response for a plugin compiled into your binary? (Yes for a compile-time plugin: the build is wrong. For a user-installed plugin, refuse and continue.) Revert.

Step 4: isolate a failing plugin. Make Quote of fastbox call panic("bug"). Run go test ./thirdparty/fastbox: the domestic test fails because fastbox answers with plugin panic: bug in Failures. Run go run ./cmd/shipd: the other two carriers still print, and skipped fastbox plugin panic: bug appears. Revert.

Step 5: a missing dependency. Remove the flatrate import from plugins.go. Run go run ./cmd/shipd. Expected: some plugins failed to start: fastbox: required plugin "flat" is not registered and the remaining plugins work.

Step 6: go out of process. Run go test -v ./rpcplugin. Read the test: net.Pipe stands in for a socket to a subprocess, the client fetches the manifest during the handshake, Quote crosses the connection and the remote ErrNotServed comes back as an error. Expected: PASS. Then measure the cost: add a benchmark that calls Quote 100,000 times in-process and over rpcplugin; expect the RPC to be one to two orders of magnitude slower.

MeasureIn-process carrierRPC carrier
Call cost (your benchmark)measuremeasure
Crash of the pluginHost panics unless recoverHost gets an error
Memory sharedYesNo
Third-party can read host memoryYesNo

Step 7 (Laravel, optional). In a Laravel 13 project with Orchestra Testbench and Pest, copy the php/ files, add App\Providers\ShippingServiceProvider::class to bootstrap/providers.php, require the local package acme/fastbox through a Composer path repository, and run ./vendor/bin/pest. Expected: five engine tests and three architecture tests pass; removing the package leaves the first test passing. Add use Acme\Fastbox\FastboxCarrier; to RateEngine.php and the first arch test fails.

Common misconceptions ​

BeliefReality
A plugin system means loading .so or .jar files at runtimeDiscovery can be compile-time (Go imports, Caddy) or package-manager based (Composer)
Go's plugin package is the Go way to do pluginsThe package's own docs list heavy limits and suggest IPC or generated imports; go-plugin and blank imports dominate
Microkernel and microservices are the same thingOne deployable with in-process plugins versus many deployables; they combine but are different decisions
An interface is enough of a contractSemantics, timeouts, errors and the version are also contract
Plugins are isolated because they are separate packagesSame process means shared memory and privileges
WordPress hooks are bad designThey are an untyped but very successful public API; the cost is discoverability and ordering
The core should be as small as possibleThe core should be stable; a rich but stable core is fine
More extension points is betterEach is a long-term promise; add them where variation is proven
Hot-unloading plugins is a normal featureIt is hard (OSGi supports it; Go compiled-in plugins and plugin cannot)
Open-source plugins need no security reviewSupply-chain and update risks remain
A registry is a global singletonIt is a type; a default instance is a convenience that tests should bypass
Microkernel scales wellRichards rates scalability low because most implementations are single units

Cheat sheet ​

TopicWhat to remember
ShapeStable core + versioned contract + registry + plugins
Direction of dependencyPlugins depend on the contract; the core depends on no plugin
DiscoveryStatic import, config list, package metadata, filesystem scan, manifest scan
Extension pointsStrategy (one), typed set (all), hook (tweak), pipeline (ordered), macro (mixin)
Hooks vs interfacesHooks: flexible, string-named; interfaces: checked, discoverable
Isolation ladderIn-process, WASM, process (RPC/gRPC), container
LifecycleRegister, resolve, init, active, disabled, stop, unload
VersioningPlugin version for users; contract major for the core; additive changes through optional interfaces
SecurityTrust, permissions, isolation, checksums; never "same privileges as the host" by accident
PerformanceCoarse contract, lazy activation, per-call timeout
GoInterface + registry + blank imports; go-plugin for processes; wazero for sandboxes; avoid plugin unless one builder controls everything
LaravelContract + service provider + tag(); Manager and extend for one-of; package auto-discovery via extra.laravel.providers
Anti-patternsReaching into internals, god registry, dependency hell, fat or chatty contract
Service scaleGateway filters, sidecars, WASM filters, webhooks
TestCore with stub plugins; each plugin against the contract; arch tests

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What are the two kinds of components in a microkernel architecture, and which one may depend on the other? Must-know ​

Answer

Answer: A core system and plugin modules. Plugins depend on the core's contract; the core depends on no concrete plugin. See Core system and plugins.

2 — Name four discovery methods and one product for each. Good to know ​

Answer

Answer: Static registration (Go database/sql, Caddy), config list (Laravel bootstrap/providers.php), package metadata (Composer extra.laravel), filesystem or manifest scan (WordPress plugins folder, VS Code). See Discovery.

3 — When would you choose a Laravel Manager with extend over tagged bindings? Important ​

Answer

Answer: When exactly one implementation is selected by name (cache store, mail transport). Tagged bindings are for typed sets where all implementations take part, like carriers.

4 — What is the difference between a WordPress action and a filter? Must-know ​

Answer

Answer: An action reacts and returns nothing; a filter receives a value, changes it and must return it. Both are ordered by priority (default 10), then by registration order.

5 — Why do many Go projects avoid the standard plugin package? Important ​

Answer

Answer: The host and plugins must be built with the same toolchain, flags and dependency sources; plugins cannot be closed; platform support is limited; and the docs suggest generated blank imports or IPC instead.

6 — What does go-plugin give you that blank imports do not? Important ​

Answer

Answer: Process isolation (a plugin panic does not crash the host), language neutrality via gRPC, a handshake and protocol version, optional checksum and TLS.

7 — Which isolation level would you use for code written by your tenants, and why? Must-know ​

Answer

Answer: WASM (in-process sandbox with granted host functions) or a container or microVM, because the code is untrusted and must not share memory or privileges. See Isolation levels.

8 — List the lifecycle states and say which failure must not stop the others. Important ​

Answer

Answer: Discovered, registered, initialised, active, disabled, stopped, unloaded. An init failure of one plugin marks it Failed and the others continue.

9 — What two versions matter for a plugin, and what do they protect? Important ​

Answer

Answer: The plugin's own version (user-facing) and the contract (API) major version it targets (core compatibility). The registry refuses a contract mismatch before calling the plugin.

10 — Name three anti-patterns and the fix for each. Important ​

Answer

Answer: Plugins reaching into internals (visibility rules, facade, arch tests); god registry (one typed registry per extension point); dependency hell (core owns shared contracts, isolation, Requires).

11 — Why is the extension point of our engine "typed set" and not a hook? Good to know ​

Answer

Answer: Every carrier must contribute rates through a checked signature; a hook would pass untyped values and could not report per-plugin failures cleanly.

12 — How does a microkernel look at service scale? Good to know ​

Answer

Answer: A gateway or proxy is the core; filters, sidecars or WASM modules are plugins; the registry is configuration pushed by a control plane; the contract is a filter API or protocol.

Glossary ​

TermMeaning
MicrokernelA small core providing minimal services, with features outside it; the name comes from operating systems
Core systemThe stable part of a plugin architecture that owns the contract, registry and lifecycle
Plugin / plug-inA component that extends a system through its contract without rebuilding the core
Add-on, extensionSynonyms for plugin in different ecosystems (Wikipedia lists plug-in, add-in, add-on, extension)
Plugin contractShape, semantics and version of the interface between core and plugin
ManifestMetadata (name, version, API version, requires) read before plugin code runs
RegistryThe core's collection of plugins, their state and lookup
Service locatorA registry that hands out arbitrary services by name; a smell when it becomes the god registry
DiscoveryHow the registry learns which plugins exist
Extension pointA named, documented place where plugin code is called
Strategy / driverAn extension point where one implementation is chosen by name
Typed setAn extension point that calls all implementations of an interface
HookA named point where callbacks run; in WordPress, an action or a filter
ActionA hook callback that reacts and returns nothing
FilterA hook callback that receives a value and returns a changed value
PriorityWordPress ordering key; default 10; lower runs first
Pipeline / middlewareA chain where each element handles input and calls the next
Macro / MacroableLaravel's runtime method extension via a trait
Service providerLaravel's class that registers bindings and boots a package or module
Package auto-discoveryLaravel reading extra.laravel.providers from composer.json
Tagged bindingA Laravel container tag grouping bindings for injection as an iterable
ManagerLaravel's base class for driver-based services, with extend for custom drivers
Composer pluginA Composer package of type composer-plugin with a PluginInterface class
init() registrationA Go package registering itself on import, as database drivers do
Blank importGo import _ "pkg", which runs init() without using the package
Go plugin packageStandard library loader for -buildmode=plugin shared objects with strict build-match rules
go-pluginHashiCorp's library for plugins as subprocesses over net/rpc or gRPC
gRPCRPC framework over HTTP/2 with Protocol Buffers, used for language-neutral plugins
WASM / WebAssemblyA sandboxed binary format runnable inside a host through a runtime
wazeroA zero-dependency WebAssembly runtime for Go
Envoy Wasm filterAn Envoy HTTP filter implemented as a WASM plugin
SidecarA helper process next to a service, sometimes used as a plugin host
Extension hostVS Code's separate process that runs extensions
Activation eventVS Code's declared trigger that loads an extension lazily
OSGi bundleA Java module with explicit imports and exports and a managed lifecycle
XcaddyThe tool that builds Caddy with chosen modules compiled in
Isolation levelHow strongly a plugin is separated from the host
Supply chain attackCompromise through a plugin, its update or its dependencies
Dependency hellConflicting version requirements among plugins and their libraries
God registryOne registry holding everything, acting as a global service locator
API versionThe contract major version a plugin targets

References ​

All URLs below returned HTTP 200 when fetched; the text of each was saved and the quotes above were checked against it.

Built by Morteza Negahi