The Plugin Pattern

The Plugin Pattern in Go: A workshop foreman needs parts cut, welded and painted, and has no interest in meeting the tradespeople.

The Analogy: The Notice Board in the Workshop

A workshop foreman needs parts cut, welded and painted, and has no interest in meeting the tradespeople. So the foreman pins a job description on the notice board: takes a part, returns a finished part, and states its trade name. That description is fixed and public. Anyone in the building who can do that work pins their own card underneath it, with their trade name written on the front.

When a job arrives labelled "weld", the foreman reads the board, finds the card marked weld, and hands the part over. The foreman has never met the welder, does not know whether the welding is done with gas or with an arc, and does not have to be retrained when a plasma cutter joins the shop. Adding a trade is adding a card. Removing one is removing a card. The foreman's instructions never change, because they were written about the job description rather than about any particular tradesperson.

Go builds this out of three completely ordinary pieces: an interface (the job description), a map from name to constructor (the board), and a package init function (the act of pinning your card up). The only piece with any subtlety is the direction of the arrows. The plugin imports the core in order to register itself, and the core never imports the plugin - if it did, the whole point would be lost. But that means nothing in the program references the plugin package, so something has to import it purely to make its init run. That something is the main package, with a blank import: _ "example.com/app/stages".

That inversion is why database/sql can talk to PostgreSQL without ever having heard of PostgreSQL, why image.Decode handles PNG only if some package imported image/png, and why importing net/http/pprof silently changes what your server serves - the profiling endpoints from the previous module are registered by an init. This lesson builds the pattern end to end, then covers Go's real plugin package, which loads shared objects at runtime, and explains why almost nobody should use it.


Syntax or Core Structure

The core package owns the interface and the board, and knows nothing else.

// codec/codec.go
package codec

import (
	"fmt"
	"sort"
)

// Codec is the job description. Implementations live in other packages.
type Codec interface {
	Name() string
	Encode(v []byte) ([]byte, error)
}

var registry = make(map[string]func() Codec)

// Register is called from a plugin's init. It panics on a duplicate name
// because two packages fighting over one name is a build mistake, not a
// runtime condition, and it is better to hear about it before main starts.
func Register(name string, newCodec func() Codec) {
	if newCodec == nil {
		panic("codec: Register with nil constructor for " + name)
	}
	if _, dup := registry[name]; dup {
		panic("codec: Register called twice for " + name)
	}
	registry[name] = newCodec
}

func Open(name string) (Codec, error) {
	newCodec, ok := registry[name]
	if !ok {
		return nil, fmt.Errorf("codec %q not registered (have %v)", name, Names())
	}
	return newCodec(), nil
}

func Names() []string {
	out := make([]string, 0, len(registry))
	for n := range registry {
		out = append(out, n)
	}
	sort.Strings(out) // map order is random; error messages must not be
	return out
}

A plugin imports the core, implements the interface, and pins its card up:

// codec/hexcodec/hex.go
package hexcodec

import (
	"encoding/hex"

	"example.com/app/codec"
)

type hexCodec struct{}

func (hexCodec) Name() string { return "hex" }

func (hexCodec) Encode(v []byte) ([]byte, error) {
	dst := make([]byte, hex.EncodedLen(len(v)))
	hex.Encode(dst, v)
	return dst, nil
}

func init() {
	codec.Register("hex", func() codec.Codec { return hexCodec{} })
}

And main chooses which cards are on the board:

// main.go
package main

import (
	"fmt"

	"example.com/app/codec"
	_ "example.com/app/codec/hexcodec" // imported for its init only
)

func main() {
	fmt.Println("available:", codec.Names())

	c, err := codec.Open("hex")
	if err != nil {
		fmt.Println(err)
		return
	}
	out, _ := c.Encode([]byte("Go"))
	fmt.Printf("%s -> %s\n", c.Name(), out)

	if _, err := codec.Open("base64"); err != nil {
		fmt.Println("error:", err)
	}
}

Output:

available: [hex]
hex -> 476f
error: codec "base64" not registered (have [hex])

Delete the blank import and this still compiles. It just prints available: [] and fails to open hex. That is the signature failure of the pattern, and it is why the error message lists what is registered instead of only what is missing.


