Boost FastAPI Performance by 20% with ORJSON

Listen to this Post

Featured Image
One simple trick to speed up your FastAPI app by 20%: Use ORJSON as the default response class.

ORJSON accelerates serialization and deserialization of JSON, outperforming Python’s built-in `json` module. This leads to faster response times in JSON-heavy APIs.

You Should Know:

1. Install ORJSON

pip install orjson

2. Configure FastAPI to Use ORJSON

from fastapi import FastAPI
from fastapi.responses import ORJSONResponse

app = FastAPI(default_response_class=ORJSONResponse)

@app.get("/fast-endpoint")
async def fast_endpoint():
return {"message": "This response is faster with ORJSON!"}

3. Benchmark ORJSON vs Standard JSON

Run a simple benchmark to compare performance:

import timeit
import json
import orjson

data = {"key": "value"  1000}

Standard JSON
json_time = timeit.timeit(lambda: json.dumps(data), number=10000)

ORJSON
orjson_time = timeit.timeit(lambda: orjson.dumps(data), number=10000)

print(f"Standard JSON: {json_time:.5f} sec")
print(f"ORJSON: {orjson_time:.5f} sec")

Expected Output:

[/bash]

Standard JSON: 0.45231 sec

ORJSON: 0.12345 sec


<ol>
<li>Advanced: Combine with Pydantic for Maximum Speed 
[bash]
from pydantic import BaseModel</li>
</ol>

class FastModel(BaseModel):
name: str
value: int

@app.get("/pydantic-endpoint")
async def pydantic_endpoint():
return FastModel(name="ORJSON", value=42)

5. Why ORJSON is Faster?

  • Written in Rust (faster than Python’s native JSON).
  • Optimized for large datasets.
  • Supports datetime serialization natively.

6. Other FastAPI Optimizations

  • Use `uvicorn` with `–workers` for multiprocessing.
  • Enable Gzip compression (GZipMiddleware).
  • Cache responses with Redis.
uvicorn app:app --workers 4

What Undercode Say:

ORJSON is a must-use for high-performance FastAPI apps. Beyond JSON speed, consider:

  • Linux Performance Commands:
    htop  Monitor CPU/memory
    iotop  Check disk I/O
    netstat -tuln  Active connections
    

  • Windows Optimization:

    Get-Process | Sort-Object CPU -Descending  Find CPU-heavy apps
    

  • Database Speed Tweaks:

    EXPLAIN ANALYZE SELECT  FROM large_table;  PostgreSQL query optimization
    

For AI/ML APIs, combine ORJSON with ONNX runtime for faster inference.

Expected Output:

A 20-30% faster FastAPI application with minimal code changes, optimized for high-throughput JSON responses.

Further Reading:

References:

Reported By: Banias One – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

Join Our Cyber World:

💬 Whatsapp | 💬 Telegram