Every programmer lives through this drama at least once in their career. You join a new project: a scrappy startup from five years ago has grown into a profitable enterprise platform, business is booming, the engineering team has swelled to a hundred people, and the repository has ballooned to a million lines of code. Yet somehow, working in the codebase feels like defending a besieged fortress.
The simplest feature—say, adding a single discount field to the shopping cart calculation—turns into a two-week investigation involving leads from three departments. Engineers are terrified of touching legacy modules because any tweak triggers a cascade of failures across seemingly unrelated services in production. Builds break from circular dependencies, unit tests need three hundred lines of mock setup, and Lead Time to Production climbs exponentially.
In our industry, it is fashionable to blame "not enough microservices," "lack of Clean Architecture," or plain old "tech debt." Look under the hood of real-world mega-codebases, though, and the root cause runs deeper. In a thorough engineering conversation with Timur Shemsedinov on HowProgrammingWorks, Dmitry Kmaladze—a principal systems architect across major US tech corporations—dissects this fundamental crisis in modern industrial software engineering.
Let's take this apart piece by piece: why familiar OOP patterns and popular frameworks turn million-line codebases into an impassable swamp, how to structure architecture around a strict split between domain computation and system wiring, and why that discipline keeps engineers sane over decades.
The Crisis of Scale: Why Frameworks and Heavy OOP Break at a Million Lines
In smaller projects of 10,000 to 50,000 lines, tools like Spring Boot, NestJS, or ASP.NET Core feel like peak engineering elegance. You slap an @Injectable() annotation on a class, inject a database service into a controller constructor, drop @Entity() above a model, and ship a working app in a couple of days. Day-one velocity is off the charts.
Once a codebase crosses 500,000 lines and marches toward a million, however, that framework magic hits back hard. Three systemic traps emerge:
- Implicit coupling via transitive dependencies.
Classic OOP encourages bundling behavior and state together inside classes. Soon
OrderServiceimportsUserRepository,PaymentGateway,AuditLogger, andEmailNotificationService. Each of those pulls in dozens more services. Instead of a clean directed acyclic graph (DAG), your codebase turns into a dense hairball where every module is indirectly coupled to every other module. - Held hostage by framework fashion cycles. Every popular web framework follows trend cycles. Roughly every 3 to 5 years, a framework undergoes a major paradigm shift: maintainers deprecate old APIs, change decorator syntax, or swap out the underlying runtime altogether. If your core business rules (tax calculations, balance deductions, permission checks) are welded to framework classes, annotations, and interfaces, upgrading the stack means rewriting a million lines of code. In practice, nobody does that—so the project stays frozen on an ancient, vulnerable library version forever.
- Erosion of domain context. Open a typical enterprise service class and you will see a chaotic stew: right next to JWT token validation, it opens a PostgreSQL transaction, ships a request body to Elasticsearch, publishes a Kafka message, and hides three lines of actual discount math somewhere in the noise. We examined these degradation mechanics in Architectural Erosion: Why Vibe Coding Destroys Long-Lived Systems, where unchecked code generation rapidly multiplied coupling entropy.
When business logic is smeared thinly across network adapters and infrastructure calls, the system becomes unmanageable. The only way back to control is drawing a hard boundary at the architectural level.
Separation of Powers: Pure Domain vs. System Wiring
Dmitry Kmaladze's core architectural rule sounds deceptively simple: a software system's architecture must fundamentally separate domain computational logic (Domain Logic) from system wiring (System Wiring).
Engineering exploded-view diagram of a smartphone separating the central computational logic chip from the outer system wiring board.
Think of a modern smartphone as a physical analogy. Inside, there is a CPU core crunching video compression algorithms or cryptographic hashes. That processor does not care one bit where the bytes came from—whether over Wi-Fi, from flash storage, or from a user tapping the touchscreen. The processor is a pure computational engine.
Everything else in the phone—the motherboard, radio modules, PCIe lanes, power delivery—is the wiring system. Its sole job is to feed the right bytes into the chip on time and route the computed result out to the speaker or display. The motherboard never does algorithm math, and the chip has no idea which antenna vendor is soldered onto the board.
Your codebase needs the exact same boundary:
- Domain Core: Strictly pure, deterministic functions and immutable data structures. Zero I/O operations, zero network calls, zero database queries, zero system clock reads, and zero environment variable lookups. A module takes data in and returns a computed result;
- System Adapters: Thin, isolated modules that talk to the outside world—running a SQL query against PostgreSQL, publishing an event to RabbitMQ, or serializing a JSON response for a gRPC client. Adapters contain zero business rules;
- System Wiring (Composition Root): A dedicated space in the application where adapters are wired up to pure domain functions through explicit contracts.
Anatomy of a Pure Core: Deterministic Functions Unaware of Databases or Networks
Let's see how this looks in real TypeScript code. Suppose we are designing a critical checkout flow that calculates totals and checks eligibility for a corporate order.
In traditional enterprise code, a developer would create an OrderService and inject a database connection pool plus a logger via its constructor. With separated wiring, the domain core stays completely isolated:
// Listing 1. Pure domain business logic core (Domain Core)
// Notice: there is not a single external import in this file! No frameworks, no DB, no ORM.
export interface OrderItem {
readonly id: string;
readonly price: number;
readonly quantity: number;
}
export interface CustomerProfile {
readonly id: string;
readonly tier: 'standard' | 'premium' | 'vip';
readonly balance: number;
}
export interface DiscountPolicy {
readonly rate: number;
readonly maxCap: number;
}
export interface CalculationResult {
readonly subtotal: number;
readonly discountAmount: number;
readonly total: number;
readonly isEligible: boolean;
}
// Pure deterministic function: output depends strictly on input arguments
export function calculateOrderSettlement(
items: readonly OrderItem[],
customer: CustomerProfile,
policy: DiscountPolicy
): CalculationResult {
// 1. Compute cart subtotal
const subtotal = items.reduce((acc, item) => acc + item.price * item.quantity, 0);
// 2. Compute base discount based on customer tier
let rawDiscount = 0;
if (customer.tier === 'vip') {
rawDiscount = subtotal * policy.rate;
} else if (customer.tier === 'premium') {
rawDiscount = subtotal * (policy.rate * 0.5);
}
// 3. Apply maximum discount cap (maxCap)
const discountAmount = Math.min(rawDiscount, policy.maxCap);
const total = Math.max(0, subtotal - discountAmount);
// 4. Verify customer's financial eligibility
const isEligible = customer.balance >= total;
return {
subtotal,
discountAmount,
total,
isEligible,
};
}
Look closely at Listing 1. There are no async/await keywords, no exceptions thrown mid-calculation, and zero coupling to any library.
You can run this exact function in Node.js, compile it to WebAssembly for the browser, or drop it into a lightweight Cloudflare Worker. It is crystal clear: pass the same inputs, and you get the exact same output down to the last bit.
The Wiring Layer: Use Case Factories, Ports, and Isolated Assembly
Now comes the obvious question: if the function knows nothing about the outside world, who fetches its data from the database and persists the result to disk?
That is the job of the system wiring layer. In Kmaladze's architecture, it is built with Use Case Factories and I/O Ports:
// Listing 2. System wiring layer and use case factory (System Wiring)
// Here pure math is connected to infrastructure adapters.
import { calculateOrderSettlement, OrderItem, CustomerProfile, DiscountPolicy } from './domain-core';
// Storage port: an abstract contract with no tie to PostgreSQL or MongoDB
export interface OrderStoragePort {
loadCustomer(customerId: string): Promise<CustomerProfile>;
loadPolicy(): Promise<DiscountPolicy>;
commitTransaction(orderId: string, total: number): Promise<void>;
}
// Telemetry and logging port
export interface LoggerPort {
info(message: string, context?: Record<string, unknown>): void;
warn(message: string, context?: Record<string, unknown>): void;
}
// Use case factory: performs dependency wiring (Wiring)
export function createOrderCheckoutWorkflow(
storage: OrderStoragePort,
logger: LoggerPort
) {
// Returned workflow function: orchestrates the data flow
return async function executeCheckout(
orderId: string,
customerId: string,
items: readonly OrderItem[]
): Promise<{ success: boolean; total: number }> {
logger.info('Старт процедуры оформления заказа', { orderId, customerId });
// 1. Asynchronously fetch required data from infrastructure
const [customer, policy] = await Promise.all([
storage.loadCustomer(customerId),
storage.loadPolicy(),
]);
// 2. Delegate math to the pure domain logic function
const settlement = calculateOrderSettlement(items, customer, policy);
// 3. Branch control flow based on computation results
if (!settlement.isEligible) {
logger.warn('Отказ в оформлении: баланс клиента ниже требуемой суммы', {
customerId,
required: settlement.total,
balance: customer.balance,
});
return { success: false, total: settlement.total };
}
// 4. Persist side effects through the storage port
await storage.commitTransaction(orderId, settlement.total);
logger.info('Заказ успешно зафиксирован в базе данных', { orderId, total: settlement.total });
return { success: true, total: settlement.total };
};
}
Notice how clean the division of labor is in Listing 2:
executeCheckoutruns zero SQL queries and has no idea which table stores customers;- It acts purely as a dispatcher: it fetches structures through the port, passes them to
calculateOrderSettlement, checksisEligible, and triggers persistence; - Factory assembly happens in a single application entry point (
Composition Root). If the company decides tomorrow to swap PostgreSQL for KiviDB or ScyllaDB, the domain core does not change by a single character—only theOrderStoragePortimplementation changes.
Instead of dynamically looking up services in a global registry at runtime (Runtime Service Locator), factories rely on strict TypeScript static typing. If you forget to pass a logger or database adapter to a factory, the project simply refuses to compile. No surprise production crashes because a DI container failed to resolve a circular dependency at startup.
The Death of Mock Hell: Testing Business Logic Without Faking a Database
Ask any enterprise developer what they hate most, and you will hear the same answer: writing unit tests for business services.
In traditional architectures, unit testing feels like torture. To test a 5-line discount branch, you end up writing 80 lines of test-framework boilerplate: mocking repo.findOne, mocking the transaction manager, mocking the logger, and making sure every mock returns a promise in the right shape. Worse, the moment someone refactors a SQL query, the test breaks even though the business rules never changed. Your tests are verifying implementation details, not behavior.
With a pure core architecture, testing becomes genuinely pleasant:
- To test business logic, you need zero mocks. You create three plain objects in memory, pass them to
calculateOrderSettlement, and check the result with a simpleassert.strictEqual. The test runs in microseconds; - Testing the wiring layer (the use case factory) only needs trivial in-memory port stubs that return a fixed profile;
- Infrastructure adapters are verified with isolated integration tests against real containers via Testcontainers, testing honest SQL against a live database.
The testing pyramid finally stands right-side up: verifying hundreds of domain scenarios takes seconds in CI.
The Microservices Illusion and Conway's Law in Giant Codebases
When a monolithic codebase starts grinding to a halt, management often makes a bold call: "Let's split everything into microservices!" They hire DevOps engineers, set up Kubernetes, and slice the codebase into 50 tiny repositories.
If the original monolith suffered from tangled wiring and business logic, though, splitting it creates a disaster: a distributed monolith. The coupling never goes away—it just migrates from in-process function calls to unreliable HTTP/gRPC network hops. Now, instead of an instant compiler error, you deal with network latency, partial node failures, broken transactional integrity, and distributed tracing overhead.
Dmitry Kmaladze emphasizes that service boundaries should follow organizational structure (Conway's Law), not folder size.
If two teams modify the same business workflow every day, splitting their code across separate networked services only slows everyone down. Keeping the codebase in a single monorepo with strict module-boundary linters is far more reliable:
- Pure cores for different domains can sit in neighboring packages;
- They are forbidden from importing one another directly;
- Cross-domain interaction is wired together only at the top-level composition layer.
We previously examined the nature of long-term architectural choices in Reversible and Irreversible Architectural Decisions in the Era of Generative Code, highlighting how isolating the business core makes the surrounding tech stack completely reversible.
Practical Migration Path: Untangling Existing Legacy Code
You are probably thinking right now: "That all sounds great for a greenfield project. But we already have a million lines of ORM-and-decorator spaghetti! How do we survive?"
Whatever you do, do not declare a six-month feature freeze to rewrite everything from scratch (Second System Syndrome)—the business will never forgive you. Instead, migrate using the Strangler Fig Pattern:
- Freeze new logic in existing services. When a new business requirement arrives, forbid adding new methods to old database-coupled classes;
- Extract pure functions. Start by pulling out algorithmic chunks. Find the calculation formulas buried inside a giant method, move them to an import-free file, and cover them with simple unit tests;
- Define port interfaces. Use TypeScript contracts to declare the exact data that function needs from the database;
- Turn the old service into a thin adapter. Let the legacy service class simply fetch data through the existing ORM and delegate the math to your new pure function.
Step by step, your domain core crystallizes, shedding its infrastructure ballast while the codebase regains its flexibility and predictability.
No—pure functions don't need libraries to add numbers or transform objects. For networking tasks (JSON parsing, HTTP routing, connection pooling), you still use fast, battle-tested libraries (Fastify, Hono, pg), keeping them strictly inside your thin adapter layer.
Configure architectural linters (such as dependency-cruiser or ESLint's no-restricted-imports rule) in CI/CD to automatically block any commit where code inside the domain directory imports from infrastructure layers.