Technical Depth: Initialisation Order, Ownership and the Real plugin Package

The import graph is the whole trick

        main
        /         /      blank import: for the side effect only
      /      v
     |     hexcodec
     |        |
     |        |  normal import: to call Register
     v        v
        codec

Two arrows point at codec and none point away from it. That is what makes the core stable: you can add a tenth codec without touching, testing or even recompiling the core package. It also means the core can be published as a library while every plugin lives in someone else's repository.

What Go guarantees about initialisation

The pattern rests entirely on init ordering, and the guarantees are stronger than most people assume.

RuleConsequence for a registry
Package-level variables are initialised before any init in that package, in dependency orderregistry is a non-nil map by the time anything can call Register
An imported package is fully initialised before the importing package beginscodec is ready before hexcodec.init runs, always
A package is initialised exactly once, however many packages import itTen plugins importing codec still get one registry
Multiple init functions in one package run in the order the files are presented to the compilergo build sorts by filename, but do not design around it
All initialisation happens in a single goroutine, sequentiallyRegister needs no lock if it is only ever called from init
main.main runs only after every init in the program has returnedThe board is complete and frozen before the first request

That fifth row is the reason the example has no mutex, and the reason the honest comment is "if". The moment you let anything register after startup - a test helper, a config reload - you need a sync.RWMutex around both the write and the read, because Open may then run concurrently with Register. The race detector will find this immediately if you have a test that does it.

Why Register panics but factories return errors

Panicking looks harsh until you notice when each function runs. Register runs during initialisation, before the program has done any work, and a duplicate name is a mistake in the import list that no runtime handling can fix. Crashing at startup with a clear message is the kindest outcome. The standard library agrees: sql.Register panics on a duplicate driver, and http.Handle panics on a duplicate pattern.

A factory is different. It runs after configuration is available, its input comes from a user, and "that stage's settings are wrong" is an ordinary error the program should report properly. So factories return (Thing, error) and never panic. Panic while initialising, return errors once running is the line, and it is worth stating in the core package's doc comment so plugin authors follow it.

Register a constructor, not an instance

map[string]func() Codec and map[string]Codec look interchangeable and are not.

  • A constructor is called later, so it can see parsed flags, environment and config. Every caller gets its own state, so a codec holding a buffer is safe without locking.
  • An instance is built during init, before flag.Parse has run and before any config file is read. It is shared by every caller, so it must be safe for concurrent use, and it must be usable with no configuration at all.
  • database/sql splits the difference: you register a driver.Driver instance, but the only thing it does is act as a factory - its Open method builds the actual connection later, once there is a DSN to work with.

Reading configuration inside init is the most common version of this mistake. flag.Parse has not been called, so every flag still holds its default, and the plugin quietly configures itself wrong.

Registries in the standard library

RegistryKeyNotice board it fills
sql.Register(name, driver.Driver)driver namesql.Open("pgx", dsn) works with no import of the driver's API
image.RegisterFormat(name, magic, decode, decodeConfig)a magic byte prefiximage.Decode sniffs the header and picks a decoder
gob.Register(value)the concrete type's nameLets an interface-typed field be encoded and decoded
crypto.RegisterHash(h, factory)a crypto.Hash constantShows the key need not be a string
expvar.Publish(name, v)metric namePanics on a duplicate, like the others
net/http/pprof's initURL path on DefaultServeMuxThe reason a blank import changes what your server serves

The real plugin package

Go can genuinely load code at runtime. You build a package with -buildmode=plugin, then look symbols up by name:

// go build -buildmode=plugin -o hex.so ./hexplugin
p, err := plugin.Open("hex.so") // runs the plugin's init functions
if err != nil {
	return err
}

sym, err := p.Lookup("New") // func New() codec.Codec
if err != nil {
	return err
}
newCodec, ok := sym.(func() codec.Codec)
if !ok {
	return fmt.Errorf("plugin: New has unexpected type %T", sym)
}

// A variable symbol comes back as a POINTER to the variable.
vsym, err := p.Lookup("Version") // var Version string
version, ok := vsym.(*string)

