---
title: "Sub-Second FastAPI Cold Start: The LazyRouter Pattern"
description: "Importing 70 routers at FastAPI startup is expensive. LazyRouter defers the import until the first hit and drops cold start to around 300ms."
author: "Anderson Henrique"
date: "2026-04-28T10:15:00Z"
updated: "2026-05-12T14:05:04.351982Z"
category: "technical"
tags: ["fastapi","python","performance","cold-start","architecture"]
canonical: "https://www.ntlabs.dev/en/blog/fastapi-cold-start-lazy-router"
locale: "en"
---

Our backend has more than 460 endpoints spread across 70 routers — auth, billing, content, Stripe integration, RAG, medical transcription, and so on. We used to import them all at the top of main.py the obvious way: app.include_router(auth_router), app.include_router(billing_router), and so forth. It worked. But cold start crossed 800ms and the first request after a deploy felt slow.

The diagnosis was simple: each import pulls in Pydantic models, SQLAlchemy dependencies, external clients. Even if the first request was to /health, Python had already paid the cost of loading everything.

The fix is what we internally call LazyRouter. Instead of importing the module at the top, we register only a path and a lazy function that performs the import on first call. The registration happens in a central registry.py, where each line is an entry saying "this path resolves to this module, imported on demand".

The effect was immediate: cold start dropped from 800ms to around 300ms. The first hit on a specific router pays a small import overhead (5-30ms), but the second is already cached. In practice this is invisible — Railway's health check responds quickly, the health gate releases traffic early, and real users never touch an endpoint that hasn't already been imported by some prior hit.

The takeaway: import is an expensive operation in Python, and the startup of a large FastAPI app feels that disproportionately. Deferring what can be deferred unblocks the critical path. It isn't a trick — just respecting the real cost of each import line.
