Skip to content

Performance

Practical guidance for maximizing throughput, reducing latency, and optimizing resource utilization in Kirak applications.


Database connection pooling is the most significant performance lever in a deployed Kirak application.

{
"database": {
"pool_min": 5,
"pool_max": 20,
"pool_recycle_seconds": 3600
}
}
Setting Default Production Recommendation Description
database.pool_min 1 5 Minimum idle connections kept open. Set to your baseline concurrent demand.
database.pool_max 10 20 - 50 Maximum connection ceiling per worker process.
database.pool_recycle_seconds 3600 1800 - 3600 Periodically recycles idle connections to prevent silent disconnects by firewalls or MySQL wait_timeout.

Calculate pool_max per worker process:

pool_max <= floor((db_max_connections - reserved_connections) / num_workers)

Example: A MySQL instance with max_connections = 150, 10 connections reserved for migrations and administrative tooling, and 4 worker processes:

pool_max <= floor((150 - 10) / 4) = 35

Terminal window
# Production with Gunicorn (Recommended)
gunicorn main:app \
-w 4 \
-k uvicorn.workers.UvicornWorker \
--bind 0.0.0.0:8000 \
--timeout 30
# Production with single Uvicorn per container
uvicorn main:app --host 0.0.0.0 --port 8000 --loop uvloop

Worker Sizing: Set worker count to 2 x CPU_cores + 1 for I/O-bound API workloads.

Container orchestrators (Docker, Kubernetes, AWS ECS) rely on non-zero exit codes to detect crashes and trigger restarts:

Execution Command Exit Code on Startup Failure Notes
uvicorn main:app (1 worker) Code 3 Clean container failure detected
uvicorn main:app --workers N (N > 1) Code 0 Uvicorn logs failure but parent exits 0, masking crashes from container runners
gunicorn -k uvicorn.workers.UvicornWorker Code 3 Gunicorn exits non-zero on worker boot failure

[!TIP] In containerized environments (Kubernetes, Cloud Run), run one Uvicorn process per container and scale horizontally by adding replicas. If running multiple workers on a single virtual machine, use Gunicorn to ensure crash failures exit with a non-zero code.


Record-by-record loops generate severe latency and database lock contention. Use Kirak’s bulk operations instead.

# Inefficient: N separate network round-trips
for record in records:
await kirak.create("orders", record)
# High Performance: Single multi-row INSERT statement
await kirak.create("orders", records, chunk_size=500, batch_size=200)
  • On MySQL, multi-row inserts are batched in single SQL statements.
  • On PostgreSQL and SQLite, batch_size is automatically capped at 32767 // num_columns (SQLite: 32766 // num_columns) to respect database parameter ceilings.
# Uniform change across matching rows:
await kirak.update("orders", {"status": "pending"}, {"status": "processing"})
# Individual changes per record in one transaction:
await kirak.update("orders", data=[
{"id": 1, "status": "shipped"},
{"id": 2, "status": "cancelled"}
])

Because Kirak does not use an ORM lazy-loader, automatic N+1 query patterns cannot occur in CRUD routing. However, avoid introducing them manually in after-hooks:

# Slow: N queries executed sequentially
@kirak.on("orders").hook("after_fetch")
async def enrich_orders_slow(result):
for order in result.get("data", []):
user = await kirak.fetch("users", {"id": order["user_id"]})
order["user"] = user["data"][0] if user["data"] else None
return result
# Fast: 1 batched query using the __in operator
@kirak.on("orders").hook("after_fetch")
async def enrich_orders_fast(result):
orders = result.get("data", [])
user_ids = list({o["user_id"] for o in orders if o.get("user_id")})
if not user_ids:
return result
users_resp = await kirak.fetch("users", {
"id__in": user_ids,
}, limit=len(user_ids), select=["id", "name", "email"])
user_map = {u["id"]: u for u in users_resp.get("data", [])}
for order in orders:
order["user"] = user_map.get(order["user_id"])
return result

Offset pagination (?page=1000&limit=10) degrades significantly on large tables because the database must scan and discard 10,000 index rows before returning 10.

Use cursor-based filtering on the primary key:

# High-performance cursor pagination
await kirak.fetch("events", {"id__gt": last_seen_id}, limit=50, order_by="id", order="ASC")

Avoid retrieving unused columns (especially large TEXT or JSON payloads):

await kirak.fetch("users", limit=100, select=["id", "email", "role"])

This reduces network serialization overhead, memory consumption, and database buffer usage.


Without Redis, rate limiting executes an atomic SQL upsert to the kirak_rate_limits table on every request.

With Redis (KIRAK_REDIS_URL):

  • Evaluates sliding-window quotas in sub-millisecond Lua operations.
  • Zero database write overhead on incoming requests.
  • Auto-expiring keys eliminate retention pruning background jobs.