Back to sketch

SYSTEM DESIGN SKETCHBOOK / PRACTICE SHEET / NO. 31

Design a dependency injection framework

Advanced · 45 min · Client & library design

Your platform team ships a library that backend services use to wire their objects together. Service authors declare what each class needs, and the container builds the graph at startup and for every incoming request. Today each team hand-writes factories, and mistakes only show up in production.

Requirements

  • Register bindings from a token (an interface or a named key) to a class, a factory function, or an existing instance, each with a lifetime: singleton, scoped (one per request), or transient (new every time).
  • Resolve a requested token by constructing it and all of its transitive dependencies in a valid order.
  • Open a scope per request; scoped instances are shared inside it and disposed in reverse creation order when it closes.
  • Report missing bindings, cycles and lifetime mistakes with the full dependency path, before the service starts taking traffic.

Constraints and assumptions

  • The largest application has 2,000 bindings, an average of 4 constructor dependencies each, and graph depth up to 15.
  • Container build (validation plus eager singletons) must finish in under 300 ms, because some services cold-start on every deploy and in serverless runtimes.
  • A busy process handles 5,000 requests/s; each request opens one scope and resolves about 40 objects. Container overhead must stay under 50 µs per request.
  • Resolution is called from many threads at once; a singleton must be constructed exactly once.
  • Some targets are compiled ahead of time, where runtime reflection over constructors is unavailable or very slow.

Out of scope for the first sketch

Method interception and proxies (AOP) · XML or YAML configuration formats · Hot reloading bindings in a running process · Loading plugins from untrusted code

Draw your design

Rough math and notes

Done on paper? Compare with the worked approaches