That pointer detail catches everyone once: Lookup of a var Version string yields *string, not string. Beyond that, the constraints are severe enough to disqualify the package from most projects:

  • It works on Linux, FreeBSD and macOS. There is no Windows support.
  • The plugin and the host must be built by the exact same Go toolchain version, and every package they share must be the identical version built with the identical flags and build tags. Any drift produces a plugin was built with a different version of package ... failure at Open.
  • A loaded plugin can never be unloaded. Opening the same path twice returns the same handle, so there is no reload story and no way to reclaim the memory.
  • Symbols are matched by name and asserted at runtime, so a signature change that a compiler would have caught becomes a startup error instead.

The practical alternatives, in the order teams usually reach for them: recompile the binary (Go builds in seconds and ships as one static file, which is the whole reason the language exists); run each plugin as a subprocess speaking a protocol over stdio or gRPC, which is what HashiCorp's go-plugin does for Terraform; embed a sandboxed interpreter such as Starlark or a WebAssembly runtime; or use compile-time registration, as in the example above. When people say "the plugin pattern in Go" they nearly always mean the last of these, and the reason is not laziness - one static binary with no ABI and no version skew is worth more than dynamic loading.


Real World Example: A Text Pipeline Configured by File

A log-scrubbing pipeline where the stages, their order and their settings all come from a config file, and the core package has never heard of any individual stage.

// pipeline/pipeline.go
package pipeline

import (
	"encoding/json"
	"fmt"
	"sort"
)

// Stage is the job description.
type Stage interface {
	Kind() string
	Apply(line string) string
}

// Factory builds a Stage from that stage's own slice of the config file.
// The core never looks inside cfg; only the stage that registered knows
// what shape it should be.
type Factory func(cfg json.RawMessage) (Stage, error)

var factories = make(map[string]Factory)

func Register(kind string, f Factory) {
	if f == nil {
		panic("pipeline: nil factory for " + kind)
	}
	if _, dup := factories[kind]; dup {
		panic("pipeline: Register called twice for " + kind)
	}
	factories[kind] = f
}

func Kinds() []string {
	out := make([]string, 0, len(factories))
	for k := range factories {
		out = append(out, k)
	}
	sort.Strings(out)
	return out
}

// Spec is one entry in the config file.
type Spec struct {
	Kind   string          `json:"kind"`
	Config json.RawMessage `json:"config,omitempty"`
}

type Pipeline []Stage

// Build resolves every spec up front, so an unknown kind or a bad setting
// fails at startup rather than on the first line of real traffic.
func Build(specs []Spec) (Pipeline, error) {
	p := make(Pipeline, 0, len(specs))
	for i, s := range specs {
		f, ok := factories[s.Kind]
		if !ok {
			return nil, fmt.Errorf("stage %d: unknown kind %q (have %v)", i, s.Kind, Kinds())
		}
		st, err := f(s.Config)
		if err != nil {
			return nil, fmt.Errorf("stage %d (%s): %w", i, s.Kind, err)
		}
		p = append(p, st)
	}
	return p, nil
}

func (p Pipeline) Apply(line string) string {
	for _, s := range p {
		line = s.Apply(line)
	}
	return line
}

Three stages, each pinning its own card up. Two need no configuration; one owns a schema the core never sees.

// pipeline/stages/stages.go
package stages

import (
	"bytes"
	"encoding/json"
	"errors"
	"strings"

	"example.com/app/pipeline"
)

type squeeze struct{}

func (squeeze) Kind() string          { return "squeeze" }
func (squeeze) Apply(l string) string { return strings.Join(strings.Fields(l), " ") }

type upper struct{}

func (upper) Kind() string          { return "upper" }
func (upper) Apply(l string) string { return strings.ToUpper(l) }

type redact struct {
	words []string
	mask  string
}

func (redact) Kind() string { return "redact" }

func (r redact) Apply(l string) string {
	for _, w := range r.words {
		l = strings.ReplaceAll(l, w, r.mask)
	}
	return l
}

