Skip to main content

FastAPI-compatible web framework with Rust HTTP core - 2-3x faster with Python 3.13 free-threading

Project description

TurboAPI Architecture

TurboAPI

The FastAPI you know. The speed you deserve.

PyPI version License Python 3.13+ Ask DeepWiki

The ProblemThe SolutionQuick StartBenchmarksAsync SupportMigration Guide


The Problem

You love FastAPI. The clean syntax. The automatic validation. The beautiful docs. But then you deploy to production, and the reality hits:

"Why is my simple API only handling 8,000 requests per second?"

You've optimized your database queries. Added caching. Switched to async. Still not fast enough. The bottleneck isn't your code—it's the framework itself.

Python's GIL (Global Interpreter Lock) means only one thread executes Python code at a time. JSON serialization happens in pure Python. HTTP parsing happens in pure Python. Every microsecond adds up.

The Solution

TurboAPI is FastAPI with a Rust-powered engine. Same API. Same syntax. 1.3-1.8x faster.

# This is all you change
from turboapi import TurboAPI as FastAPI

Everything else stays exactly the same.

TurboAPI Speedup

Why It's Faster

What FastAPI Does What TurboAPI Does Speedup
HTTP parsing in Python HTTP parsing in Rust (Hyper/Tokio) 3x
JSON with json.dumps() SIMD-accelerated JSON (simd-json) 2x
GIL-bound threading Python 3.13 free-threading 2x
dict-based routing Radix tree with O(log n) lookup 1.5x
Async via asyncio Async via Tokio work-stealing 1.2x

The result? Your existing FastAPI code runs faster without changing a single line of business logic.


Quick Start

Installation

pip install turboapi

Requirements: Python 3.13+ (free-threading recommended for best performance)

Hello World

from turboapi import TurboAPI

app = TurboAPI()

@app.get("/")
def hello():
    return {"message": "Hello World"}

app.run()

That's it. Your first TurboAPI server is running at http://localhost:8000.

Async Handlers (New!)

TurboAPI now supports true async with Tokio-powered execution:

from turboapi import TurboAPI
import asyncio

app = TurboAPI()

@app.get("/sync")
def sync_handler():
    return {"type": "sync", "message": "Fast!"}

@app.get("/async")
async def async_handler():
    await asyncio.sleep(0.001)  # Simulated I/O
    return {"type": "async", "message": "Even faster under load!"}

app.run()

Async handlers are automatically detected and routed through Tokio's work-stealing scheduler for optimal concurrency.

For Maximum Performance

Run with Python's free-threading mode:

PYTHON_GIL=0 python app.py

This unlocks the full power of TurboAPI's Rust core by removing the GIL bottleneck.


Benchmarks

Real numbers matter. Here's TurboAPI vs FastAPI on identical hardware:

Latest Benchmark Results

Endpoint TurboAPI FastAPI Improvement
Sequential Latency
GET / 0.76ms 1.05ms 1.4x faster
GET /benchmark/simple 0.61ms 0.81ms 1.3x faster
GET /benchmark/medium 0.61ms 0.77ms 1.3x faster
GET /benchmark/json 0.72ms 1.04ms 1.4x faster
Concurrent Latency
GET / 2.05ms 2.53ms 1.2x faster
GET /benchmark/json 2.17ms 3.90ms 1.8x faster

Throughput (requests/second)

Endpoint TurboAPI FastAPI Speedup
GET / (hello world) 19,596 8,336 2.4x
GET /json (object) 20,592 7,882 2.6x
GET /users/{id} (path params) 18,428 7,344 2.5x
POST /items (model validation) 19,255 6,312 3.1x

Async Handler Performance

Metric Sync Handler Async Handler Notes
Sequential (100 req) 0.66ms 0.76ms Similar performance
Concurrent (200 req) 108ms batch 139ms batch Sync faster for CPU-bound
I/O Wait (1ms sleep) 2.22ms 2.06ms Async wins for I/O

Key Insight: Use async handlers when you have actual I/O operations (database, network). For pure CPU work, sync handlers are slightly faster.

Run Your Own Benchmarks

# Quick benchmark
python benches/python_benchmark.py

# Full comparison with FastAPI
python tests/benchmark_comparison.py

# Async vs Sync comparison
python benches/async_comparison_bench.py

Async Support

How Async Works in TurboAPI

TurboAPI uses a hybrid async architecture:

┌─────────────────────────────────────────────────────────┐
│                Your Python Handlers                      │
│         @app.get("/sync")      @app.get("/async")       │
│         def handler():         async def handler():     │
├─────────────────────────────────────────────────────────┤
│              Handler Classification                      │
│   simple_sync │ body_sync │ simple_async │ body_async  │
├─────────────────────────────────────────────────────────┤
│              Tokio Runtime (Rust)                        │
│         Work-stealing scheduler • 14 workers            │
├─────────────────────────────────────────────────────────┤
│              pyo3-async-runtimes                         │
│     Python coroutines ↔ Rust futures conversion         │
└─────────────────────────────────────────────────────────┘

