Spaghetti Code: What It Is, Why It Happens and How to Fix It

Raghav Chamadiya8 min read
On this page

Spaghetti code is code with tangled control flow and tangled dependencies, where you cannot follow what one part does, or change it, without touching others. It is a kind of technical debt that builds up when a codebase grows without boundaries. This guide covers what causes spaghetti code, what it looks like in practice, how to see it in a repository with commands, and how to untangle it.

What is spaghetti code?

Spaghetti code is a codebase, file or function in which the paths through the program cross and loop back so often that no single thread can be pulled out. The name comes from the image of a plate of noodles: every strand touches every other strand.

Two kinds of tangle get the same name. The first is tangled control flow inside a function: deep nesting, flags that change meaning halfway down, early exits in odd places, and in older languages goto. The second is tangled dependencies between modules: A imports B, B imports C, C imports A, and a shared helper reaches into half the codebase.

Both make the same thing expensive: finding out what a change will break. It is a classic code smell, and the smell is the structure, not the style. Spaghetti code can be nicely formatted and still be spaghetti.

What causes spaghetti code?

Spaghetti code is rarely written on purpose. It accumulates through changes that each looked reasonable. The common causes:

  • Patches under deadline. A fix goes in where it is fastest to add, not where it belongs, and the next one builds on top of it.
  • No boundaries. Without a rule about which module may call which, every module ends up calling every other.
  • Shared mutable state. Globals, singletons and objects passed everywhere let any code change any data, so behavior depends on call order.
  • Copy instead of extract. Duplicated logic drifts apart, and a fix has to be repeated in each copy.
  • Features bolted onto a function. A function that started at ten lines gains a flag per request, and each flag adds a branch.
  • Nobody owns the structure. When no one looks at the whole graph, no one notices it going wrong. In Fowler's quadrant this is mostly reckless, inadvertent debt.

AI coding agents add to this when they work file by file: each change is locally fine, and the cross-file structure gets no review.

A spaghetti code example

The clearest example of dependency spaghetti is two modules that import each other. Here is a small Python case, then the same logic with the knot removed.

python
# orders.py
from billing import charge_customer

def place_order(order):
    order.status = "placed"
    charge_customer(order)          # billing does the work...

# billing.py
from orders import place_order      # ...and reaches back into orders

def charge_customer(order):
    if order.total > 500 and not order.verified:
        order.status = "held"
        place_order(order)          # re-enters orders to retry
    else:
        order.status = "paid"

Neither file can be read or tested alone, and importing either one first can fail with a partial module. The fix is to give the shared part a home and let billing return a result instead of calling back:

python
# order_status.py  (shared, depends on nothing)
PLACED, HELD, PAID = "placed", "held", "paid"

# billing.py  (depends only on order_status)
from order_status import HELD, PAID

def charge_customer(order) -> str:
    return HELD if order.total > 500 and not order.verified else PAID

# orders.py  (depends on billing, never the reverse)
from billing import charge_customer
from order_status import PLACED

def place_order(order):
    order.status = PLACED
    order.status = charge_customer(order)

The dependency now runs one way: orders to billing to order_status. The same idea fixes tangled control flow inside one function: replace nested conditions with early returns and give each branch a named helper.

python
# Tangled
def ship(o):
    if o:
        if o.paid:
            if not o.held:
                if o.address:
                    send(o)

# Flat
def ship(o):
    if not (o and o.paid and not o.held and o.address):
        return
    send(o)

What are the symptoms of spaghetti code?

The main symptom is that changes are slower and riskier than they should be. Teams report the same signs:

  • A small change breaks something in a part of the code the author never opened.
  • Nobody can explain a module without explaining three others first.
  • Tests need a large setup because a module cannot be built in isolation.
  • Bugs come back after being fixed, because the same logic lives in several places.
  • New engineers take weeks to make a first safe change.
  • Everyone avoids one particular file.

How to see spaghetti code in a codebase

You can measure tangle directly: look at the import graph and at function shape. A dependency graph shows cycles and over-central files that a file-by-file read hides. Four signals are worth checking.

1. Import cycles. A cycle means a group of files that cannot be understood or loaded independently. Each language has a tool; the circular dependency guide has tested commands for TypeScript, Python and Go.

2. Hub files. A file imported by a large share of the codebase is a place where any change fans out. Look for the file with the most dependents.

3. Long functions and deep nesting. Count branches and indentation levels. A function with many paths is hard to test, since each path needs its own case.

4. Coupling between modules. Files that always change together, even without importing each other, are coupled through hidden state or shared assumptions.

repowise builds one graph of files and symbols and scores each file for these structural problems:

bash
uv tool install repowise                  # or pipx / pip install repowise
repowise init                             # builds the graph and scores every file
repowise health                           # lowest-scoring files, top findings
repowise health --refactoring-targets     # per-file plans, including Break Cycle
repowise context src/billing.py --include callers   # who depends on this file
repowise serve                            # dashboard: Graph, Architecture, Coupling, Blast radius

