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 for | Go to |
|---|---|
| The style in a few tables | Everything in one minute |
| Why a core plus plugins at all | Why it exists |
| Operating systems, Eclipse, OSGi, WordPress, VS Code, go-plugin | Where it comes from |
| One block per concept | The concept catalogue |
| Contract and versioning rules, error messages, knobs | Mechanics |
| The shipping-rate engine in Go and Laravel | Go, Laravel |
| Plugins reaching into the core, god registry, dependency hell | Solving the classic problems |
| Which isolation level, which extension point | Choosing |
| Plugins in a monolith, a modular monolith, microservices, at scale | In architecture |
| Run it, add a third-party plugin, break it | Lab |
| Wrong beliefs, cheat sheet, self-check, terms, sources | Misconceptions, Cheat sheet, Self-check, Glossary, References |
Everything in one minute
The vocabulary. Every row is unpacked in the concept catalogue.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Core system (microkernel) | The small part that every user needs and that rarely changes | The shipping Engine and Registry | The core grows a branch per customer |
| Plugin | A separate piece that adds one capability through the contract | fastbox carrier | Every new carrier edits core code |
| Plugin contract | The interface and rules the core promises to keep | Carrier with Manifest() and Quote() | Plugins depend on internals and break at each core release |
| Registry | The core's list of installed plugins and their state | Registry.Register, tagged container bindings | The core hard-codes if name == "ground" |
| Discovery | How the registry learns what exists | blank import, Composer extra.laravel, config list | Plugins exist but nobody calls them |
| Extension point | A named place in the core where plugins attach | strategy, typed set, hook, pipeline | Plugins patch core code |
| Isolation level | How far a plugin is separated from the host | in-process, RPC process, WASM, container | One bad plugin kills the host or steals secrets |
| Lifecycle | The states a plugin goes through | register, init, active, disabled, stop | Half-started plugins answer requests |
| Plugin versioning | A rule for which plugin versions a core accepts | APIVersion = 2, manifest check | A core upgrade silently breaks plugins |
Four extension-point types, one table.
| Type | The core... | Typical API | Example products |
|---|---|---|---|
| Strategy / driver | picks exactly one implementation by name | Manager::driver('x'), sql.Open("pgx", ...) | Laravel cache and mail drivers, Go database/sql |
| Typed set | calls all implementations and merges | tagged bindings, slice of interfaces | Our shipping engine, Terraform providers in one plan |
| Hook (action / filter) | announces moments; plugins react or change a value | add_action, add_filter | WordPress, Composer plugin events |
| Pipeline / middleware | passes the work through plugins in order | next(ctx) | HTTP middleware, Caddy handlers, Envoy filter chain |
Four isolation levels, one table.
| Level | Memory shared with the host? | A crash... | Speed of a call | Typical use |
|---|---|---|---|---|
| In-process library | Yes | kills the host | nanoseconds | Trusted internal plugins, Go init() registration, Composer packages |
| In-process WASM | No (own linear memory) | traps inside the sandbox | microseconds | Envoy WASM filters, wazero-hosted rules |
| Separate process, RPC/gRPC | No | the host survives | 0.1 to a few ms | go-plugin (Terraform, Vault, Nomad), VS Code extension host |
| Container or microVM | No, plus OS limits | the host survives | network hop | Untrusted 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 boundary | With a plugin boundary |
|---|---|
| New carrier, new payment provider, new rule: edit the core and redeploy everything | New carrier is a package that implements one interface |
| The core test suite grows with every variant | The core is tested against stub plugins; each plugin has its own tests |
| Customer-specific code sits in the main branch | Customer code lives outside; the core never sees it |
| Fast to start | Needs an up-front contract; slower to start |
| Good for: one product, one customer | Good for: products, platforms, ecosystems |
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
- "A plugin architecture is a folder where you drop
.soor.jarfiles." 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. - "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.
- "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.
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 pluginsThe 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.
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 resultReal 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).
| Product | Core | Plugins |
|---|---|---|
| Eclipse | Launcher and runtime | Nearly all features |
| VS Code | Editor shell, extension host | Language support, themes, debuggers |
| WordPress | Request lifecycle, hooks, data model | Plugins and themes |
| Terraform | Graph walker, state, plan/apply | Providers (AWS, Azure, ...) |
| Caddy | Config loader, module loader | HTTP handlers, TLS issuers, storage |
| Laravel | Container, kernel, events | Packages via service providers |
| Composer | Dependency resolver | Plugins 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).
| Part | Example in our engine | Who breaks it |
|---|---|---|
| Shape | Quote(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 |
| Version | APIVersion = 2 in the manifest | A core that changes semantics without bumping |
| Optional capabilities | Initializer, Closer (Go); optional methods | A 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 flavour | Where | What it adds |
|---|---|---|
| Map in memory | Go shipping.Registry, Caddy module registry | Simple, fast, rebuilt at start |
| Service container tags | Laravel $app->tag([...], 'carriers') | Lazy resolution, constructor injection |
| Manifest-driven | VS Code package.json, Eclipse MANIFEST.MF | Core reads metadata without running plugin code |
| Service registry with callbacks | OSGi | Dynamic: services appear and vanish while running |
| Database table | SaaS 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".
| Method | How it works | Pros | Cons | Used by |
|---|---|---|---|---|
| Static registration | Plugin package calls Register in init(); main imports it | Compile-time checked, one binary | Rebuild to add or remove | Go database/sql drivers, Caddy, our plugins.go |
| Config list | A file names the plugins to load | Explicit, reviewable | Typos found at start | Laravel bootstrap/providers.php, WordPress active plugins |
| Package-manager metadata | composer.json extra section read by the framework | Install equals discovery | Hidden magic; disable needs dont-discover | Laravel package auto-discovery, Composer plugins |
| Filesystem scan | Core lists a directory and loads each | Drop-in feel | Security and ordering questions | WordPress wp-content/plugins, go-plugin binaries, VS Code extensions folder |
| Manifest scan | Read package.json or plugin.xml without running code | Safe, lazy loading by event | Needs manifest schema | VS Code, Eclipse |
| Registry service / marketplace | Download and verify from a central index | Ecosystem, versions, signatures | Supply-chain risk | Terraform 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.
| Type | Contract style | Typing | Ordering | Failure handling | Example |
|---|---|---|---|---|---|
| Strategy / driver | Interface, chosen by name | Compile-time | n/a, one wins | Missing name is an error | Laravel Manager::extend |
| Typed set | Interface, all called | Compile-time | By registry order or sort | Isolate each plugin | Our Engine.Quote |
| Action hook | Name plus args, returns nothing | Runtime (strings) | Priority, then registration order | Usually unhandled | WordPress do_action |
| Filter hook | Name plus value, returns value | Runtime | Priority, then registration order | One bad filter corrupts the value | WordPress apply_filters |
| Event | Typed event object, listeners react | Compile-time (class) | Listener order | Sync vs queued | Laravel events |
| Pipeline | handle(input, next) | Compile-time | Position in chain | Short-circuit or pass | HTTP middleware, Envoy filters |
| Macro / mixin | Add methods to a core class | Runtime | Last registration wins | Name collisions | Laravel 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.
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 orderWordPress 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.
| Aspect | Hooks (WordPress style) | Typed interfaces (Go, Laravel contracts) |
|---|---|---|
| Discoverability | Grep for hook names | Compiler and IDE find implementations |
| Safety | Wrong argument count shows up at runtime | Wrong signature does not compile (or fails static analysis) |
| Evolution | Add args carefully; names are forever | Add optional interfaces, bump major for breaking |
| Cross-plugin interference | High: filters chain on shared values | Lower: each plugin returns its own result |
| Best for | Many small tweaks by unrelated authors | A 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.
| Level | Mechanism | Memory | Failure | Privileges | Cost |
|---|---|---|---|---|---|
| 0 In-process, no guard | Direct call | Shared | Panic or leak hits host | Same as host | Lowest |
| 1 In-process, guarded | recover, timeout, per-plugin goroutine/try-catch | Shared | Panics contained; leaks and memory corruption not | Same as host | Low |
| 2 In-process WASM | wazero, Envoy Wasm | Separate linear memory | Trap, host continues | Only imported host functions | Medium (marshalling) |
| 3 Separate process | go-plugin, VS Code extension host | Separate | Host survives | OS user of the plugin process | Medium (IPC) |
| 4 Container / microVM | Docker, Firecracker, hosted functions | Separate | Host survives | cgroups, seccomp, network policy | Highest |
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."
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).
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| Concept | VS Code | OSGi | Go (ours) | Laravel |
|---|---|---|---|---|
| Register | Read package.json manifest | Install bundle | Register in init() | register() of the provider |
| Initialise | activate() on an activation event | start, BundleActivator | Init(ctx, cfg) | boot() of the provider |
| Disable | Disable in UI, reload | stop bundle | Registry.Disable | Remove provider, dont-discover |
| Stop | deactivate() | stop | Close in reverse order | Process ends (per request) |
| Hot unload | Extension host restart | Supported | Not for compiled-in plugins | Not 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.
| Rule | Why | Where in our code |
|---|---|---|
Plugin declares APIVersion of the contract | Core can refuse incompatible plugins before calling them | Registry.Register |
| Contract major bumps only on breaking change | Plugins pin one major | shipping.APIVersion |
| Minor/additive changes use optional interfaces | Old plugins keep working | Initializer, Closer |
Requires lists plugin names; no cycles | Defines init order | Registry.Init |
| Prefer plugin-to-core over plugin-to-plugin | Avoids dependency webs | fastbox requires only flat for the demo |
| Version ranges in package manager | Composer and Go modules resolve it for you | composer.json, go.mod |
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 FailedSecurity 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).
| Threat | Example | Mitigation |
|---|---|---|
| Malicious plugin | Reads tenant data, calls home | Sandbox (WASM, container), network policy, no ambient credentials |
| Compromised update | Trusted plugin ships a bad release | Pin versions, checksums, lock files, staged rollout |
| Typosquatting | acme/fastbxo instead of acme/fastbox | Allow-list of vendors, review on install |
| Over-privileged plugin | A shipping plugin that can write orders | Give narrow interfaces, not the whole app container |
| Plugin loads plugins | Bug lets an attacker choose the file | Fixed plugin directory, verify checksum before exec |
| Host trust | Core accepts any plugin by name | Manifest 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).
| Cost | In-process | WASM | RPC process | Mitigation |
|---|---|---|---|---|
| Call | ns | us | 0.1 to a few ms | Batch calls, coarse-grained contract, cache |
| Start | init() cost | Compile and instantiate module | Fork and handshake | Lazy activation (VS Code activation events) |
| Memory | Shared heap | One linear memory per module | One process per plugin | Share one process for many instances |
| Failure of slow plugin | Blocks unless timeout | Fuel or deadline | Deadline over RPC | Per-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-pattern | Symptom | Fix |
|---|---|---|
| Plugins reaching into core internals | Plugin imports core/internal or reads core tables | Language visibility (internal/), arch tests, narrow facade |
| God registry | One registry with every service, config and plugin type | One registry per extension point; no service locator |
| Plugin dependency hell | Plugin A needs B 2.x, plugin C needs B 3.x | Core owns shared contracts; plugins avoid each other |
| Fat contract | 40 methods per plugin | Small interface plus optional capabilities |
| Chatty contract | Many calls per user action | Coarse-grained operations |
| Unversioned contract | "It worked on the last release" | Manifest API version, compatibility tests |
| Hook soup | Hundreds of hooks, unknown order | Document order, limit filters on shared values |
| Plugin as core fork | Customer edits copy of the core | Move 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.
| Situation | Fit | Why | Example |
|---|---|---|---|
| Product customisation per customer | Strong | Variation outside the core | Rules engine for insurance claims (Richards) |
| SaaS tenant extensions | Strong with isolation | Tenants run own logic | Webhooks, WASM rules, app marketplaces |
| IDEs and editors | Strong | Ecosystem is the product | Eclipse, VS Code |
| CMS and e-commerce | Strong | Third-party ecosystem | WordPress, Magento |
| CI systems | Strong | Steps are plugins | Jenkins plugins, GitHub Actions as external units |
| Payment, shipping, notification providers | Strong | Provider list changes monthly | This chapter's carriers |
| Infrastructure tools | Strong with process isolation | Many providers, one engine | Terraform, Vault, Packer |
| A CRUD app with one team | Weak | No independent variation | Use a modular monolith |
| Extreme throughput core | Weak | Indirection cost | Keep 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.
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 errorsHook execution order Important
| Rule | WordPress | Our Go engine | Our Laravel engine |
|---|---|---|---|
| Order key | Priority integer, default 10 | Slice order of Filters | Tag resolution order |
| Ties | Registration order | n/a | Container tag order |
| Filter return value | Required, passed on | Required, replaced | Required, passed on |
| Action return value | Ignored | Observer returns nothing | Event listeners (return ignored) |
| Error in a callback | Fatal unless caught | A panic in a filter is not recovered; filters run in the host | Exception 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
| Item | go-plugin | Terraform plugin protocol | VS Code |
|---|---|---|---|
| Transport | net/rpc over yamux, or gRPC | gRPC (Protocol Buffers) | Node IPC to the extension host |
| Handshake | Magic cookie plus protocol version | Protocol version negotiated | engines.vscode range in manifest |
| Versioning | ProtocolVersion integer, planned semantic version | Major protocol versions (5, 6), additive minors | Extension API versions |
| Language | Any language via gRPC | Any language via gRPC | JavaScript or TypeScript (and web) |
| Verification | Optional SecureConfig checksum | Registry signatures and provider checksums | Marketplace 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
| Where | Message or code | Meaning |
|---|---|---|
Go plugin.Open | plugin was built with a different version of package ... | Toolchain, build flags or dependency source differ between host and plugin |
Go plugin.Open | plugin: not implemented | Platform without plugin support (Windows) |
| go-plugin | Incompatible API version with plugin | Handshake ProtocolVersion mismatch |
| go-plugin | Unrecognized remote plugin message | Binary ran but is not a go-plugin server (wrong magic cookie) |
| Caddy | module not registered: http.handlers.foo | Plugin not compiled into the binary (use xcaddy) |
| Composer | Plugin class not found at activation | extra.class points to a missing class, or the package is not installed |
| Laravel | Driver [x] not supported. (InvalidArgumentException from Manager) | extend('x') was never called or the name is misspelled |
| Laravel | Target [App\...\Carrier] is not instantiable | Interface bound nowhere |
| WordPress | White screen after activation | A plugin fatal error at load; deactivate by renaming the plugin folder |
| Our Go engine | plugin "old" built for API v1, host speaks v2 | Contract version refused at Register |
| Our Go engine | plugin 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.
-- 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
// 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
}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...)
}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:
// 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
}// 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:
// 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).
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"
)// 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
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")
}
}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")
}
}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.
// 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() }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
| Option | What it is | Verdict |
|---|---|---|
| Interface + registry + blank imports | Compile-time plugins, one binary | The default choice; used by database/sql drivers and Caddy |
Standard plugin package | go build -buildmode=plugin, plugin.Open | Rarely chosen; see the limits below |
hashicorp/go-plugin | Subprocess plus net/rpc or gRPC | The mature level-3 option; Terraform, Vault, Nomad, Packer |
| WASM with wazero | Pure-Go WASM runtime, host functions | Level 2; sandboxed, language-neutral |
| gRPC service | Plugin is a network service | Service-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:
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 interfacewazero 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:
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
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
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
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
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
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
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
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
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
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():
$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:
{
"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
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
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
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
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
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
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
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 feature | Plugin role | Notes |
|---|---|---|
| Service provider | The plugin's entry point | register() binds, boot() runs after all providers are registered |
bootstrap/providers.php | The explicit plugin list | Laravel 13 provider docs describe it as the list of providers to load |
| Package auto-discovery | Install equals discovery | extra.laravel.providers in composer.json; consumers opt out with dont-discover |
| Contracts (interfaces) | The plugin contract | The container binds interface to implementation |
tag() and #[Tag('x')] | Typed-set extension point | Container docs show tagged injection; the attribute is listed among the container attributes |
Manager and extend | Strategy extension point | Used by cache, mail, queue managers; extend registers a custom creator |
| Events and listeners | Action hook | Event::listen, subscribers; sync or queued |
Macroable | Mixin extension point | macro('name', closure) adds methods at runtime |
| Pest plugins | Test-tool plugins | Pest documents a plugin system for extending the test runner |
| Composer plugins | Build-tool plugins | type: composer-plugin, class implements PluginInterface, activate() receives Composer and IOInterface |
| Pint | Code formatter | Not 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
| Solution | How | Advantage | Cost or limitation |
|---|---|---|---|
| Language visibility | Go internal/; PHP final classes and a separate Api namespace | The compiler or analyser refuses | PHP has no hard package privacy |
| Narrow facade | Give plugins a small HostAPI interface, not the container | Plugin can only do what the facade allows | More design work |
| Architecture tests | Pest arch(); Go test that parses imports | Fails in CI | Only checks what you wrote down |
| Process boundary | Move the plugin out of process | Reach is impossible, not just forbidden | Cost of IPC |
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
| Cause | Fix |
|---|---|
| Plugin A needs library X 1.x, plugin B needs X 2.x, both in one process | Process 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 B | Allow it only through Requires in the manifest, resolve in order, forbid cycles |
| Core upgrade breaks plugins | Contract major version; keep the old major for a deprecation period; run plugin compatibility tests in core CI |
| Everyone depends on everyone | Move 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
| Technique | Where |
|---|---|
Per-call timeout via context | Engine.Timeout, ctx.Done() |
recover() around plugin calls | Engine.call |
| Failure map returned to the caller | Result.Failures |
| Circuit breaker per plugin | Add after repeated failures; see Circuit Breaker |
| Bulkhead: separate worker pool per plugin | Prevents one plugin using all goroutines or threads |
| Fallback | Return 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
| Situation | Pick | Reason |
|---|---|---|
| One team, one product, rare variation | Layered or modular monolith | Contract overhead not repaid |
| Product with many integrations of one kind (carriers, gateways, exporters) | Microkernel with typed set | Providers change often, core does not |
| Product where customers need own logic, unknown at build time | Microkernel with WASM or webhooks | Isolation is required |
| Ecosystem product (CMS, IDE) | Microkernel with hooks plus manifests | Thousands of authors |
| Many teams shipping separate services | Microservices with extension points in the gateway | Teams deploy separately |
Extension-point decision
| You need | Use | Example |
|---|---|---|
| Exactly one implementation per setting | Strategy / driver (Manager) | Cache store |
| All implementations contribute | Typed set | Carriers |
| Observe or tweak a value in many places | Hook (filter) | Rate surcharge |
| Order-dependent processing | Pipeline | Auth then rate limit |
| Add a convenience method | Macro | Collection::macro |
| React to a fact | Event | RatesQuoted |
Isolation decision
| Trust and need | Level | Mechanism |
|---|---|---|
| Team code, same repo | 0 or 1 | Interfaces, recover, timeouts |
| Contractor or partner code, reviewed | 3 | go-plugin, RPC, checksum |
| Tenant or public code on your servers | 2 or 4 | WASM (wazero, Envoy Wasm), containers |
| Different language required | 2 or 3 | WASM or gRPC |
| Latency under 1 ms per call | 0, 1 or 2 | Avoid 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.
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 orderModular 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:
| Shape | What the plugin is | Isolation | Examples |
|---|---|---|---|
| Gateway with plugin filters | A filter in the proxy's chain | In-process (Lua, Go, WASM) | Envoy HTTP filters, Kong plugins, Traefik middleware, Caddy modules |
| Sidecar extension | A separate process next to the service | Process | Envoy external processing, service mesh sidecars |
| Plugin as a service | The plugin is a remote service the core calls | Network | Payment orchestration calling provider adapters, webhooks |
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.
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 serviceAcross 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
| Concern | What happens with plugins | Handling |
|---|---|---|
| Plugin list per node | Nodes run different plugin versions during a rollout | Contract versions allow mixed fleets; roll out per node group |
| Plugin config in a database | Read replica lag shows stale enabled flags | Read the switchboard from the primary or cache with a short TTL and accept the lag |
| Cached results | A cached rate survives disabling its carrier | Key the cache by plugin version and enabled set; evict on disable |
| Shared state between instances | Plugin keeps local counters | Put shared state in Redis or the DB, not in plugin memory |
| Multi-region | A plugin that calls a regional API | Per-region configuration; plugin gets the region in its config |
Scaling path: 1×, 10×, 100×
| Load | Design | Plugins |
|---|---|---|
| 1x: a shop with 3 carriers | One binary or Laravel app | In-process, init() or tagged providers |
| 10x: many tenants, own settings | Switchboard table, per-tenant enabled set, per-call timeouts and breakers | Still in-process, tenant-specific configuration |
| 100x: tenants bring code | WASM or process isolation, quota per plugin, plugin marketplace with review and signatures | Level 2 or 3, plugin metrics per tenant |
| Beyond | Plugin as a service with its own SLO | Network 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.
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.
| Measure | In-process carrier | RPC carrier |
|---|---|---|
| Call cost (your benchmark) | measure | measure |
| Crash of the plugin | Host panics unless recover | Host gets an error |
| Memory shared | Yes | No |
| Third-party can read host memory | Yes | No |
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
| Belief | Reality |
|---|---|
A plugin system means loading .so or .jar files at runtime | Discovery can be compile-time (Go imports, Caddy) or package-manager based (Composer) |
Go's plugin package is the Go way to do plugins | The 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 thing | One deployable with in-process plugins versus many deployables; they combine but are different decisions |
| An interface is enough of a contract | Semantics, timeouts, errors and the version are also contract |
| Plugins are isolated because they are separate packages | Same process means shared memory and privileges |
| WordPress hooks are bad design | They are an untyped but very successful public API; the cost is discoverability and ordering |
| The core should be as small as possible | The core should be stable; a rich but stable core is fine |
| More extension points is better | Each is a long-term promise; add them where variation is proven |
| Hot-unloading plugins is a normal feature | It is hard (OSGi supports it; Go compiled-in plugins and plugin cannot) |
| Open-source plugins need no security review | Supply-chain and update risks remain |
| A registry is a global singleton | It is a type; a default instance is a convenience that tests should bypass |
| Microkernel scales well | Richards rates scalability low because most implementations are single units |
Cheat sheet
| Topic | What to remember |
|---|---|
| Shape | Stable core + versioned contract + registry + plugins |
| Direction of dependency | Plugins depend on the contract; the core depends on no plugin |
| Discovery | Static import, config list, package metadata, filesystem scan, manifest scan |
| Extension points | Strategy (one), typed set (all), hook (tweak), pipeline (ordered), macro (mixin) |
| Hooks vs interfaces | Hooks: flexible, string-named; interfaces: checked, discoverable |
| Isolation ladder | In-process, WASM, process (RPC/gRPC), container |
| Lifecycle | Register, resolve, init, active, disabled, stop, unload |
| Versioning | Plugin version for users; contract major for the core; additive changes through optional interfaces |
| Security | Trust, permissions, isolation, checksums; never "same privileges as the host" by accident |
| Performance | Coarse contract, lazy activation, per-call timeout |
| Go | Interface + registry + blank imports; go-plugin for processes; wazero for sandboxes; avoid plugin unless one builder controls everything |
| Laravel | Contract + service provider + tag(); Manager and extend for one-of; package auto-discovery via extra.laravel.providers |
| Anti-patterns | Reaching into internals, god registry, dependency hell, fat or chatty contract |
| Service scale | Gateway filters, sidecars, WASM filters, webhooks |
| Test | Core with stub plugins; each plugin against the contract; arch tests |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Microkernel | A small core providing minimal services, with features outside it; the name comes from operating systems |
| Core system | The stable part of a plugin architecture that owns the contract, registry and lifecycle |
| Plugin / plug-in | A component that extends a system through its contract without rebuilding the core |
| Add-on, extension | Synonyms for plugin in different ecosystems (Wikipedia lists plug-in, add-in, add-on, extension) |
| Plugin contract | Shape, semantics and version of the interface between core and plugin |
| Manifest | Metadata (name, version, API version, requires) read before plugin code runs |
| Registry | The core's collection of plugins, their state and lookup |
| Service locator | A registry that hands out arbitrary services by name; a smell when it becomes the god registry |
| Discovery | How the registry learns which plugins exist |
| Extension point | A named, documented place where plugin code is called |
| Strategy / driver | An extension point where one implementation is chosen by name |
| Typed set | An extension point that calls all implementations of an interface |
| Hook | A named point where callbacks run; in WordPress, an action or a filter |
| Action | A hook callback that reacts and returns nothing |
| Filter | A hook callback that receives a value and returns a changed value |
| Priority | WordPress ordering key; default 10; lower runs first |
| Pipeline / middleware | A chain where each element handles input and calls the next |
| Macro / Macroable | Laravel's runtime method extension via a trait |
| Service provider | Laravel's class that registers bindings and boots a package or module |
| Package auto-discovery | Laravel reading extra.laravel.providers from composer.json |
| Tagged binding | A Laravel container tag grouping bindings for injection as an iterable |
| Manager | Laravel's base class for driver-based services, with extend for custom drivers |
| Composer plugin | A Composer package of type composer-plugin with a PluginInterface class |
init() registration | A Go package registering itself on import, as database drivers do |
| Blank import | Go import _ "pkg", which runs init() without using the package |
Go plugin package | Standard library loader for -buildmode=plugin shared objects with strict build-match rules |
| go-plugin | HashiCorp's library for plugins as subprocesses over net/rpc or gRPC |
| gRPC | RPC framework over HTTP/2 with Protocol Buffers, used for language-neutral plugins |
| WASM / WebAssembly | A sandboxed binary format runnable inside a host through a runtime |
| wazero | A zero-dependency WebAssembly runtime for Go |
| Envoy Wasm filter | An Envoy HTTP filter implemented as a WASM plugin |
| Sidecar | A helper process next to a service, sometimes used as a plugin host |
| Extension host | VS Code's separate process that runs extensions |
| Activation event | VS Code's declared trigger that loads an extension lazily |
| OSGi bundle | A Java module with explicit imports and exports and a managed lifecycle |
| Xcaddy | The tool that builds Caddy with chosen modules compiled in |
| Isolation level | How strongly a plugin is separated from the host |
| Supply chain attack | Compromise through a plugin, its update or its dependencies |
| Dependency hell | Conflicting version requirements among plugins and their libraries |
| God registry | One registry holding everything, acting as a global service locator |
| API version | The 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.
- Mark Richards, Software Architecture Patterns, O'Reilly (free report), chapter 3 "Microkernel Architecture". oreilly.com (the chapter text is in this page; we read the report, not Richards and Ford, Fundamentals of Software Architecture)
- Wikipedia (secondary): Microkernel, Plug-in (computing), Pattern-Oriented Software Architecture; Buschmann et al., POSA vol. 1 (not read)
- Eclipse: FAQ: What is a plug-in?; OSGi Alliance: Architecture overview, Core: Framework lifecycle
- VS Code: Extension Host, Activation Events, Extension manifest, Extension runtime security
- WordPress Plugin Handbook: Hooks, Actions, Filters, Custom hooks
- Laravel 13: Packages, Service Providers, Service Container, Events; framework source: Manager.php, Macroable.php; Pest plugins
- Composer: Plugins
- Go: plugin package source and documentation; HashiCorp go-plugin README; wazero
- Caddy: Extending Caddy
- Terraform: Plugin development, Plugin protocol
- Envoy: Wasm HTTP filter