Examples

Copy-paste ready snippets

Common integrations for Python and TypeScript.

Python

FastAPI with PostgreSQL

python

Production FastAPI app with Postgres storage.

example.pypython
from fastapi import FastAPI
from halt import RateLimiter, presets
from halt.stores.postgres import PostgresStore
from halt.adapters.fastapi import HaltMiddleware

app = FastAPI()
store = PostgresStore(connection_string="postgresql://user:pass@localhost/db")

limiter = RateLimiter(store=store, policy=presets.PUBLIC_API)
app.add_middleware(HaltMiddleware, limiter=limiter)

TypeScript

Express with MongoDB

typescript

Express API with MongoDB storage backend.

example.tstypescript
import express from 'express';
import { RateLimiter, presets } from 'halt';
import { MongoDBStore } from 'halt/stores/mongodb';
import { haltMiddleware } from 'halt/express';

const app = express();
const store = new MongoDBStore({ connectionString: 'mongodb://localhost:27017', database: 'halt' });

const limiter = new RateLimiter({ store, policy: presets.PUBLIC_API });
app.use(haltMiddleware(limiter));

Python

SaaS with Quotas

python

Multi-tenant quotas + penalties.

example.pypython
from halt import RateLimiter, presets
from halt.core.quota import QuotaManager, QUOTA_PRO_MONTHLY
from halt.stores.postgres import PostgresStore

store = PostgresStore(connection_string="...")
quota_manager = QuotaManager(store)

def check_and_consume(user_id: str):
    allowed, quota = quota_manager.check_quota(user_id, QUOTA_PRO_MONTHLY)
    if not allowed:
        return {"error": "Quota exceeded"}
    quota_manager.consume_quota(user_id, QUOTA_PRO_MONTHLY)
    return {"ok": True}

TypeScript

Next.js API Route

typescript

Next.js App Router middleware.

example.tstypescript
// app/api/data/route.ts
import { withHalt } from 'halt/next';
import { InMemoryStore, presets } from 'halt';

const store = new InMemoryStore();

export const GET = withHalt(async () => {
  return Response.json({ data: "ok" });
}, { store, policy: presets.PUBLIC_API });

TypeScript

DynamoDB with Penalties

typescript

AWS DynamoDB storage + abuse detection.

example.tstypescript
import { RateLimiter, presets } from 'halt';
import { DynamoDBStore } from 'halt/stores/dynamodb';
import { PenaltyManager, PENALTY_MODERATE } from 'halt/core/penalty';

const store = new DynamoDBStore({ tableName: 'rate_limits', region: 'us-east-1' });
const penaltyManager = new PenaltyManager(store, PENALTY_MODERATE);

Python

Multi-algorithm mix

python

Different algorithms per endpoint.

example.pypython
from halt import RateLimiter, Policy, Algorithm, InMemoryStore

store = InMemoryStore()
policies = {
    "public": Policy(name="public", limit=100, window=60, algorithm=Algorithm.TOKEN_BUCKET),
    "auth": Policy(name="auth", limit=5, window=60, algorithm=Algorithm.FIXED_WINDOW),
}