repowise health --refactoring-targets lists plans per file. A Break Cycle plan names the smallest set of import edges to invert to break a runtime dependency cycle, and it only counts runtime imports, so type-only imports do not show up as false cycles. See the graph layer and code health docs for details.

How common is spaghetti code in real projects?

Very common, and mature projects are not exempt. We analysed 195 of the most-starred public repositories indexed on repowise.dev (November 2026): 253,688 production source files, each repo with 1,000+ GitHub stars, production code only.

MeasureResult
Repos with at least one circular import chain between files173 of 195 (89%)
Production files inside a circular import chain, pooled18.9% (47,896 of 253,688)
Files inside a cycle, median repo9.2%
Largest cycle, median repo16 files
Repos where the largest cycle holds 25% or more of the code27
Share of files importing the most-imported file, median repo19.6%
Repos with a file imported by 25% or more of the codebase68 of 194 (35%)
Python repos with a cycle51 of 51
Go repos with a cycle12 of 22

Scroll the table sideways to see every column.

Read these as structure, not as a verdict. These are file-level cycles, and barrel files in TypeScript and __init__.py re-exports create chains that are often harmless at runtime. A popular project with a cycle is not broken, and a hub file can be a deliberate public surface. The numbers tell you where to look first, and the question to ask is whether anyone chose the shape.

How do you fix spaghetti code?

Fix spaghetti code in small steps, with tests in place, one tangle at a time. A rewrite is rarely the answer: it throws away behavior you cannot yet describe. Refactoring keeps behavior fixed while the structure improves, and the clean code principles show what to aim for in each step.

  1. Pick where to start. Do not untangle everything. Start with the files that change often and score worst, since that is where the tangle costs you now. See refactoring priorities by impact per effort.
  2. Pin behavior with tests. Write characterization tests that record what the code does today, including the odd parts. Without them you cannot tell a refactor from a change.
  3. Break cycles first. A cycle blocks every other cleanup. Two standard moves: extract the shared part into a new module both sides import (as in the example above), or invert the dependency so the lower layer depends on an interface the higher layer implements.
  4. Shrink the hub. Split a file that everything imports into focused modules, and update importers to the narrower one. Keep a thin re-export for a release if the change is wide.
  5. Flatten long functions. Use early returns, extract a named function for each branch, and replace flag arguments with separate functions.
  6. Enforce the boundary. Add a check to CI that fails on a new cycle or a forbidden import, so the structure stays fixed once repaired. Our circular dependency guide shows the flags that make each tool fail the build.

Commit after each step, and keep each step small enough to review in one sitting. For tools that automate parts of this, see the best refactoring tools comparison.

Spaghetti code vs lasagna code and ravioli code

Spaghetti, lasagna and ravioli describe three ways code can be structured, and each has its own failure.

NameStructureFailure mode
SpaghettiNo clear structure, everything links to everythingCannot change one part without touching others
LasagnaMany strict layers stacked on one anotherA change must pass through every layer, and the layers hide where the work happens
RavioliMany small, self-contained piecesToo many tiny parts, and the system is hard to see as a whole

Scroll the table sideways to see every column.

Lasagna is the usual overcorrection: a team escapes spaghetti by adding layers, then finds each feature touches six of them. The goal is not a pasta type. It is clear boundaries with dependencies that run one way and as few layers as the problem needs.

FAQ

What is spaghetti code?
Spaghetti code is code with tangled control flow and dependencies, where you cannot follow or change one part without touching others. It shows up as deep nesting and long functions inside a file, and as import cycles and over-central files across a codebase. The name comes from the way the strands cross and loop like noodles on a plate.
What causes spaghetti code?
It builds up from changes made without a view of the whole structure: patches under deadline, no rules about which module may call which, shared mutable state, copied logic and features bolted onto existing functions. Each change is small and reasonable, so the tangle is rarely noticed until a change becomes risky.
How do you fix spaghetti code?
Pin current behavior with tests, then untangle in small steps. Break import cycles first by extracting a shared module or inverting a dependency, then split the file that everything imports, then flatten long functions with early returns and extracted helpers. Add a CI check so new cycles fail the build.
Why is spaghetti code bad?
It makes every change slower and riskier. You cannot predict what a change affects, tests need large setups, bugs return because logic is duplicated, and new engineers take longer to become productive. The cost shows up as time spent, not as a single failure.
How do you find spaghetti code in a repository?
Look at the import graph and at function shape: circular import chains, files imported by a large share of the codebase, long functions with deep nesting, and files that always change together. In repowise, repowise health ranks the lowest-scoring files and repowise health --refactoring-targets lists per-file plans, including Break Cycle for runtime import cycles.
What is the difference between spaghetti code and lasagna code?
Spaghetti code has no clear structure and everything links to everything. Lasagna code has many strict layers, so a change has to pass through each one. Ravioli code is many small self-contained pieces. Spaghetti is too little structure, and lasagna is often what a team builds in reaction to it.
Is spaghetti code the same as technical debt?
Spaghetti code is one form of technical debt. Technical debt also includes outdated dependencies, missing tests and dead code. Tangled structure is the form that most directly slows down change, which is why it is usually worth fixing before the others. See what is technical debt.