Handler Types

TurboAPI automatically classifies handlers for optimal dispatch:

Handler Type Description Use Case
simple_sync Sync, no body GET endpoints
body_sync Sync, with body POST/PUT without complex types
model_sync Sync, with model validation POST with dhi models
simple_async Async, no body GET with I/O operations
body_async Async, with body POST/PUT with I/O operations
enhanced Full Python wrapper Complex dependencies

When to Use Async

# Use sync for pure computation
@app.get("/compute")
def compute():
    result = sum(i * i for i in range(1000))
    return {"result": result}

# Use async for I/O operations
@app.get("/fetch-data")
async def fetch_data():
    async with aiohttp.ClientSession() as session:
        async with session.get("https://api.example.com/data") as resp:
            return await resp.json()

# Use async for database operations
@app.get("/users/{user_id}")
async def get_user(user_id: int):
    user = await database.fetch_one(query, values={"id": user_id})
    return {"user": user}

Migration Guide

TurboAPI is designed as a drop-in replacement for FastAPI. Here's how to migrate:

Step 1: Change Your Imports

# Before (FastAPI)
from fastapi import FastAPI, Depends, HTTPException, Query, Path
from fastapi.responses import JSONResponse, HTMLResponse
from fastapi.middleware.cors import CORSMiddleware

# After (TurboAPI)
from turboapi import TurboAPI as FastAPI, Depends, HTTPException, Query, Path
from turboapi.responses import JSONResponse, HTMLResponse
from turboapi.middleware import CORSMiddleware

Step 2: Update Your Models

TurboAPI uses dhi instead of Pydantic (it's API-compatible):

# Before (Pydantic)
from pydantic import BaseModel

# After (dhi)
from dhi import BaseModel

Step 3: Run Your App

# FastAPI way still works
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

# Or use TurboAPI's built-in server (faster)
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)

That's it. Your FastAPI app is now a TurboAPI app.


Feature Parity

Everything you use in FastAPI works in TurboAPI:

Feature Status Notes
Route decorators (@get, @post, etc.) Full parity
Path parameters With type coercion
Query parameters With validation
Request body (JSON) SIMD-accelerated
Response models Full support
Async handlers Tokio-powered
Dependency injection Depends() with caching
OAuth2 authentication Password & AuthCode flows
HTTP Basic/Bearer auth Full implementation
API Key auth Header/Query/Cookie
CORS middleware Rust-accelerated
GZip middleware Configurable
Background tasks Async-compatible
WebSocket HTTP upgrade support
APIRouter Prefixes and tags
HTTPException With custom headers
Custom responses JSON, HTML, Redirect, etc.

Real-World Examples

API with Authentication

from turboapi import TurboAPI, Depends, HTTPException
from turboapi.security import OAuth2PasswordBearer

app = TurboAPI(title="My API", version="1.0.0")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/users/me")
def get_current_user(token: str = Depends(oauth2_scheme)):
    if token != "secret-token":
        raise HTTPException(status_code=401, detail="Invalid token")
    return {"user": "authenticated", "token": token}

Async Database Access

from turboapi import TurboAPI
import asyncpg

app = TurboAPI()
pool = None

@app.on_event("startup")
async def startup():
    global pool
    pool = await asyncpg.create_pool("postgresql://localhost/mydb")

@app.get("/users/{user_id}")
async def get_user(user_id: int):
    async with pool.acquire() as conn:
        row = await conn.fetchrow("SELECT * FROM users WHERE id = $1", user_id)
        return dict(row) if row else {"error": "Not found"}

Request Validation

from dhi import BaseModel, Field
from typing import Optional

class CreateUser(BaseModel):
    name: str = Field(min_length=1, max_length=100)
    email: str = Field(pattern=r'^[\w\.-]+@[\w\.-]+\.\w+$')
    age: Optional[int] = Field(default=None, ge=0, le=150)

@app.post("/users")
def create_user(user: CreateUser):
    return {"created": True, "user": user.model_dump()}

CORS and Middleware

from turboapi.middleware import CORSMiddleware, GZipMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://yourapp.com"],
    allow_methods=["*"],
    allow_headers=["*"],
)

app.add_middleware(GZipMiddleware, minimum_size=1000)

Architecture

TurboAPI's secret is a hybrid architecture:

