DEV Community

Cover image for Instagram Couldn't Safely Reload Its Django Monolith. Import Side Effects Were Why
Gabriel Anhaia
Gabriel Anhaia

Posted on Edited on AI-assisted

Instagram Couldn't Safely Reload Its Django Monolith. Import Side Effects Were Why


You change one line in one view. The dev server throws away every module it has loaded and starts over. In 2019 that cost Instagram's engineers more than 20 seconds per restart, sometimes closer to a minute, on a codebase their PyCon talk that year called a ["million-LOC, thousand endpoint Django application"](https://pycon-archive.python.org/2019/schedule/presentation/372).

The obvious fix is to reload only what changed. Instagram's engineering blog explained why they couldn't: "because imports can have arbitrary side effects, there is no safe way to incrementally reload our server." That sentence is from "Python at Scale: Strict Modules", published October 17, 2019, the third post in their Python-at-scale series. The story of what they built next runs through Meta's Cinder fork and ends in a keyword that shipped in Python 3.15.0 on October 9, 2026. It also leaves you with a design rule you can apply this afternoon.

What "importing does things" looked like

The post walks through ordinary module-level code. A regex compiled at the top of a file. A @route decorator that registers a view in a global URL map the moment the module is imported. A config value fetched from a network service at module scope, so that if the config service is down, the web server can't even start. A translated copy of the post also preserves an import chain twelve modules deep that ended up using a service before it was initialized.

Here is that shape in a few lines. The helper modules are hypothetical; the pattern is the one the post describes:

# orders/views.py: importing this file does work
import re

from app.config import fetch_remote_config
from app.routing import route

SKU_RE = re.compile(r"^[A-Z]{3}-\d{4}$")
CONFIG = fetch_remote_config()   # network I/O at import

@route("/orders")                # mutates a global registry
def list_orders(request):
    ...
Enter fullscreen mode Exit fullscreen mode

Each line looks harmless on its own. Together they turn import orders.views into a program that runs every time anything imports the file, in whatever order the import graph happens to produce. The post makes that second point directly: import order is not set anywhere explicit, it falls out of the whole system's imports, and it can differ depending on the entry point. So a test runner, a management command and the web server can each see a different order, and code that silently depends on one of them breaks under the others.

That is why reload was unsafe. Reloading one module re-runs its top-level code. If that code registers a route, you now have it twice, or once pointing at a stale function. If it opened a connection, you have two. The only reliable way back to a known state was a full restart.

A long row of black dominoes on a cream background, the first one tipped by a small burnt-orange import arrow
One import, and everything downstream of it runs.

Strict modules: make the import checkable

Instagram's answer was opt-in. You put __strict__ = True at the top of a module, and a custom loader takes over for that file. Per the post, the loader parses the source, "performs abstract interpretation on the loaded code to analyze it", transforms the AST, and compiles it. The analysis rejects module-level code that has side effects or does I/O. A translation of the second half spells out the boundaries:

  • Defining a function that talks to the network is fine. Calling it at module level is not.
  • Side-effect-free dynamic code is allowed, such as decorators that don't mutate global state and dictionary comprehensions that build constants.
  • Imports from non-strict modules are treated as unsafe, apart from known-safe standard library functions.
  • Strict modules and the classes in them are immutable once created. Attributes assigned in __init__ go into __slots__, so nothing bolts extra state onto an instance later.

The post described all of this as experimental: a working prototype, early in its production rollout. It also pointed at what a side-effect-free module would make possible later, such as lazy module-level execution and faster imports of unchanged modules. What a strict module guarantees: importing it can't touch the network, register anything globally, or depend on who imported first. Reloading it means running pure definitions again.

Lazy imports: attack the same problem from the other end

Strict modules restrict what an import may do. The next project changed when an import happens at all. In June 2022, Meta's Germán Méndez Bravo wrote up Lazy Imports in Cinder, Meta's CPython fork. An import binds a deferred object and loads the module only when the name is first used. The numbers he reports for Instagram Server: startup had been loading about 28,000 modules, and lazy imports loaded about 12x fewer. Reload time on development servers dropped roughly 70% at p50 and 60% at p90. Circular import errors went from about 80 a day to zero.

Then came the upstream debate. PEP 690, by Méndez Bravo and Carl Meyer, proposed making lazy imports an opt-in, interpreter-wide mode. The Steering Council rejected it on December 2, 2022, with the concern that it would create "a split in the community over how imports work": code that relies on import-time execution would behave differently under a global switch.