func newRedact(cfg json.RawMessage) (pipeline.Stage, error) {
	conf := struct {
		Words []string `json:"words"`
		Mask  string   `json:"mask"`
	}{Mask: "[redacted]"} // the default is set BEFORE decoding

	if len(cfg) > 0 {
		dec := json.NewDecoder(bytes.NewReader(cfg))
		dec.DisallowUnknownFields() // a typo is an error, not a shrug
		if err := dec.Decode(&conf); err != nil {
			return nil, err
		}
	}
	if len(conf.Words) == 0 {
		return nil, errors.New("redact needs at least one word")
	}
	return redact{words: conf.Words, mask: conf.Mask}, nil
}

func init() {
	pipeline.Register("squeeze", func(json.RawMessage) (pipeline.Stage, error) { return squeeze{}, nil })
	pipeline.Register("upper", func(json.RawMessage) (pipeline.Stage, error) { return upper{}, nil })
	pipeline.Register("redact", newRedact)
}

main supplies the config and the one blank import that puts the cards on the board.

// main.go
package main

import (
	"encoding/json"
	"fmt"

	"example.com/app/pipeline"
	_ "example.com/app/pipeline/stages" // registers squeeze, upper, redact
)

const config = `[
  {"kind": "squeeze"},
  {"kind": "redact", "config": {"words": ["hunter2", "s3cr3t"]}},
  {"kind": "upper"}
]`

func main() {
	fmt.Println("kinds:", pipeline.Kinds())

	var specs []pipeline.Spec
	if err := json.Unmarshal([]byte(config), &specs); err != nil {
		panic(err)
	}
	p, err := pipeline.Build(specs)
	if err != nil {
		panic(err)
	}

	for _, l := range []string{
		"  user   logged  in with hunter2  ",
		"token=s3cr3t   scope=read",
	} {
		fmt.Printf("%q\n -> %q\n", l, p.Apply(l))
	}

	// A config naming a stage nobody imported.
	_, err = pipeline.Build([]pipeline.Spec{{Kind: "gzip"}})
	fmt.Println("build error:", err)

	// A stage whose own settings are wrong.
	_, err = pipeline.Build([]pipeline.Spec{
		{Kind: "redact", Config: json.RawMessage(`{"word": "x"}`)},
	})
	fmt.Println("config error:", err)
}

Output:

kinds: [redact squeeze upper]
"  user   logged  in with hunter2  "
 -> "USER LOGGED IN WITH [REDACTED]"
"token=s3cr3t   scope=read"
 -> "TOKEN=[REDACTED] SCOPE=READ"
build error: stage 0: unknown kind "gzip" (have [redact squeeze upper])
config error: stage 0 (redact): json: unknown field "word"

pipeline imports nothing from stages, stages imports pipeline, and main blank-imports stages. Every arrow points inward, which is why you could publish pipeline as a library and let other people write stages you will never see. Two binaries built from the same core with different blank imports are genuinely different products, and the only line that differs between them is in main.

json.RawMessage is what keeps the core honest. pipeline parses the outer list - kind, config - and treats each config value as opaque bytes. The redact factory owns its own schema, its own default (Mask is set before Decode runs, so an absent key leaves it as [redacted] rather than the empty string), and its own validation. DisallowUnknownFields turns "word" for "words" into a startup error instead of a silently ignored key and a stage that redacts nothing - which is exactly the failure you would rather not discover in a log file six weeks later.

Look at the mask in the output: [REDACTED], in capitals. Nothing capitalised it deliberately; upper simply runs after redact because the config file says so. Swap those two entries and you get [redacted] with the rest of the line still uppercased, and no code changes and nothing recompiles. That is the deliverable of this pattern - the behaviour lives in data - and it is also the warning attached to it, because stage interactions like this one are invisible in any single stage's source. The Build-then-Apply split is the mitigation: unknown kinds and bad settings surface at startup, so a broken config never reaches traffic.

The costs are real and worth naming. Every registered plugin is linked into the binary whether the config mentions it or not, so the binary grows and each plugin's dependency tree becomes yours - one stage importing a large cloud SDK affects everyone who imports the stages package. Registration also defeats the linker's dead-code elimination for those packages, because a reachable init makes everything it touches reachable. And you have traded a compile error for a startup error: {"kind": "gzip"} is a typo the compiler would have caught if the pipeline had been written as ordinary Go. Take the trade when the set of behaviours genuinely varies per deployment, per tenant, or per customer. Do not take it to make a fixed three-stage pipeline feel configurable.