┌──────────────────────────────────────────────────────────┐
│              Your Python Application                      │
│           (exactly like FastAPI code)                     │
├──────────────────────────────────────────────────────────┤
│         TurboAPI (FastAPI-compatible layer)              │
│      Routing • Validation • Dependency Injection          │
├──────────────────────────────────────────────────────────┤
│           Handler Classification (Phase 3+4)             │
│   simple_sync │ body_sync │ simple_async │ body_async   │
├──────────────────────────────────────────────────────────┤
│            PyO3 Bridge (zero-copy)                       │
│       Rust ↔ Python with minimal overhead                 │
├──────────────────────────────────────────────────────────┤
│            TurboNet (Rust HTTP Core)                     │
│   • Hyper + Tokio async runtime (14 worker threads)     │
│   • SIMD-accelerated JSON (simd-json)                    │
│   • Radix tree routing                                   │
│   • Zero-copy response buffers                           │
│   • pyo3-async-runtimes for async handler support       │
└──────────────────────────────────────────────────────────┘

Python handles the logic you care about. Routes, validation rules, business logic—all in Python.

Rust handles the heavy lifting. HTTP parsing, JSON serialization, connection management—the parts that need to be fast.

The result: FastAPI's developer experience with systems-level performance.


Building from Source

Want to contribute or build from source?

git clone https://github.com/justrach/turboAPI.git
cd turboAPI

# Create venv with Python 3.13 free-threading
python3.13t -m venv venv
source venv/bin/activate

# Build the Rust extension
pip install maturin
maturin develop --release

# Install Python package
pip install -e ./python

# Run tests
PYTHON_GIL=0 python -m pytest tests/ -v

# Run benchmarks
python benches/python_benchmark.py
python tests/benchmark_comparison.py

Roadmap

Completed ✅

  • Rust HTTP core (Hyper/Tokio)
  • SIMD JSON serialization & parsing
  • Python 3.13 free-threading support
  • FastAPI feature parity (OAuth2, Depends, Middleware)
  • Radix tree routing with path parameters
  • Handler classification for optimized fast paths
  • Async handler optimization (Tokio + pyo3-async-runtimes)
  • WebSocket HTTP upgrade support

In Progress 🚧

  • HTTP/2 with server push
  • OpenAPI/Swagger auto-generation

Planned 📋

  • GraphQL support
  • Database connection pooling
  • Prometheus metrics
  • Distributed tracing
  • gRPC support

Community


License

MIT License. Use it, modify it, ship it.


Stop waiting for Python to be fast. Make it fast.

pip install turboapi

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

turboapi-0.5.2.tar.gz (440.2 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

turboapi-0.5.2-cp314-cp314-win_amd64.whl (2.1 MB view details)

Uploaded CPython 3.14Windows x86-64

turboapi-0.5.2-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.6 MB view details)

Uploaded CPython 3.14manylinux: glibc 2.17+ x86-64

turboapi-0.5.2-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (2.6 MB view details)

Uploaded CPython 3.14manylinux: glibc 2.17+ ARM64

turboapi-0.5.2-cp314-cp314-macosx_11_0_arm64.whl (2.3 MB view details)

Uploaded CPython 3.14macOS 11.0+ ARM64

turboapi-0.5.2-cp314-cp314-macosx_10_12_x86_64.whl (2.4 MB view details)

Uploaded CPython 3.14macOS 10.12+ x86-64

turboapi-0.5.2-cp313-cp313-win_amd64.whl (2.1 MB view details)

Uploaded CPython 3.13Windows x86-64

turboapi-0.5.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.6 MB view details)

Uploaded CPython 3.13manylinux: glibc 2.17+ x86-64

turboapi-0.5.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (2.6 MB view details)

Uploaded CPython 3.13manylinux: glibc 2.17+ ARM64

turboapi-0.5.2-cp313-cp313-macosx_11_0_arm64.whl (2.3 MB view details)

Uploaded CPython 3.13macOS 11.0+ ARM64

turboapi-0.5.2-cp313-cp313-macosx_10_12_x86_64.whl (2.4 MB view details)

Uploaded CPython 3.13macOS 10.12+ x86-64

File details

Details for the file turboapi-0.5.2.tar.gz.

File metadata

  • Download URL: turboapi-0.5.2.tar.gz
  • Upload date:
  • Size: 440.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for turboapi-0.5.2.tar.gz
Algorithm Hash digest
SHA256 1611f28ebeccb184e58f9f1e659cfc50208d74045f86a2492d78a088140964f7
MD5 e362f402450ad6e21bf6b5bd752aede5
BLAKE2b-256 4ed9b4b44894a1afbbe1460fdfbe7b25804300eedf30d733018e7c4757353c17

See more details on using hashes here.

File details

Details for the file turboapi-0.5.2-cp314-cp314-win_amd64.whl.

File metadata

  • Download URL: turboapi-0.5.2-cp314-cp314-win_amd64.whl
  • Upload date:
  • Size: 2.1 MB
  • Tags: CPython 3.14, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for turboapi-0.5.2-cp314-cp314-win_amd64.whl
