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.21.tar.gz (488.4 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.21-cp314-cp314t-macosx_11_0_arm64.whl (2.0 MB view details)

Uploaded CPython 3.14tmacOS 11.0+ ARM64

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

Uploaded CPython 3.14Windows x86-64

turboapi-0.5.21-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.21-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.21-cp314-cp314-macosx_11_0_arm64.whl (2.3 MB view details)

Uploaded CPython 3.14macOS 11.0+ ARM64

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

Uploaded CPython 3.14macOS 10.12+ x86-64

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

Uploaded CPython 3.13Windows x86-64

turboapi-0.5.21-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.21-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.21-cp313-cp313-macosx_11_0_arm64.whl (2.3 MB view details)

Uploaded CPython 3.13macOS 11.0+ ARM64

turboapi-0.5.21-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.21.tar.gz.

File metadata

  • Download URL: turboapi-0.5.21.tar.gz
  • Upload date:
  • Size: 488.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: maturin/1.9.4

File hashes

Hashes for turboapi-0.5.21.tar.gz
Algorithm Hash digest
SHA256 db5f16d3db669347e725102f25c17eff9b4d3809ac8e5447b875d4871895cc96
MD5 451f6010c39487dd898bb9f8379a55e5
BLAKE2b-256 feccbcddec2eb10b4a20d95ec149a51ca8d39a528a00189eb7b33e09405b9ffe

See more details on using hashes here.

File details

Details for the file turboapi-0.5.21-cp314-cp314t-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for turboapi-0.5.21-cp314-cp314t-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 54c4de4c0d405c571ee818dc68b9709feca736610a1bf2de4c428ac8993dcb7b
MD5 479cad0e7507d8c7a1d9370688ebf713
BLAKE2b-256 3cbc4518977874a16da1b8689b36a00071661f2ff7969614fc22e663d1936d88

See more details on using hashes here.

File details

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

File metadata

  • Download URL: turboapi-0.5.21-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.21-cp314-cp314-win_amd64.whl
Algorithm Hash digest
SHA256 5575d1bef3c60b101ebf693299562640b636bf187054c24172e4a01f82382f5b
MD5 0037624ef52a305bbcaf8f789ed72906
BLAKE2b-256 d934019adecdc073a8df38b8a27bc5d33e2926280149a0a7b611f5737b81bb8b

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for turboapi-0.5.21-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 a759cefa762e4859169ca7c38debda9d9899e390b27a7f0fdb7651ca9dcda83a
MD5 6122b5af302c099bb21fa4a19232fa7b
BLAKE2b-256 5d4be09a1a9243007fdfc279caac32eccaf4bfe3e5ac45361ee963c100698917

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for turboapi-0.5.21-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Algorithm Hash digest
SHA256 102107a9624639a15cdab41a3843cddfde0da499e66a397363a1d2e3a38cef95
MD5 ef0a6ed46c902d3523a851ece27820f5
BLAKE2b-256 e637b52167f8ebb5d627a47b278a5b99a615cbd2b6d93faf8a2e9f303c5d2b81

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for turboapi-0.5.21-cp314-cp314-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 c90bafb651451a9cd263e56d7c863e82082c74f875d3215b622ca919aefb1eb2
MD5 043f2987b859537b3aa66befacfb9560
BLAKE2b-256 3daaae22d82b19768f8684437073b7de7312749dfaf137fb1a21560763cd3493

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for turboapi-0.5.21-cp314-cp314-macosx_10_12_x86_64.whl
Algorithm Hash digest
SHA256 4d93db57d6507e65966b89ffe771c3bc265fc4d0b5abce198cf2b09e820cf3c2
MD5 a8718a5f513ede4084a2fb06e466c22f
BLAKE2b-256 85cf6d445dd7b1661a804115ab901d2f3531afeddb7f32c6ff09f93627967c21

See more details on using hashes here.

File details

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

File metadata

  • Download URL: turboapi-0.5.21-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.21-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 209932caa8f0467c6658f0028ca5583faea19f98d54fd0548bdcb6a4c4ad3ca3
MD5 79c99b15c68d25062210c189a757d1eb
BLAKE2b-256 f3f0bf1499940847a384c7f603fd7744a4b6cbd2b55a31a6ea501cf5df83ab80

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for turboapi-0.5.21-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 24b7fab754f9b0934c6e60384ce3a12d73313d713e4afc324d3332e56627c950
MD5 2efbea6914ccab2d0940b005e8339406
BLAKE2b-256 ead5729db48ced73153245adeeb7feca0250db8c091fdb787be7bfc4a3f55e7f

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for turboapi-0.5.21-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Algorithm Hash digest
SHA256 07b39fcd7a1ff3bbabde748a371087bc8f7f6c8348533958bd6fef51cc3749ae
MD5 42163aa300abfdaea132b3ad723a8c62
BLAKE2b-256 248a663d045d0f7e390ad387c9a8cfd3ce9e3e489050336e307e0c316e49f0d1

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for turboapi-0.5.21-cp313-cp313-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 ae0326cce2c3c3813e93e70d789a7eec7ffa38a106454fd1fc9539041f03c3e2
MD5 8a7a4b4e11c16f6910ce6f64f3778f26
BLAKE2b-256 9c8c281029f53fa61c4583f616e1498038180e02463ac8f28d1422949f45dd0a

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for turboapi-0.5.21-cp313-cp313-macosx_10_12_x86_64.whl
Algorithm Hash digest
SHA256 57d2bfbf8870f75222adfd8b8e810306bc9e673cd04e5750fd4416fd81931c3e
MD5 459676ad8c8928693886ed9fdb2cb84c
BLAKE2b-256 64d5f607af846d375fbcde9f675eb75a361bb825c06e4e6f1326c0345fe3b238

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