[hypequery](https://hypequery.com/) › Multi-Tenant ClickHouse Analytics in Python | hypequery
Index for agents: https://hypequery.com/llms.txt
Canonical page: https://hypequery.com/clickhouse-python-multi-tenant

> Scope every ClickHouse query to the right customer from Python. Declare a tenant key once; hypequery adds the filter and refuses untrusted tenants.

[Open sourceApache 2.0](https://github.com/hypequery/hypequery)

Python multi-tenancy

# Multi-tenant ClickHouse analytics in Python, without a filter to forget

Declare the tenant column once on the dataset. Every query from your jobs, FastAPI endpoints, and agents runs inside one customer's data, and a query without a trusted tenant fails instead of returning everyone's rows.

[Get started ](https://hypequery.com/docs/quick-start#python)[Read the tenancy docs](https://hypequery.com/docs/python/datasets/multi-tenancy)

Isolation

Fail-closed tenant key

Tenant source

Authenticated principal only

Runs in

Jobs, FastAPI, agents

## One missing WHERE leaks a customer

When every query has to remember `WHERE org_id = %s`, the one that forgets returns another customer’s data. Code review is the only guard.

## The tenant ends up in the request body

APIs that accept a tenant as a parameter let any caller ask for any tenant. The scope has to come from authentication, not input.

## Each surface re-implements the rule

Background jobs, API routes, and AI agents all need the same scoping, and each one is a new place to get it wrong.

Declare it once

## The dataset owns the tenant rule

Set `tenant_key` on the dataset and hypequery adds the tenant predicate to every query it plans. The tenant comes from a trusted execution context, never from the query itself.

- A query without a tenant fails with `tenant-required`
- Filtering on the tenant field from a query is rejected
- `analytics.for_tenant(...)` binds a client to one tenant for a whole request
- The same rule applies to relationships and joined datasets

datasets.py

### Tenant key on the dataset

analytics/datasets.py

```
from hypequery.datasets import Dataset, dimension, measure

orders = Dataset(
    name="orders",
    source="orders",
    tenant_key="org_id",  # every query is scoped by this column
    time_key="created_at",
    dimensions={
        "status": dimension("string"),
        "country": dimension("string"),
    },
    measures={
        "revenue": measure.sum("amount"),
        "order_count": measure.count("order_id"),
    },
)
```

Ordinary Python you review and version with the rest of your app.

HTTP endpoints

## Serve it with the tenant taken from auth

hypequery Serve resolves the tenant from the authenticated principal. No header, query parameter, or body field can set or change it.

Mark an endpoint `tenant="required"` to refuse callers without a tenant, or `"forbidden"` for internal, tenant-free routes.

A request body that tries to set a tenant is rejected with a validation error, so the scope can only narrow, never widen.

api.py

### Tenant-scoped dataset endpoint

analytics/api.py

```
from hypequery.datasets import tenant
from hypequery.serve import (
    EndpointPolicy, HttpSecurity, Principal, add_dataset_endpoint,
    create_api,
)

def resolve_tenant(principal: Principal):
    org_id = lookup_org(principal.subject)  # your code
    return tenant(org_id) if org_id else None

api = create_api(
    auth=authenticate,
    tenant=resolve_tenant,
    security=HttpSecurity(allowed_hosts=("analytics.example.com",)),
)
add_dataset_endpoint(
    api,
    "/datasets/orders/query",
    dataset=orders,
    client=analytics,
    policy=EndpointPolicy(
        tenant="required"
    ),  # tenant-free callers are refused
)
# Mount api in FastAPI, Django, Flask, or any ASGI or WSGI server.
```

A resolver can return one tenant or none. It cannot grant several tenants or all of them.

Where teams usually get stuck

## Questions teams ask

### Row-level security for ClickHouse in Python

hypequery enforces tenant scope in the query it generates. You can still add ClickHouse row policies underneath as a second layer.

### Multi-tenant FastAPI analytics

Dataset endpoints take the tenant from your authenticator, so every customer-facing chart is scoped the same way.

### Tenant isolation for background jobs

Jobs pass a trusted tenant through `ExecutionContext`. A job that forgets fails loudly instead of aggregating every customer.

### Same rules for AI agents

Agents connected over MCP run as one principal with one tenant, using the same datasets and the same scope.

Examples

## Runnable examples

Every example runs against the same seeded ClickHouse dataset. Scaffold one with `npx @hypequery/cli create <slug> -y`, or browse the [full list](https://hypequery.com/examples).

[Example · Python](https://hypequery.com/examples/django-analytics)

### [Django analytics on ClickHouse: ORM for app data, typed datasets for metrics](https://hypequery.com/examples/django-analytics)

[Keep your Django models in SQLite or Postgres and serve ClickHouse analytics from typed hypequery datasets, scoped to request.user's organization.](https://hypequery.com/examples/django-analytics)

[PythonDjangoClickHouseAnalytics APIMulti-tenantSaaS analytics](https://hypequery.com/examples/django-analytics)

[Open example](https://hypequery.com/examples/django-analytics)

[Example · Python](https://hypequery.com/examples/fastapi-analytics-api)

### [A FastAPI analytics API on ClickHouse with tenant-scoped datasets](https://hypequery.com/examples/fastapi-analytics-api)

[Serve governed ClickHouse analytics from FastAPI: datasets defined once in Python, query endpoints mounted beside your routes, tenant fixed by the token.](https://hypequery.com/examples/fastapi-analytics-api)

[PythonFastAPIClickHouseAnalytics APIMulti-tenantSaaS analytics](https://hypequery.com/examples/fastapi-analytics-api)

[Open example](https://hypequery.com/examples/fastapi-analytics-api)

Further reading

## Go deeper where it actually helps

### [Dataset multi-tenancy](https://hypequery.com/docs/python/datasets/multi-tenancy)

[Tenant keys, execution context, and tenant-bound clients.](https://hypequery.com/docs/python/datasets/multi-tenancy)

[Open guide](https://hypequery.com/docs/python/datasets/multi-tenancy)

### [Serve multi-tenancy](https://hypequery.com/docs/python/multi-tenancy)

[Resolve tenants from the principal and require them per endpoint.](https://hypequery.com/docs/python/multi-tenancy)

[Open guide](https://hypequery.com/docs/python/multi-tenancy)

### [Authentication](https://hypequery.com/docs/python/authentication)

[Bearer tokens, API keys, and principals.](https://hypequery.com/docs/python/authentication)

[Open guide](https://hypequery.com/docs/python/authentication)

### [Multi-tenant analytics in TypeScript](https://hypequery.com/clickhouse-multi-tenant-analytics)

[The same model on the TypeScript side.](https://hypequery.com/clickhouse-multi-tenant-analytics)

[Open guide](https://hypequery.com/clickhouse-multi-tenant-analytics)

Related pillars

[Embedded analytics](https://hypequery.com/embedded-analytics)[ClickHouse with Python](https://hypequery.com/clickhouse-python)[ClickHouse with FastAPI](https://hypequery.com/clickhouse-fastapi)[MCP for Python backends](https://hypequery.com/clickhouse-python-mcp)[Python semantic layer](https://hypequery.com/python-semantic-layer)

Next step

## Add a tenant key to one dataset

Define one dataset with `tenant_key`, run a query without a tenant, and watch it refuse.

Open source, and it runs in your own backend. Want it hosted?

[Get started ](https://hypequery.com/docs/quick-start#python)[Tenancy docs](https://hypequery.com/docs/python/datasets/multi-tenancy)