Common Mistakes

  1. Forgetting the blank import. The program compiles, starts, and reports unknown kind for something that is plainly implemented in the repository. Always list the registered names in the error, and consider logging them once at startup.
  1. Putting the blank imports in a library instead of main. Every consumer of that library then gets every plugin and its dependencies, whether they wanted them or not. Blank imports belong in the main package, or in one clearly named stages/all package that a main can choose to import.
  1. Reading flags, environment or config inside init. flag.Parse has not run, so every flag still holds its default. Register a factory that reads configuration later; never configure during registration.
  1. Registering an instance where a constructor was needed. A single shared Stage holding a buffer is a data race waiting for a second goroutine. If the plugin has any mutable state, register something that builds a fresh one.
  1. Allowing registration after startup without a lock. The no-mutex version is only safe while Register is confined to init. A test helper or config reload that calls it later needs a sync.RWMutex, and go test -race will show you why.
  1. Panicking inside a factory. Factories run on user input, so a bad setting must be an error. Save panic for Register, where the caller is a programmer and the program has not started.
  1. Iterating the registry map without sorting. Map order is randomised per run, so an unsorted Kinds() produces error messages that change between runs and tests that fail one time in six.
  1. Ignoring unknown keys in a plugin's own config. Without DisallowUnknownFields, {"word": "x"} decodes cleanly into a struct expecting words and you ship a redactor that redacts nothing.
  1. Asserting a plugin.Lookup variable to the wrong type. Lookup returns a pointer for variable symbols, so var Version string comes back as *string. Assert with the two-value form and report %T on failure, because the compiler cannot help you here.
  1. Assuming -buildmode=plugin is portable. There is no Windows support, and the host and plugin must share an exact toolchain version and identical shared dependencies. A CI matrix that does not pin all of that will produce plugins that fail to load.
  1. Building the pipeline lazily. Resolving each spec on first use means a typo in stage seven surfaces after stages one to six have already processed traffic. Resolve everything in one Build call at startup.

Best Practices

  • Keep the interface, the registry and the factory type in the core package, and let the core import nothing from its plugins. If you ever need an import in the other direction, the seam is in the wrong place.
  • Register in init, construct in a Build or Open call. Registration records a name; construction reads configuration.
  • Panic on a duplicate or nil registration, return errors for anything driven by user input, and say so in the core package's doc comment so plugin authors follow the same rule.
  • Hand each plugin its own json.RawMessage and let it own the schema, the defaults and the validation. Set defaults on the struct before decoding into it, and use DisallowUnknownFields.
  • Sort anything derived from the registry before printing it, and include the available names in every "unknown kind" error.
  • Resolve the whole configuration at startup so a bad config fails before the first request rather than during one.
  • Keep blank imports in main, or in a single explicitly named aggregate package, so each binary decides which plugins it carries.
  • Prefer compile-time registration. Reach for subprocesses, WebAssembly or plugin.Open only when the set of behaviours must change without a rebuild, and only after writing down how you will pin toolchain and dependency versions.

Practice Exercises

  1. Add a truncate stage taking {"max": n} with a default of 80, rejecting n <= 0 with an error from its factory. Then place it before and after redact in the config and explain the two different results for a line whose secret sits near the cut.
  1. Split the stages into one package each and add a stages/all package whose only content is blank imports. Build two binaries - one importing all, one importing only stages/upper - and print Kinds() from each. Then compare the two binary sizes and account for the difference.
  1. Make the registry safe for registration after startup: add a sync.RWMutex, guard both Register and the lookup in Build, and write a test that registers from one goroutine while another calls Build. Run it with -race before and after adding the lock and keep both outputs.
  1. Attempt the dynamic version. Build one stage with go build -buildmode=plugin, load it with plugin.Open and Lookup, and then deliberately break it - rebuild the host with a different Go version, or bump a shared dependency. Record the exact error each time, and write a short note on what your CI would have to guarantee for this to be shippable.