The idea came back as explicit syntax. PEP 810, whose authors include Pablo Galindo Salgado, Méndez Bravo and Dino Viehland, was accepted on November 3, 2025, and is now Final for Python 3.15:

lazy import json
lazy from orders.adapters import PostgresOrderRepo
Enter fullscreen mode Exit fullscreen mode

The lazy form is allowed only at module level, not inside functions, class bodies or try blocks, and lazy from x import * is a syntax error. A __lazy_modules__ list lets a library opt specific imports in while staying eager on older Pythons, and -X lazy_imports or PYTHON_LAZY_IMPORTS changes the default for a whole process. The PEP's motivation says that for command-line tools, lazy imports "can reduce startup time by 50-70% in practice", and it lists Meta's Cinder write-ups separately among its real-world examples.

Notice what lazy does not do. The PEP says reification "imports the module at that point in the program." If the module fetches config over the network at top level, that fetch still happens. It just happens on the first request that touches the name instead of at boot. A side effect you could at least see at startup becomes one that fires in the middle of a handler. Lazy imports pay off most on modules that were already safe to import.

The rule: importing a module should do nothing

Both projects converge on the same property. A module whose top level only defines things can be imported in any order, reloaded, imported lazily and imported by a test with no setup. A module that does things at the top level fights all four.

So keep module scope to definitions: functions, classes, constants, type aliases. Keep these out of it:

  • Network or database calls, including "just read the config."
  • Opening connections, pools or clients.
  • Registering into anything global: routes, signal handlers, plugin registries.
  • Reading environment variables into module-level values that later code treats as fixed.

The core of an application is where this matters most, because it is the code you most want to import cheaply, from tests, scripts and workers. Written against a port, it needs nothing from the outside world to load:

# orders/core.py: importing this does nothing
from dataclasses import dataclass
from typing import Protocol

class OrderRepo(Protocol):
    def list_open(self) -> list[str]: ...

@dataclass(frozen=True)
class ListOpenOrders:
    repo: OrderRepo

    def __call__(self) -> list[str]:
        return self.repo.list_open()
Enter fullscreen mode Exit fullscreen mode

A test imports it and runs it with a fake, and nothing else happens:

from orders.core import ListOpenOrders

class FakeRepo:
    def list_open(self) -> list[str]:
        return ["ORD-1"]

def test_lists_open_orders() -> None:
    assert ListOpenOrders(FakeRepo())() == ["ORD-1"]
Enter fullscreen mode Exit fullscreen mode

A cream workbench with small black port sockets and burnt-orange adapter plugs laid out unconnected, one hand-drawn wiring diagram beside them
Definitions at import time. Connections happen in one place, later.

One composition root, called once

The side effects still have to live somewhere. Put them in one function that runs at startup, in an order you wrote down. That function is the composition root: it reads settings, builds adapters, hands them to the core and registers routes.

# main.py: the one place that touches the world
from fastapi import FastAPI

from orders.adapters import PostgresOrderRepo
from orders.core import ListOpenOrders
from settings import load_settings

def create_app() -> FastAPI:
    settings = load_settings()          # I/O, here, once
    repo = PostgresOrderRepo(settings.database_url)
    list_open = ListOpenOrders(repo)

    app = FastAPI()

    @app.get("/orders")
    def list_orders() -> list[str]:
        return list_open()

    return app
Enter fullscreen mode Exit fullscreen mode

The @app.get decorator still registers a route, but it runs when create_app() is called, against an app object that function owns. Nothing is registered at import. FastAPI is incidental here; serve it with Uvicorn's --factory flag, which treats the target as "a () -> <ASGI app> callable", and the same applies to a Django AppConfig.ready() or a Flask app factory.

What you get back maps onto Instagram's list. Import order stops being load-bearing, because the only order that matters is the sequence of lines in create_app. Reload stays safe, because re-importing orders.core re-runs definitions. A config outage fails one function with a clear traceback instead of breaking an import twelve modules away. And lazy import becomes a free speed-up rather than a way to move a network call into a request handler.

To find the modules in your own codebase that do work on import, CPython's -X importtime flag prints how long each import took: run python -X importtime -c "import orders.views" and start with the entries whose self time stands out.


If this was useful

Hexagonal Architecture in Python is built around the idea at the end of this post: a core that knows only its ports, adapters at the edge, and one place at startup that wires them. The book builds a single async FastAPI and SQLAlchemy 2 service five ways (Hexagonal, Clean, Onion, layered and vertical slice), then measures them, so you can see what each style does to boundaries like this one. Every listing runs from the free companion repo.

Hexagonal Architecture in Python by Gabriel Anhaia

Top comments (0)