SYSTEM DESIGN SKETCHBOOK / PRACTICE SHEET / NO. 31
Design a dependency injection framework
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
SYSTEM DESIGN SKETCHBOOK / FOLLOW-UPS
Design a dependency injection framework
Finish your first sketch before answering these. Cross out freely.
- A request-scoped object ends up injected into a singleton. What goes wrong at runtime, and how could the container refuse it?
- Two services depend on each other. How do you detect the cycle and report it, and are there any cycles you would allow?
- Two threads resolve the same lazy singleton at the same moment, and its constructor takes 2 seconds. What happens in your design?
- Startup now takes 4 seconds because the container reflects over 2,000 classes. How do you move that work to build time, and what do you give up?
- Tests and individual tenants need to override a few bindings. How do you layer containers without creating two copies of a singleton that should be shared?
Compare afterwards: worked approaches and reading at sketchbook /questions/dependency-injection/review