Algorithm Hash digest
SHA256 49fed868fb7cb214bb894f40e6c89aa7b0829a890648637839d1834de058ad5d
MD5 59ec57c4aa3f2999e57220ea1dcf836b
BLAKE2b-256 05874e1261f88fdef7d313646a6c279338f901ae0ad8c2e078b729f2a35e2ae7

See more details on using hashes here.

File details

Details for the file turboapi-0.5.2-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for turboapi-0.5.2-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 2297ed40d48bed693591ac23412f30d42e22077b5d3cc4a23543f79f4317f0bc
MD5 adf9c22660bda54359c4865d73e020a3
BLAKE2b-256 484496d6ec66bc7d089e7e6d0b5411b994d39e88fffe9f57a92ef9c62a630c91

See more details on using hashes here.

File details

Details for the file turboapi-0.5.2-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.

File metadata

File hashes

Hashes for turboapi-0.5.2-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Algorithm Hash digest
SHA256 d379e822362299986d77e526cfb842187192018480cb8495e7cedd82e709c295
MD5 8ae567a8ca0d4c076b12ee5760b9d65e
BLAKE2b-256 d5e5d5326ee5c5455fa62c9f3b19273154f6233f61c648bc89bdbb7c9c7d6598

See more details on using hashes here.

File details

Details for the file turboapi-0.5.2-cp314-cp314-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for turboapi-0.5.2-cp314-cp314-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 c807a935609f0be85519d1286c2885b7e37ea01933275aa23b7d6b262bb60afd
MD5 1d1da2c7db66f4b33c169d45f1fef716
BLAKE2b-256 704c5238ed4337edbe85f1416605a990a9699f1316181d1a2f2116daf30f06d5

See more details on using hashes here.

File details

Details for the file turboapi-0.5.2-cp314-cp314-macosx_10_12_x86_64.whl.

File metadata

File hashes

Hashes for turboapi-0.5.2-cp314-cp314-macosx_10_12_x86_64.whl
Algorithm Hash digest
SHA256 6e4f9af41bd8b767d32dc0ef882ffad3e97488034b84f215e316fc9ddaf64483
MD5 4032bbd6df3bf760fdfd50722f9f6fdd
BLAKE2b-256 2bed8959bcb2527ab958fe3350e70e390536dd95b9c024dc9193947942eb5c06

See more details on using hashes here.

File details

Details for the file turboapi-0.5.2-cp313-cp313-win_amd64.whl.

File metadata

  • Download URL: turboapi-0.5.2-cp313-cp313-win_amd64.whl
  • Upload date:
  • Size: 2.1 MB
  • Tags: CPython 3.13, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for turboapi-0.5.2-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 cefc40de34716498be7dca7a8dc0237341e0c189668a0000341b699c110f970d
MD5 419e56ee1887136149b116087a8586b6
BLAKE2b-256 b76fa549028cd0ebccc6370ee1d5efe19deba41d701c8de28e9cf1d56d4f6999

See more details on using hashes here.

File details

Details for the file turboapi-0.5.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for turboapi-0.5.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 0a46f544da42304eed1b72ae1a357436c72b57a26a778974162832475294f0c7
MD5 27eb45e492e4b226f74da3ab5bd6c31d
BLAKE2b-256 af230c30e9f537596e86b61e4a34299fa98536c8131fb72634a9c1767813cd34

See more details on using hashes here.

File details

Details for the file turboapi-0.5.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.

File metadata

File hashes

Hashes for turboapi-0.5.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Algorithm Hash digest
SHA256 59323f0415217367536c9c62620e56f6d0976d34797bbeef30492f636c6d8814
MD5 c208c93a386e2561212a20c036bf40f2
BLAKE2b-256 2ae3670e702e575bd1caa354580b1c343d11be606b1404b3aa826358f6f93c71

See more details on using hashes here.

File details

Details for the file turboapi-0.5.2-cp313-cp313-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for turboapi-0.5.2-cp313-cp313-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 b2a5e36079d7907b9253cd407fd343c12a9f7cafed2633469ec5759b1b01ad4f
MD5 5a76ff59beeb68f16d2af9a3aaf6d4c2
BLAKE2b-256 11f19682d63635c1997930e58df9b1cd8d96f2ae88a109fd996f93307cffd35f

See more details on using hashes here.

File details

Details for the file turboapi-0.5.2-cp313-cp313-macosx_10_12_x86_64.whl.

File metadata

File hashes

Hashes for turboapi-0.5.2-cp313-cp313-macosx_10_12_x86_64.whl
Algorithm Hash digest
SHA256 aa71866198eebba03a7adfd46b61c003281165584898b02ca0ac0e0e9e77ad31
MD5 1509e4961bb97b7dd1cbe42722f4d7ea
BLAKE2b-256 feeca27112fd8aa8fc704f70d9346e3a94f4a95ec2ed7c7262d8316822217fb8

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page