How Frameworks Are Built from Patterns
A framework you've never seen looks like hundreds of files and a lot of magic; follow one request through it and every step is a pattern this course has taught (a facade to start it, observers when it starts, a pipeline of middleware, a dictionary of routes, a container, a controller, a repository), and the framework calling your code, not the other way round, is what makes it a framework.
Journeyman · OOP · Software Development · Updated
After this lesson you can
- Follow one request through a framework and name the pattern behind each step it passes
- Explain inversion of control: a framework calls your code, where your code calls a library
- Find your way around a new framework by asking where its composition root, pipeline, routes, controllers and repositories are
Key takeaways
- Following one request through a framework, from start-up to response, names a pattern at every step.
- Start-up is a facade, start-up events observers, middleware a chain, routes a dictionary of functions, the container dependency injection, controllers MVC, and data sits behind repositories.
- A framework calls your code (inversion of control), where your code calls a library; its run loop is a template method whose steps you fill in.
- On a new framework, find its composition root, its pipeline, its routes, its controllers and its repositories, and the rest of the files fall into place.
Before this: the rest of this pass: Dependency Injection, Containers, Repository, MVC and Middleware.
Here's a day that happens to almost every developer. You start a new job, or move to a new team, and the app is built on a framework you've never used. Your last team used Express; this one uses Spring Boot. The project has two hundred files, and things happen that no file seems to ask for: a class is made though nobody writes new, a method runs though nobody calls it. Where do you even start reading? This lesson's answer: follow one request through, and name what you meet. Every step is a pattern you already know.
The problem: it looks like magic
Look at what you write in a framework, and what you don't. You write a controller method that borrows a book. You never call it. You ask for a CheckoutService in a constructor. You never make one. You write a sign-in check. You never put it in front of anything. Something else does all of that, and until you know what, the app feels like magic, and magic is hard to debug.
What would you try? Reading the framework's own source code, top to bottom, takes months. Reading every file in the project takes days, and you'd still not know which runs first. Copying what the other files do works until something breaks, and then you can't tell why.
What helps is a map: the few kinds of thing a framework is made of, and the order a request meets them in.
A framework in forty lines
To see the map without the magic, here is a whole framework, small enough to read: it starts, tells whoever's listening that it started, passes a request through its middleware, finds the endpoint for the address, has its container make the service the endpoint needs, and writes the response. The parts you'd write as an app developer are at the top; the framework is below them. One request comes in, Maya borrowing The Lighthouse Keeper:
// The app: the parts you write.
MiniFramework app = new MiniFramework();
app.OnStarted(() => Console.WriteLine("started: listening for requests"));
app.Use((request, next) =>
{
Console.WriteLine( quot;middleware: {request.Method} {request.Path} from {request.User}");
return next(request);
});
app.Register(() => new CheckoutService(new InMemoryLoans()));
app.Map("POST /loans", request => app.Get<CheckoutService>().Borrow(request.User, request.Body));
app.Run(new Request("POST", "/loans", "Maya", "The Lighthouse Keeper"));
record Request(string Method, string Path, string User, string Body);
record Response(int Status, string Body);
class InMemoryLoans
{
private int count;
public int Add(string member, string title)
{
Console.WriteLine( quot;repository: loan {++count} saved");
return count;
}
}
class CheckoutService
{
private readonly InMemoryLoans loans;
public CheckoutService(InMemoryLoans loans) => this.loans = loans;
public Response Borrow(string member, string title) => new Response(201, quot;Loan {loans.Add(member, title)}: {member}, {title}");
}
// The framework: it calls the parts you wrote, in its own order.
class MiniFramework
{
private readonly List<Action> startedListeners = new();
private readonly List<Func<Request, Func<Request, Response>, Response>> middleware = new();
private readonly Dictionary<string, Func<Request, Response>> routes = new();
private readonly Dictionary<Type, Func<object>> recipes = new();
public void OnStarted(Action listener) => startedListeners.Add(listener);
public void Use(Func<Request, Func<Request, Response>, Response> step) => middleware.Add(step);
public void Map(string route, Func<Request, Response> endpoint) => routes[route] = endpoint;
public void Register<T>(Func<T> make) where T : notnull => recipes[typeof(T)] = () => make();
public T Get<T>()
{
Console.WriteLine( quot;container: made a {typeof(T).Name}");
return (T)recipes[typeof(T)]();
}
public void Run(Request request)
{
foreach (Action listener in startedListeners) { listener(); }
Func<Request, Response> handler = Route;
for (int i = middleware.Count - 1; i >= 0; i--)
{
var step = middleware[i];
var next = handler;
handler = r => step(r, next);
}
Response response = handler(request);
Console.WriteLine( quot;{response.Status} {response.Body}");
}
private Response Route(Request request)
{
Console.WriteLine( quot;router: {request.Method} {request.Path} goes to its endpoint");
return routes[ quot;{request.Method} {request.Path}"](request);
}
}
started: listening for requests
middleware: POST /loans from Maya
router: POST /loans goes to its endpoint
container: made a CheckoutService
repository: loan 1 saved
201 Loan 1: Maya, The Lighthouse Keeper
record Request(String method, String path, String user, String body) { }
record Response(int status, String body) { }
static class InMemoryLoans {
private int count;
int add(String member, String title) {
count++;
IO.println("repository: loan " + count + " saved");
return count;
}
}
static class CheckoutService {
private final InMemoryLoans loans;
CheckoutService(InMemoryLoans loans) { this.loans = loans; }
Response borrow(String member, String title) { return new Response(201, "Loan " + loans.add(member, title) + ": " + member + ", " + title); }
}
interface Handler { Response handle(Request request); }
interface Middleware { Response handle(Request request, Handler next); }
// The framework: it calls the parts you wrote, in its own order.
static class MiniFramework {
private final List<Runnable> startedListeners = new ArrayList<>();
private final List<Middleware> middleware = new ArrayList<>();
private final Map<String, Handler> routes = new HashMap<>();
private final Map<Class<?>, Supplier<?>> recipes = new HashMap<>();
void onStarted(Runnable listener) { startedListeners.add(listener); }
void use(Middleware step) { middleware.add(step); }
void map(String route, Handler endpoint) { routes.put(route, endpoint); }
<T> void register(Class<T> type, Supplier<T> make) { recipes.put(type, make); }
<T> T get(Class<T> type) {
IO.println("container: made a " + type.getSimpleName());
return type.cast(recipes.get(type).get());
}
void run(Request request) {
for (Runnable listener : startedListeners) { listener.run(); }
Handler handler = this::route;
for (int i = middleware.size() - 1; i >= 0; i--) {
Middleware step = middleware.get(i);
Handler next = handler;
handler = r -> step.handle(r, next);
}
Response response = handler.handle(request);
IO.println(response.status() + " " + response.body());
}
private Response route(Request request) {
IO.println("router: " + request.method() + " " + request.path() + " goes to its endpoint");
return routes.get(request.method() + " " + request.path()).handle(request);
}
}
// The app: the parts you write.
void main() {
MiniFramework app = new MiniFramework();
app.onStarted(() -> IO.println("started: listening for requests"));
app.use((request, next) -> {
IO.println("middleware: " + request.method() + " " + request.path() + " from " + request.user());
return next.handle(request);
});
app.register(CheckoutService.class, () -> new CheckoutService(new InMemoryLoans()));
app.map("POST /loans", request -> app.get(CheckoutService.class).borrow(request.user(), request.body()));
app.run(new Request("POST", "/loans", "Maya", "The Lighthouse Keeper"));
}
started: listening for requests
middleware: POST /loans from Maya
router: POST /loans goes to its endpoint
container: made a CheckoutService
repository: loan 1 saved
201 Loan 1: Maya, The Lighthouse Keeper
from dataclasses import dataclass
@dataclass
class Request:
method: str
path: str
user: str
body: str
@dataclass
class Response:
status: int
body: str
class InMemoryLoans:
def __init__(self):
self.count = 0
def add(self, member, title):
self.count += 1
print(f"repository: loan {self.count} saved")
return self.count
class CheckoutService:
def __init__(self, loans):
self.loans = loans
def borrow(self, member, title):
return Response(201, f"Loan {self.loans.add(member, title)}: {member}, {title}")
class MiniFramework:
"""The framework: it calls the parts you wrote, in its own order."""
def __init__(self):
self.started_listeners = []
self.middleware = []
self.routes = {}
self.recipes = {}
def on_started(self, listener):
self.started_listeners.append(listener)
def use(self, step):
self.middleware.append(step)
def map(self, route, endpoint):
self.routes[route] = endpoint
def register(self, kind, make):
self.recipes[kind] = make
def get(self, kind):
print(f"container: made a {kind.__name__}")
return self.recipes[kind]()
def run(self, request):
for listener in self.started_listeners:
listener()
handler = self.route
for step in reversed(self.middleware):
handler = (lambda step, next: lambda r: step(r, next))(step, handler)
response = handler(request)
print(f"{response.status} {response.body}")
def route(self, request):
print(f"router: {request.method} {request.path} goes to its endpoint")
return self.routes[f"{request.method} {request.path}"](request)
# The app: the parts you write.
def log_request(request, next):
print(f"middleware: {request.method} {request.path} from {request.user}")
return next(request)
app = MiniFramework()
app.on_started(lambda: print("started: listening for requests"))
app.use(log_request)
app.register(CheckoutService, lambda: CheckoutService(InMemoryLoans()))
app.map("POST /loans", lambda request: app.get(CheckoutService).borrow(request.user, request.body))
app.run(Request("POST", "/loans", "Maya", "The Lighthouse Keeper"))
started: listening for requests
middleware: POST /loans from Maya
router: POST /loans goes to its endpoint
container: made a CheckoutService
repository: loan 1 saved
201 Loan 1: Maya, The Lighthouse Keeper
class InMemoryLoans {
#count = 0;
add(member, title) {
this.#count++;
console.log(`repository: loan ${this.#count} saved`);
return this.#count;
}
}
class CheckoutService {
constructor(loans) { this.loans = loans; }
borrow(member, title) { return { status: 201, body: `Loan ${this.loans.add(member, title)}: ${member}, ${title}` }; }
}
// The framework: it calls the parts you wrote, in its own order.
class MiniFramework {
#startedListeners = [];
#middleware = [];
#routes = new Map();
#recipes = new Map();
onStarted(listener) { this.#startedListeners.push(listener); }
use(step) { this.#middleware.push(step); }
map(route, endpoint) { this.#routes.set(route, endpoint); }
register(name, make) { this.#recipes.set(name, make); }
get(name) {
console.log(`container: made a ${name}`);
return this.#recipes.get(name)();
}
run(request) {
for (const listener of this.#startedListeners) { listener(); }
const handler = this.#middleware.reduceRight((next, step) => (r) => step(r, next), (r) => this.#route(r));
const response = handler(request);
console.log(`${response.status} ${response.body}`);
}
#route(request) {
console.log(`router: ${request.method} ${request.path} goes to its endpoint`);
return this.#routes.get(`${request.method} ${request.path}`)(request);
}
}
// The app: the parts you write.
const app = new MiniFramework();
app.onStarted(() => console.log("started: listening for requests"));
app.use((request, next) => {
console.log(`middleware: ${request.method} ${request.path} from ${request.user}`);
return next(request);
});
app.register("CheckoutService", () => new CheckoutService(new InMemoryLoans()));
app.map("POST /loans", (request) => app.get("CheckoutService").borrow(request.user, request.body));
app.run({ method: "POST", path: "/loans", user: "Maya", body: "The Lighthouse Keeper" });
started: listening for requests
middleware: POST /loans from Maya
router: POST /loans goes to its endpoint
container: made a CheckoutService
repository: loan 1 saved
201 Loan 1: Maya, The Lighthouse Keeper
interface LibraryRequest { method: string; path: string; user: string; body: string; }
interface LibraryResponse { status: number; body: string; }
type Handler = (request: LibraryRequest) => LibraryResponse;
type Middleware = (request: LibraryRequest, next: Handler) => LibraryResponse;
type Key<T> = abstract new (...args: never[]) => T;
class InMemoryLoans {
private count = 0;
add(member: string, title: string): number {
this.count++;
console.log(`repository: loan ${this.count} saved`);
return this.count;
}
}
class CheckoutService {
private readonly loans: InMemoryLoans;
constructor(loans: InMemoryLoans) { this.loans = loans; }
borrow(member: string, title: string): LibraryResponse {
return { status: 201, body: `Loan ${this.loans.add(member, title)}: ${member}, ${title}` };
}
}
// The framework: it calls the parts you wrote, in its own order.
class MiniFramework {
private readonly startedListeners: (() => void)[] = [];
private readonly middleware: Middleware[] = [];
private readonly routes = new Map<string, Handler>();
private readonly recipes = new Map<Key<unknown>, () => unknown>();
onStarted(listener: () => void): void { this.startedListeners.push(listener); }
use(step: Middleware): void { this.middleware.push(step); }
map(route: string, endpoint: Handler): void { this.routes.set(route, endpoint); }
register<T>(key: Key<T>, make: () => T): void { this.recipes.set(key, make); }
get<T>(key: Key<T>): T {
console.log(`container: made a ${key.name}`);
return this.recipes.get(key)!() as T;
}
run(request: LibraryRequest): void {
for (const listener of this.startedListeners) { listener(); }
const handler = this.middleware.reduceRight<Handler>((next, step) => (r) => step(r, next), (r) => this.route(r));
const response = handler(request);
console.log(`${response.status} ${response.body}`);
}
private route(request: LibraryRequest): LibraryResponse {
console.log(`router: ${request.method} ${request.path} goes to its endpoint`);
return this.routes.get(`${request.method} ${request.path}`)!(request);
}
}
// The app: the parts you write.
const app = new MiniFramework();
app.onStarted(() => console.log("started: listening for requests"));
app.use((request, next) => {
console.log(`middleware: ${request.method} ${request.path} from ${request.user}`);
return next(request);
});
app.register(CheckoutService, () => new CheckoutService(new InMemoryLoans()));
app.map("POST /loans", (request) => app.get(CheckoutService).borrow(request.user, request.body));
app.run({ method: "POST", path: "/loans", user: "Maya", body: "The Lighthouse Keeper" });
started: listening for requests
middleware: POST /loans from Maya
router: POST /loans goes to its endpoint
container: made a CheckoutService
repository: loan 1 saved
201 Loan 1: Maya, The Lighthouse Keeper
Look at the app's part: five calls that hand the framework things (a listener, a middleware, a recipe, a route) and one, Run, that hands over control. From then on the framework decides what runs, and when. Nothing in the app calls the endpoint or the middleware; the framework does.
Where the languages differ. The real frameworks are much bigger, but they're made of these same pieces. C#, Java and TypeScript look services up by their type; JavaScript by name. Java writes the framework's helper classes as static nested classes, as compact Java files need.
The map: a pattern at every step
Here is the same request again, step by step, with the pattern behind each one and where this course taught it:
| Step | What happens | The pattern | Where you met it |
|---|---|---|---|
| Start-up | one call, Run, starts dozens of parts in order |
Facade | Pass 1, Facade |
| "Started" | the framework tells whoever signed up | Observer | Pass 1, Observer; Pass 3, events |
| The pipeline | each middleware answers the request or passes it on | Chain of Responsibility, as middleware | Pass 3; Middleware |
| Routing | the address picks the endpoint from a table | A dictionary of functions | Pass 1, Factories the Modern Way |
| The container | makes the service the endpoint asks for, with its parts | Dependency injection, a factory | Dependency Injection, Containers |
| The endpoint | takes the request, asks the model, picks the response | MVC's controller | MVC |
| The data | loans saved and found through one promise | Repository | Repository |
| The response | drawn as a page or as data, whichever was asked for | Strategy (one way of drawing, swapped) | Pass 2, Strategy; MVC's views |

Don't call us, we'll call you
There's one more idea in that program, and it's the one that makes a framework a framework. With a library, your code is in charge: you call Math.Max, or a date library's AddDays, when you want. With a framework, the framework is in charge: it runs, and it calls your code (your endpoint, your middleware, your constructor) when it decides to. Control has been turned around, which is why it's called inversion of control, and nicknamed "don't call us, we'll call you".
Inside, the framework's Run is a Template Method from Pass 2 in its function form: the framework fixes the steps and their order (start, tell the listeners, pass through the middleware, route, respond), and you fill in the steps with your own code. That's also why a framework's container (an inversion of control container) is the one that says new: it's the framework doing the calling.
What this looks like in a framework
Here is the library's start-up file in each framework, with each line labeled by the pattern it uses. These aren't run here: each needs its framework's project around it. Versions checked on 2026-11-01.
// ASP.NET Core 10, Program.cs: the composition root.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(new LibraryDatabase("riverside-db")); // container: one for the app
builder.Services.AddScoped<ILoanRepository, DatabaseLoans>(); // Repository, one per request
builder.Services.AddScoped<CheckoutService>(); // dependency injection
builder.Services.AddControllers(); // MVC controllers
var app = builder.Build();
app.Lifetime.ApplicationStarted.Register(() => app.Logger.LogInformation("started")); // Observer
app.UseAuthentication(); // middleware (Chain of Responsibility)
app.UseAuthorization(); // middleware
app.MapControllers(); // routing: address to controller
app.Run(); // Facade: one call starts it all
// Spring Boot 4.1: @SpringBootApplication finds the app's parts, and run(...) starts it all (Facade).
// @Service and @Repository classes go in the container; @RestController classes are MVC
// controllers, routed by @PostMapping; filters are the middleware; an event listener hears "started".
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
@SpringBootApplication
public class LibraryApplication {
public static void main(String[] args) {
SpringApplication.run(LibraryApplication.class, args);
}
@EventListener(ApplicationReadyEvent.class) // Observer
public void started() {
System.out.println("started");
}
}
# FastAPI 0.162: the app object is the framework; decorators register your code for it to call.
from contextlib import asynccontextmanager
from fastapi import Depends, FastAPI
from library import CheckoutService, get_checkout
@asynccontextmanager
async def lifespan(app: FastAPI):
print("started") # runs when the app starts (an Observer-style hook)
yield
app = FastAPI(lifespan=lifespan)
@app.middleware("http") # middleware (Chain of Responsibility)
async def log_request(request, call_next):
return await call_next(request)
@app.post("/loans") # routing: address to endpoint
def borrow(member: str, title: str, checkout: CheckoutService = Depends(get_checkout)): # dependency injection
return checkout.borrow(member, title) # the endpoint as controller, asking the model
// Express 5.3: the start file is the composition root, by hand.
import express from "express";
import { CheckoutService, DatabaseLoans, LibraryDatabase } from "./library.js";
const checkout = new CheckoutService(new DatabaseLoans(new LibraryDatabase("riverside-db"))); // DI by hand, Repository
const app = express();
app.use(express.json()); // middleware (Chain of Responsibility)
app.post("/loans", (req, res) => { // routing: address to endpoint
res.status(201).json(checkout.borrow(req.body.member, req.body.title)); // the endpoint as controller
});
app.listen(3000, () => console.log("started")); // one call starts it; a listener hears "started"
// NestJS 12.3, main.ts: NestFactory makes the app from its module (a factory, then the container).
import { NestFactory } from "@nestjs/core";
import { LibraryModule } from "./library.module";
async function start(): Promise<void> {
const app = await NestFactory.create(LibraryModule); // the container makes every provider
app.enableShutdownHooks(); // lifecycle hooks: Observer
await app.listen(3000); // Facade: one call starts it all
console.log("started");
}
start();
Finding your way around a new framework
On your first day with a new framework, ask five questions, in this order. Each one is a pattern from this pass, so you know what the answer will look like:
- Where's the composition root? The start-up file (
Program.cs, the@SpringBootApplicationclass,main.py,app.js,main.ts), where the parts are registered and the app is started. - What's in the pipeline, and in what order? The middleware: sign-in, logging, errors. A request that's refused before your code runs was stopped here.
- Where are the routes? The table, or the decorators and annotations, that map each address to its endpoint.
- Where are the controllers? The endpoints, each of which should be short: take the request, ask the model, answer.
- Where are the repositories? The one place each kind of data is saved and found.
When something happens "by magic", one of these five did it.
Check yourself
2 questions to try on the lesson page.
So what
A framework isn't magic; it's the patterns of this course, assembled, with one twist: it calls your code. Follow one request through and name what it meets, and a framework you've never seen becomes a map you already know how to read.