Why the Fastest Code Starts by Doubting Itself
Hatched by Kai Nguyen
Apr 20, 2026
10 min read
8 views
82%
The hidden discipline behind speed
What if the fastest way to make software faster is not to trust it more, but to question it earlier?
That sounds backwards. Speed is usually framed as an optimization problem, a hunt for indexes, shortcuts, and clever tricks. But beneath the surface, the deeper pattern is not cleverness. It is selectivity. Good systems, whether they are SQL engines or Python programs, become fast when they stop doing unnecessary work and start making their assumptions explicit.
That is the strange common ground between query optimization and assertions. One is about persuading a database to do less work. The other is about persuading your code to admit when its logic is broken. In both cases, the real enemy is not complexity itself, but uncontrolled work: scanning too much, calculating too much, believing too much, and discovering mistakes too late.
The deeper question connecting these ideas is this: How do you design systems that are both fast and trustworthy without confusing the two?
The answer is not to eliminate checks. It is to move them to the right place, where they are cheap, precise, and revealing.
Speed is not doing things quickly. It is avoiding the wrong things
Many developers think performance is about making operations faster. But the most powerful optimization is often more radical: avoid doing the operation at all.
In SQL, this is the logic behind sargable queries. If a query can use an index, the database can jump directly to the relevant rows instead of scanning the entire table. But certain habits quietly destroy that advantage. Wrap an indexed column in arithmetic, use a leading wildcard, or apply negation in the wrong place, and you may force the engine to inspect far more data than necessary. The query still works, but it has lost its selectivity.
That idea generalizes beautifully. A fast system is one that preserves the ability to narrow the search space early. A slow system keeps forcing itself to reconsider everything.
Think of it like finding a book in a library. If the catalog is useful, you go straight to the shelf. If not, you walk every aisle. The difference is not just speed. It is whether the system can constrain reality before it spends energy exploring it.
Assertions play a similar role in code. They are not there to make programs more robust by brute force. They are there to make assumptions visible. An assertion says: this should already be true here. If it is not, something upstream has gone wrong, and I want to know now.
That is a powerful kind of efficiency. Instead of allowing a bad state to propagate until it causes a mysterious downstream failure, the assertion compresses the investigation window. It turns a vague bug into a specific breach of expectation.
The fastest systems are not the ones that work the hardest. They are the ones that know what not to examine, what not to repeat, and what not to tolerate.
The shared logic of indexes and assertions
At first glance, indexes and assertions live in different worlds. One belongs to database tuning. The other belongs to Python debugging and testing. But both are forms of structural honesty.
An index is a promise about structure. It tells the query planner where useful order already exists. The database does not need to infer everything from scratch; it can follow a map. An assertion is a promise about state. It tells the runtime what must already be true before the next step can proceed.
Both are premised on the same insight: the system should not pay repeatedly for facts that are already known.
A poorly written SQL query may force the engine to calculate a transformation on every row, sort more than necessary, or filter too late. That is like a program that waits until the end to discover that its inputs were malformed. By then, the damage is done. The system has already expended effort on bad premises.
Assertions stop that pattern during development. They act like a watchdog for invariants, catching programmer errors as soon as possible. In a test suite, they become a compact language for expressing expectations. In production, they are typically disabled because their purpose is not to handle user errors, but to expose mistakes in the codebase itself.
This distinction matters. There is a difference between a system that can recover from external uncertainty and a system that merely hopes internal logic is sound. Assertions are for internal truth, not external negotiation. SQL indexing is similar. It is not a patch for bad data modeling or a substitute for a sane schema. It is a way to make the right path cheaper once the structure is already in place.
That is why the strongest codebases, like the strongest databases, are built on explicit boundaries:
- Preconditions are checked before work begins.
- Invariants are monitored while work proceeds.
- Expensive operations are reserved for when they are truly needed.
- Irrelevant paths are ruled out early.
This is not just good engineering. It is a philosophy of attention.
The real tension: trust versus verification
There is a subtle trap here. If speed comes from early filtering and explicit assumptions, why not sprinkle checks everywhere? Why not validate everything constantly, inside every loop, on every row, in every function?
Because verification itself has a cost. The art is not to maximize checking. It is to place checking where it has the highest diagnostic value at the lowest operational cost.
SQL optimization reveals the cost side of this tradeoff. Unnecessary sorting, grouping, calculations, and function calls all consume time and memory. Query planners are constantly balancing the need to answer correctly against the need to answer efficiently. A query that looks elegant in syntax can be expensive in execution if it obscures the access path.
Assertions reveal the same tradeoff from the other direction. They are excellent at catching programmer mistakes, documenting intent, and flagging broken assumptions. But they are not a substitute for user input validation, error handling, or business logic. If you use them to guard against normal external failures, you may accidentally remove your safety net in production, because assertions can be turned off with optimization flags.
That means the real design question is not, “Should we check?” It is, “What kind of uncertainty are we dealing with, and where should the check live?”
Here is a useful mental model:
- External uncertainty belongs to explicit error handling.
- Internal inconsistency belongs to assertions.
- Structural inefficiency belongs to indexing, query rewriting, and avoiding unnecessary work.
When developers confuse these categories, systems become either brittle or bloated. If everything is treated as a runtime surprise, the code gets defensive and slow. If everything is treated as guaranteed, the code becomes fragile and misleading.
The best systems are selective. They do not check everything everywhere. They check the right thing at the right layer.
A practical framework: move uncertainty to the edge
The shared lesson of SQL optimization and assertions can be stated simply: push uncertainty outward, push certainty inward.
In database terms, this means shaping queries so that the engine can narrow the candidate set as early as possible. Use predicates that are friendly to indexes. Filter before sorting when you can. Keep computations off indexed columns when possible. Avoid forcing the database to treat a precise lookup like a blind search.
In program design, it means defining and defending invariants as early as possible. Validate inputs at the boundary. Assert internal truths after transformations. Make your assumptions explicit so that the code can fail close to the source of the problem.
This principle has a surprising elegance. It suggests that good engineering is not about adding more intelligence to every step. It is about arranging the system so that later steps inherit less ambiguity.
Consider a data pipeline that receives user records, transforms them, and writes them to a warehouse. If the pipeline validates shape, type, and mandatory fields at ingestion, then downstream transformations can be simpler and faster. If the warehouse query is written to exploit available indexes, then reporting becomes cheaper and more reliable. If assertions protect invariants inside transformation functions, then accidental regressions are detected before bad data spreads.
The same pattern appears in a Python application. Parse and validate external input once. Assert that internal objects obey the contract you expect. Use test assertions to encode behavior that must never drift. Let production code handle real failures with normal exception paths, not with hidden assumptions that only exist when debugging is convenient.
Robustness is not achieved by checking more things. It is achieved by making fewer things uncertain.
That is why the connection between performance tuning and assertions is more profound than it first appears. Both are methods of reducing the domain of the problem before it becomes expensive.
Why this matters beyond code
This pattern is not limited to software. It describes a general approach to cognition and decision making.
People often think rigor means scrutinizing every possibility equally. In practice, rigor means knowing which uncertainties matter at which stage. A surgeon does not spend the operating room debating every possible diagnosis. The diagnosis should have been narrowed before that point. A strong legal argument does not introduce every fact at once. It front-loads the facts that matter and filters away the rest.
Software just makes this logic visible.
A sargable query is persuasive because it respects the shape of the problem. It asks the database to use what it already knows. An assertion is persuasive because it respects the shape of correctness. It names what must be true before the program proceeds. In both cases, the system becomes better not by being more generic, but by being more committed to a structure.
This also explains why both practices can be misunderstood. A novice sees an assertion as a defensive line of code. A novice sees an index as a magic speed button. But mature engineering recognizes that both are contracts. They work only when the surrounding design is coherent.
An assertion that checks nonsense does not create reliability. An index on the wrong column does not create performance. The point is not the tool alone. The point is whether the tool reinforces the architecture of truth and selectivity.
That is the larger lesson. Systems become fast and trustworthy when they do not merely execute, but exclude. They exclude irrelevant rows. They exclude impossible states. They exclude delayed discovery.
Key Takeaways
- Optimize by reducing scope, not by adding effort. The fastest systems are the ones that narrow the search space early.
- Use assertions to defend internal truth, not to manage external uncertainty. Assertions should expose programmer mistakes, while errors and exceptions handle real-world input and failure.
- Write queries that preserve index usefulness. Avoid wrapping indexed columns in operations that force unnecessary scanning or prevent the planner from using available structure.
- Move validation to the edge, invariants to the center. Check external data at the boundary, and use assertions inside the system to protect assumptions.
- Treat performance and correctness as allies. Both improve when you make the system more selective about what it evaluates.
The real optimization is epistemic
The deepest connection between SQL tuning and assertions is not technical, but epistemological. Both are about how a system knows what it knows.
A database with a good index knows how to find relevant data without pretending every row is equally likely. A program with good assertions knows which internal truths should never be questioned silently. Both reject the fantasy that every step should be equally open ended. They replace brute force with structure.
That is why the most powerful optimizations often feel like acts of humility. They admit that not every possibility deserves equal treatment. They admit that some facts should be established before work begins. They admit that the cost of waiting for certainty is often worse than the cost of being explicit early.
So the next time you write a query or a check, ask a deeper question: Am I helping the system do less unnecessary work, or am I merely making it work harder under a nicer name?
The best code does not just run. It knows where to stop guessing.
Sources
Hatch New Ideas with Glasp AI 🐣
Glasp AI allows you to hatch new ideas based on your curated content. Let's curate and create with Glasp AI :)
Start Hatching 🐣