Rate Limiting & Subscriptions
Rate Limiting & Subscriptions¶
This document covers usage tracking, rate limiting, plan-based rate budgets, and how a tenant's plan status affects them. Plans, wallets and prices are in billing.md.
Overview¶
Huitzo tracks resource usage to ensure fair access and enable subscription-based billing:
┌─────────────────────────────────────────────────────────────────┐
│ Usage Tracking Layer │
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────────┐ │
│ │ Commands │ │ Storage │ │ LLM Tokens │ │
│ │ Executed │ │ Used │ │ Consumed │ │
│ └──────┬──────┘ └──────┬──────┘ └───────────┬─────────────┘ │
│ │ │ │ │
│ └────────────────┼──────────────────────┘ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────┐│
│ │ Redis Usage Counters ││
│ │ • Per-tenant counters with monthly rollover ││
│ │ • Real-time aggregation for dashboard display ││
│ └─────────────────────────────────────────────────────────────┘│
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────┐│
│ │ Subscription Enforcement ││
│ │ • SaaS: Stripe-based limits ││
│ │ • Self-hosted: Unlimited (customer manages infra) ││
│ └─────────────────────────────────────────────────────────────┘│
└─────────────────────────────────────────────────────────────────┘
Metrics Tracked¶
Command Execution¶
| Metric | Description | Tracked Per |
|---|---|---|
commands_executed |
Total commands run | Tenant, User, Pack |
commands_succeeded |
Successfully completed | Tenant, User, Pack |
commands_failed |
Failed executions | Tenant, User, Pack |
execution_time_seconds |
Total execution time | Tenant, User, Pack |
Storage Usage¶
| Metric | Description | Tracked Per |
|---|---|---|
storage_bytes |
Current storage used | Tenant, User, Pack |
storage_operations |
Read/write operations | Tenant, User |
storage_keys |
Number of stored keys | Tenant, User, Pack |
LLM Token Consumption¶
| Metric | Description | Tracked Per |
|---|---|---|
llm_input_tokens |
Tokens in prompts | Tenant, User, Pack, Model |
llm_output_tokens |
Tokens in responses | Tenant, User, Pack, Model |
llm_requests |
Total LLM API calls | Tenant, User, Pack, Model |
Concurrent Jobs¶
| Metric | Description | Tracked Per |
|---|---|---|
concurrent_jobs |
Currently running commands | Tenant, User |
peak_concurrent_jobs |
Max concurrent in period | Tenant |
Note: In v2, concurrent jobs are tracked for observability but not enforced. Future versions may enforce limits per plan.
Tracking Infrastructure¶
Redis Counter Structure¶
Usage counters are stored in Redis with automatic monthly rollover:
# Key pattern: huitzo:usage:{tenant_id}:{metric}:{period}
# Examples:
huitzo:usage:org_123:commands_executed:2026-01
huitzo:usage:org_123:llm_tokens:2026-01
huitzo:usage:org_123:storage_bytes:current
Counter Operations¶
# Internal SDK implementation (for reference)
async def increment_usage(tenant_id: str, metric: str, amount: int = 1):
"""Increment a usage counter."""
period = datetime.now().strftime("%Y-%m")
key = f"huitzo:usage:{tenant_id}:{metric}:{period}"
await redis.incrby(key, amount)
async def get_usage(tenant_id: str, metric: str, period: str = None) -> int:
"""Get current usage for a metric."""
period = period or datetime.now().strftime("%Y-%m")
key = f"huitzo:usage:{tenant_id}:{metric}:{period}"
return int(await redis.get(key) or 0)
Real-time Aggregation¶
The platform aggregates usage in real-time for dashboard display:
# Usage summary returned by GET /api/v1/usage
{
"period": "2026-01",
"tenant_id": "org_123",
"usage": {
"commands_executed": 1523,
"storage_bytes": 52428800, # 50 MB
"llm_tokens": {
"input": 125000,
"output": 87500,
"total": 212500
},
"concurrent_jobs": {
"current": 3,
"peak": 12
}
},
"limits": {
"commands_per_month": null, # null = unlimited for this plan
"storage_bytes": 1073741824, # 1 GB
"llm_tokens_per_month": 1000000,
"concurrent_jobs": 10 # tracked, not enforced in v2
},
"percentage_used": {
"storage": 4.88,
"llm_tokens": 21.25
}
}
Plans¶
There are no subscription tiers. D-024 CR27 deleted the personal membership
ladder (free/starter/pro/scale, SUBSCRIPTION_TIERS) and the tenant
tier column
(ADR-041 C7).
A tenant's plan comes from PLAN_CATALOG; no plan row means payg. Plans and
prices are in billing.md; the rate budgets each plan
carries are under Plan-based rate budgets. The
rate limiter never reads saas_subscriptions, and the retired per-user tier
column there has no reader at all.
Free-plan Hub guidance¶
When the limiter refuses a personal pay-as-you-go request, the Hub raises a
shell-level banner (apps/dashboard/src/components/layout/SaasRateLimitBanner.tsx)
rather than letting the request fail silently. It states the exact allowance that
was reached, names the pause as a plan limit rather than an outage, confirms that
saved work is unaffected, and counts down to the reset from the Retry-After /
X-RateLimit-Reset the limiter returned. (The heading keeps its anchor; the
personal free tier it was named for was deleted by D-024 CR27.)
It carries no upgrade call to action. Self-serve tier purchase was removed
with the legacy membership model (saas_0014) — there is no in-app path from
this banner to a higher allowance, so offering one would be a dead end. Buying
PAYG credits does not raise a plan's request or command ceiling either: credits
and rate limits are independent controls (credits meter spend, the limiter
bounds request rate). A member who needs a higher ceiling is an operator
conversation, not a checkout.
The banner is hosted-only (registrationMode === "saas-payment") and personal-
scoped: it renders only for a bucket: "user", tier: "payg" denial whose
tenant matches the acting tenant, so a Team plan's pooled refusal never
surfaces this copy.
Bring Your Own Key (BYOK)¶
Users can provide their own API keys for LLM providers (e.g., OpenAI, Anthropic) to bypass Huitzo's monthly token limits.
How it Works¶
- Configuration: The user adds their API key as a User Secret (e.g.,
OPENAI_API_KEY) for a specific pack. - Precedence: The Huitzo SDK (
ctx.llm) automatically detects and uses the user-provided key instead of the platform's shared key. - Billing:
- Usage via BYO keys consumes 0 Huitzo tokens.
- The user is billed directly by the LLM provider (e.g., directly by OpenAI) for that usage.
- Huitzo platform rate limits (requests per minute) still apply to ensure stability, but monthly quotas do not.
This lets heavy users pay providers directly: work on their own keys carries no Huitzo cost and is never refused by the wallet (billing: fail-closed outcomes).
Self-Hosted Mode¶
Self-hosted deployments have no usage limits. The customer manages their own infrastructure and is responsible for resource allocation.
# Self-hosted: All limits disabled
if settings.deployment_mode == "self_hosted":
limits = {
"commands_per_month": None,
"storage_bytes": None,
"llm_tokens_per_month": None,
"concurrent_jobs": None,
}
Self-hosted customers: - Pay a flat license fee (not usage-based) - Manage their own PostgreSQL/Redis capacity - Configure their own LLM API keys and budgets - Set internal limits via environment variables if desired
Stripe and the plan status (SaaS)¶
Billing state is never a Redis counter. It lives on the tenant's plan row,
tenant_subscriptions, and in the tenant's credit lots
(billing.md). There are no personal subscriptions: a personal
customer.subscription.* event changes no state.
A Team plan row moves through active → past_due → suspended → canceled, plus
read_only with HUITZO_TEAM_LIFECYCLE_V2_ENABLED on
(billing: Team lifecycle):
| Status | What changes |
|---|---|
past_due |
Nothing yet: a grace of 14 days, or 15 with the lifecycle v2 |
suspended |
Lifecycle v2: the allowance stops, paid lots and the plan's rate budgets stay. Flag off: the plan stops governing and members fall to per-user budgets |
read_only |
Writes refused with 402 tenant_read_only; billing, auth and staff routes stay open |
canceled |
The row stops governing and is kept for history |
Stripe is the source of truth only where a Stripe object exists: stripe_invoice
Team rows and card payments. A contract Team row has no Stripe object; the
hourly Team sweep and staff actions drive it.
| Webhook event | Effect |
|---|---|
invoice.payment_succeeded on a Team subscription |
Refreshes the anchors, opens the allowance period, and returns a past_due, suspended or read_only row to active |
customer.subscription.updated |
Status active: the same reactivation and anchor refresh. Status past_due or unpaid: the row moves to past_due and the grace is stamped. With the invoice rail on, plan_id is reconciled from the live subscription's Price |
customer.subscription.deleted |
The row moves to canceled |
Any invoice.* with metadata.purpose = team_usage_block |
Usage-block settlement, routed first; it never changes the plan status |
checkout.session.completed |
Top-up settlement, or a tenant card saved as the customer default |
Rate Limiting¶
Hosted SaaS tier limits¶
The SaaS extension classifies authenticated traffic into independent buckets so
ordinary dashboard reads cannot consume command or interactive-write capacity.
Self-hosted deployments do not mount this tier limiter. A second carve-out
(D-11, architecture/security.md#rate-limiting):
a hosted deployment running in PAYG mode with metering on does not enforce
this table either — the wallet's balance gate is the access policy there
instead.
| Endpoint class | Window | Budget |
|---|---|---|
auth_session |
minute | at least 120, or the plan's per-minute budget if higher |
bundle_asset |
minute | at least 300, or the plan's per-minute budget if higher (per user, never pooled) |
dashboard_read |
minute | the plan's per-minute budget |
interactive_write |
minute | the plan's per-minute budget (separate bucket) |
command_execution |
hour | the plan's commands/hour (unlimited on every plan) |
The budgets come from the acting tenant's plan in PLAN_CATALOG
(Plan-based rate budgets). auth_session uses a
120/minute floor so session hydration is not mistaken for logout.
bundle_asset is a GET of a dashboard's bundle files
(/api/v1/dashboards/{scope}/{name}/bundle/...). Those files are
content-addressed and served with Cache-Control: private, max-age=31536000,
immutable (apps/backend/src/backend/api/v1/dashboards.py), but a cold load
of a large dashboard fetches dozens at once. They get their own 300/minute
floor so loading a dashboard never spends, or is refused by, the read budget
its data calls need. A plan whose per-minute budget is unlimited stays
unlimited here too. The Hub shell's retry on a refused bundle is in
Dashboard loading. Public
endpoints are exempt before classification.
Plan-based rate budgets (D-024)¶
D-024 retires the free tier's rate limit
(ADR-041 C7).
Budgets come from each plan's RateBudget in PLAN_CATALOG
(extensions/saas/src/huitzo_ext_saas/plans.py,
ADR-041 C9),
and commands_per_hour is unlimited on every plan. TIER_LIMITS in
rate_limiter.py is derived from that catalog and keyed by plan id.
| Subject | Budget |
|---|---|
| Authenticated, no governing pooled plan | the acting tenant's plan; no row = payg: 60/min, unlimited commands |
Authenticated, governing pooled plan (team_*, house) |
pooled arm (below) |
| Anonymous | IP-keyed (anon:{ip}), payg per-minute budget |
- Why there is no command cap. Every platform-funded command reserves
against the acting tenant's wallet, which is the spend control; the limiter
only bounds request rate. The 5 commands/hour cap and the frozen membership
budgets (
starter/pro/scale,developer_preview) bounded the uncharged work of the personal-wallet model and were removed with it on 2026-10-09 (ADR-041 E3). - The acting tenant decides.
saas_subscriptionsis never read, and no membership tier raises a budget. Asuspendedorcanceledplan row resolves to payg. - Outages. If the plan cannot be resolved (Redis and the database both down, no stale copy), the request falls to the payg budget. Payg's command budget is unlimited, so a Redis outage lets commands through (the wallet reservation still gates them) and the per-minute classes fail open as before.
Registration limits (ADR-042 D9)¶
POST /api/v1/auth/register uses the same two primitives with the
fail_closed option, so a Redis outage answers 503 instead of letting every
request through. The limiter's Redis client has a 2s connect and socket
timeout, so an unresponsive Redis also answers 503 instead of hanging the
request.
| Limit | Default | Env override | Redis key | Response |
|---|---|---|---|---|
| Per client IP | 5 / 60s | HUITZO_REGISTER_IP_RATE_LIMIT_PER_MINUTE |
rl:pub:auth-register:<ip>:<window> |
429 |
| Global hourly breaker | 100 successful registrations | HUITZO_REGISTER_HOURLY_CAP |
cb:register:<hour-bucket> |
503, code: register_at_capacity |
| Redis outage | fails closed | HUITZO_RATE_LIMIT_ENABLED=false disables |
— | 503, code: rate_limiter_unavailable |
The client IP comes from the trusted-proxy
contract: X-Real-IP when
the transport peer is inside HUITZO_TRUSTED_PROXY_CIDRS (default loopback,
RFC 1918 and IPv6 unique-local, so nginx on a Docker bridge qualifies), the
peer otherwise. The backend never reads X-Forwarded-For; only the dashboard
edge does, from listed proxies (below). Every per-IP
limit on this page (login, register, coupon redeem, verification send and
verify, password reset and change, reauth, feedback) keys on this value. Only a
committed registration advances the breaker.
Client IP behind an HTTPS proxy¶
Behind an HTTPS proxy, the dashboard nginx's peer is the proxy. Unless nginx
restores the client, every user shares one per-IP bucket, and at the default
HUITZO_LOGIN_IP_RATE_LIMIT_PER_MINUTE=5 the 6th sign-in at a site in any
minute gets 429. The dashboard container's HUITZO_EDGE_TRUSTED_PROXIES lists
the proxies (IP addresses or CIDRs, comma-separated) whose X-Forwarded-For
names the client; nginx sends the rightmost entry that is not a listed proxy as
X-Real-IP.
| Deployment | HUITZO_EDGE_TRUSTED_PROXIES |
|---|---|
| No proxy: the dashboard is reached directly | empty, the default: trusts nothing |
Customer compose, https profile |
Caddy's fixed address on huitzo-network (172.16.231.10), written by install.sh (one hop) |
--external-tls, your proxy on the same host |
the huitzo-network gateway, the first address of HUITZO_NETWORK_SUBNET (172.16.231.1 by default), with Docker's default userland proxy. This trusts every process on the host that can reach the dashboard's port |
--external-tls, a load balancer in front of your proxy |
your proxy's address plus the load balancer's CIDR (a second hop), only if your proxy forwards the load balancer's X-Forwarded-For |
The shipped Caddyfile trusts no upstream. Caddy replaces the X-Forwarded-For
of a load balancer in front of it, so behind one the load balancer's address is
the client and all its users share one bucket. The container refuses to start
on a malformed entry, a hostname, a prefix wider than /8 (IPv4) or /16
(IPv6), the unspecified address (0.0.0.0 or ::, bare or with any prefix,
which covers 0.0.0.0/0 and ::/0), or a CIDR with host bits set such as
10.0.0.5/8 (write 10.0.0.0/8). The customer compose forwards
HUITZO_LOGIN_IP_RATE_LIMIT_PER_MINUTE to the backend when it is set in
.env. See the
trusted-proxy contract.
The registration-checkout breaker (#G16) and its per-IP limit were deleted with paid registration by the access-code fold (D-024 CR78).
Coupon redeem and verification limits (ADR-042 D9)¶
The signed-in coupon redeem and the verification send use the same
primitives, all failing closed (503 rate_limiter_unavailable on a Redis
outage; HUITZO_RATE_LIMIT_ENABLED=false disables them).
| Route | Limit | Default | Env override | Response |
|---|---|---|---|---|
POST /api/v1/coupons/redeem |
Per client IP | 5 / 60s | HUITZO_COUPON_REDEEM_IP_RATE_LIMIT_PER_MINUTE |
429 |
POST /api/v1/coupons/redeem |
Per signed-in user | 10 / hour | HUITZO_COUPON_REDEEM_USER_RATE_LIMIT_PER_HOUR |
429 |
POST /api/v1/coupons/redeem |
Global hourly breaker | 200 successful redemptions | HUITZO_COUPON_REDEEM_HOURLY_CAP |
503, code: coupon_redeem_at_capacity |
POST /api/v1/auth/verify-email/send |
Per client IP | 3 / hour | HUITZO_VERIFY_EMAIL_SEND_IP_RATE_LIMIT_PER_HOUR |
429 |
POST /api/v1/auth/verify-email/send |
Per signed-in user | 3 / hour | HUITZO_VERIFY_EMAIL_SEND_USER_RATE_LIMIT_PER_HOUR |
429 |
Coupon registration (POST /api/v1/auth/register with a coupon_code) is
covered by the registration limits above.
Feedback submission budgets¶
POST /api/v1/feedback
(spec §8) stacks a
per-user hourly budget on top of the per-IP fixed window — feedback is a
human channel, so both budgets are generous, and the FB-D10 per-submission
credit charge is the economic backstop. Both are tuning values in Settings.
| Setting | Value | Notes |
|---|---|---|
| Per-IP cap | 5 submissions / 60s (default) | check_ip_rate_limit, endpoint label feedback-submit |
| Env override | HUITZO_FEEDBACK_IP_RATE_LIMIT_PER_MINUTE |
apps/backend/src/backend/config.py::feedback_ip_rate_limit_per_minute |
| Per-user cap | 10 submissions / rolling hour (default) | Redis key rl:feedback_submit:user:<uid>:<window> |
| Env override | HUITZO_FEEDBACK_USER_RATE_LIMIT_PER_HOUR |
apps/backend/src/backend/config.py::feedback_user_rate_limit_per_hour |
| Response on trip | 429 |
error.details.code = "rate_limited", Retry-After set to the window remainder |
| Redis outage | fails open | Both budgets; the credit charge remains the floor |
Shared limits across processes (G24)¶
Every per-tenant, per-user and per-IP limit the core enforces lives in Redis,
so one budget holds across every backend process, replica and worker. A
process may keep its own count under a shared one, to bound its own memory
(listed below), but no tenant's budget lives only in one process. The
primitives are in
apps/backend/src/backend/ratelimit.py; each is one atomic Redis script, and
every key carries a TTL, so a key no request touches again disappears on its
own.
| Primitive | Shape | Key | TTL | Used by |
|---|---|---|---|---|
| Fixed window | INCR per window, the first hit sets the expiry |
rl:pub:<label>:<ip>:<window>; the per-user limits use their own rl: keys, named in their sections |
one window | the per-IP and per-user limits on this page |
| Token bucket | capacity tokens refilling at refill_per_second, timed by the Redis server clock |
rl:tb:<name>:<subject> |
the time a drained bucket takes to refill, plus one second | the runner channel's per-tenant bucket; the publish limits |
| Concurrency lease | one sorted-set member per call in flight, scored by its expiry | rl:lease:<name>:<subject> |
the longest lease it holds | a tenant's inline command executions; the managed-runner LLM gateway's calls per checkout |
Token bucket. A key that expires held a full bucket anyway, so expiry loses nothing. The bucket refills from the Redis server's clock, so processes with drifting clocks still agree.
Concurrency lease. Taking a place first drops every lease past its expiry, then admits the call only while fewer than the limit remain. Releasing removes the call's own lease. A process that dies holding a place cannot leak it: the lease expires, and the next acquire on that key drops it. Both users renew their lease while it is held: a lease lives 60 s and its holder pushes the expiry out every 20 s until it gives the place back. An inline execution renews until its slot is freed, teardown included. A gateway call renews for as long as it is open, however long a provider that trickles bytes or a container that reads slowly keeps it. A live holder never drops out of the count, and a process that dies stops renewing, so its places free within a minute. A renewal never revives a lease that already lapsed or was released.
Redis outage, per class¶
| Class | On a Redis outage | Limits |
|---|---|---|
| Abuse-sensitive | fails closed: 503, code: rate_limiter_unavailable |
registration, login (and the login-screen password change, which shares its budget), signed-in password change, forgot and reset, reauth, coupon redeem, verification send, publish |
| Ordinary request limit | fails open, with a logged warning | the runner channel's per-tenant bucket, which meanwhile spends from a per-process bucket of the same size; feedback, the sites TLS check and the setup-token failure count, which are served uncounted |
| Capacity guard | fails open, with a logged warning | a tenant's inline command executions and the gateway's calls per checkout; each process's own count of them still holds, so the children and memory it sizes stay bounded |
A fail-closed answer means no request gets through while the limiter cannot count it. A fail-open one means the request is served without the shared count. The Redis client has a 2 s connect and socket timeout, so a Redis that hangs takes the same branch as one that refuses the connection. A limiter logs each kind of outage (a refused or an admitted request, a failed release) with a traceback at most once a minute; the repeats go out at DEBUG.
When the reply to taking a lease is lost (a timeout after the script ran, or the caller cancelled), the lease may exist in Redis without its holder knowing. The limiter removes it in the background, so a slow Redis normally cannot leave a tenant's place taken until the lease lapses.
HUITZO_RATE_LIMIT_ENABLED=false turns off the fixed windows and the token
buckets, the runner channel's included, and the fail-closed limits with them.
Concurrency leases bound resource use, not request rate, so they stay on.
Publish limits¶
Publishing is limited per tenant and per user, so one account cannot flood the
Hub with packs and versions. Three routes spend from both budgets:
POST /api/v1/packs (create a pack), POST /api/v1/packs/{pack_id}/versions
(upload a version) and POST /api/v1/studio/builds/{build_job_id}/publish
(publish a Studio build). Going back to a version that must first be
restored (Activate Pack Version, directly
or through a dashboard's activate route) spends from them too, since a restore
installs a wheel as a publish does; going back to an installed version does
not. Each budget is a token bucket: its size is the burst, and it refills evenly
over the hour.
| Budget | Default | Env override | Redis key |
|---|---|---|---|
| Per tenant | 30 an hour | HUITZO_PUBLISH_TENANT_RATE_PER_HOUR |
rl:tb:publish-tenant:<tenant id> |
| Per user | 20 an hour | HUITZO_PUBLISH_USER_RATE_PER_HOUR |
rl:tb:publish-user:<user id> |
A request past either budget is refused with 429, code: publish_rate_limited
and Retry-After set to the time until the bucket holds a publish again. The
limits fail closed: a Redis outage answers 503 with
code: rate_limiter_unavailable, as registration does. Both answers come
before any work: no wheel is read, no request row is written.
HUITZO_RATE_LIMIT_ENABLED=false turns them off.
The user's budget is spent first and the tenant's second, so a request the tenant's budget refuses has already spent one of the user's. Because the limits come first, a publish that a later step refuses or answers without new work still spends: a member without developer mode, a member who neither owns the build nor is a tenant admin or owner, and a repeat click on a build whose publish request is already active (answered with that request). A member can therefore spend the tenant's budget without being able to publish, at most their own user budget an hour. An owner or admin who sees that can remove the member.
Some limits stay per process on purpose. They bound what one process can hold,
not what a tenant may do: the gateway's large-body places and forwarded-bytes
budget (memory), the per-process counts under the shared ones (a checkout's
gateway calls, a tenant's inline executions), the inline total
(HUITZO_INLINE_SPAWN_MAX_GLOBAL, children of one process), the stored-data
check's child slots (subprocesses on one replica), the local AI runtime's
request slots, and the bounded fan-out semaphores inside one request.
The SaaS plan limiter (huitzo_ext_saas.rate_limiter, the classes
above and the pooled arm)
is already one Redis counter per window and keeps its own outage policy. Its
Redis client has the same 2 s connect and socket timeout, so a Redis that hangs
takes that outage path instead of stalling the request.
Rate Limit Headers¶
HTTP/1.1 200 OK
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1706012345
Rate Limit Response¶
HTTP/1.1 429 Too Many Requests
Retry-After: 42
X-RateLimit-Limit: 5
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1784235600
{
"success": false,
"error": {
"code": "rate_limited",
"message": "Rate limit exceeded for command_execution; retry after 42s.",
"tier": "payg",
"endpoint_class": "command_execution",
"bucket": "user",
"limit": 5,
"remaining": 0,
"reset": 1784235600,
"retry_after": 42
}
}
tier names the resolved plan id (payg, team_s, house, …). bucket names the
accounting domain that denied the request: user, pool, or
member_ceiling. Clients must honor Retry-After and may use the other fields
for explanation and observability; they must not infer a logout from a 429.
Hub guidance on a personal denial¶
For an authenticated hosted user whose personal payg user bucket is
exhausted, the Hub shows one persistent, dismissible notice
(Free-plan Hub guidance). Team pool/fairness
denials and other plans retain normal retry behavior. The shell observes
structured 429s from every same-origin /api/v1/* browser request,
including embedded dashboard SDK traffic; consuming code still receives the
original response unchanged.
Team pooled rate limiting (ADR-027, ADR-041)¶
For a tenant whose plan row governs (status active or past_due; with
HUITZO_TEAM_LIFECYCLE_V2_ENABLED on, also suspended and read_only, whose
degradation is the allowance and the write refusal, not the budget), the SaaS
tier limiter switches from per-user budgets
to tenant-pooled budgets with a per-member fairness ceiling. The budgets
are each plan's RateBudget in PLAN_CATALOG
(extensions/saas/src/huitzo_ext_saas/plans.py,
ADR-041 D1).
See ADR-027 for the
cache and bucket design; extensions/saas/src/huitzo_ext_saas/plan_resolution.py
and rate_limiter.py are the implementations.
Plan resolution — tenant overrides user¶
# pseudocode — request-time resolution order (conceptual)
1. Redis fresh cache entsub:v2:{tenant_id} (TTL ~60s)
2. DB tenant_subscriptions row → re-prime BOTH cache keys
3. Redis stale cache entsub:v2:stale:{tenant_id} (24h ceiling, served only on DB error)
4. per-user path payg (double failure — loudly logged)
- A non-governing row (
canceled, andsuspendedwhile the lifecycle v2 is off) and a tenant with no row (negative-cached) fall through to the per-user path:payg. - Write-through, never delete: every writer of
tenant_subscriptionsre-primes both cache keys to the post-commit row via the single exported helper (reprime_plan_cache). The stale key is only ever overwritten. - The
v2key segment versions the cached struct's wire format (PLAN_CACHE_KEY_VERSION). A change to the serialized field set bumps it, so during a rolling deploy old and new pods never read each other's entries as malformed; the old keys expire on their TTL. - A
plan_idthat is not in the catalog logs an error and resolves — at refresh time — to payg budgets, never the highest plan and never an exception. A plan whose budget does not pool (payg,partner_managed) takes the per-user path.
Pooled buckets¶
| Endpoint class | Subject / Redis key | Budget |
|---|---|---|
auth_session |
per-user (existing key shape) | max(120, per_member_rpm_ceiling) |
bundle_asset |
per-user (existing key shape); never draws on the tenant pool | max(300, per_member_rpm_ceiling) |
dashboard_read |
pool rl:{class}:tenant:{tid}:{win} + ceiling rl:{class}:member:{uid}:{win} |
pool = pooled_requests_per_minute; ceiling = per_member_rpm_ceiling |
interactive_write |
same shapes, separate bucket | same dimensions |
command_execution |
pool only | commands_per_hour (-1 = unlimited; unlimited on every plan) |
| anonymous | anon:{ip} |
untouched |
- The per-member ceiling is checked first; a ceiling denial never increments the pool, so a noisy member cannot drain the crew's budget.
- Success-path
X-RateLimit-*headers report the pool limit withremaining = min(pool_remaining, ceiling_remaining); a 429 names the denying bucket in the structured body. - Redis outage policy is unchanged, now crew-wide:
command_executionfails closed, the interactive classes fail open.
Member money-in gate¶
The wallet money writes of a plan tenant are refused server-side. The gate is not a rate limit, but it keys on the same plan row:
| Plan row | Result |
|---|---|
team_* |
409 team_managed_billing. With HUITZO_TEAM_CARD_OVERFLOW_ENABLED on, the tenant's owner and admins may top up and arm auto-recharge on the tenant card |
house |
409 house_plan_no_topup |
None, or canceled (payg) |
The owner and admins pass; a member gets 403 |
The full route-by-role table is in REST: tenant wallet and billing: who can move money.
Usage views¶
| Surface | Who | What |
|---|---|---|
GET /api/v1/billing/usage |
Any member | Commands in the last 30 days, seats and packs against the tenant's quotas, and a plan tenant's plan block (REST) |
GET /api/v1/billing/allowance |
Any member | The Team period's units (REST) |
GET /api/v1/wallet/usage/summary, /charges, /by-dimension, /daily |
Owner and admins (members: their own charges) | Priced usage against the wallet (REST) |
GET /api/v1/admin/usage/tenants |
Platform staff | Core metered usage per tenant (REST) |
Past a limit¶
There is no overage and no soft limit. Each limit refuses at the point it is checked:
| Limit | Result |
|---|---|
| No allowance and no credits | 402 INSUFFICIENT_CREDITS at the next reservation (billing: fail-closed outcomes) |
| Request rate | 429 rate_limited, with Retry-After |
| A tenant quota (seats, packs, monthly commands) | 409 tenant_quota_exceeded |
Best Practices¶
For Pack Developers¶
- Batch operations when possible - Reduce command count
- Use appropriate LLM models - gpt-4o-mini costs less than gpt-4o
- Implement caching - Reduce redundant LLM calls
- Clean up old storage - Delete data you no longer need
For Platform Administrators¶
- Monitor usage trends - Use Prometheus metrics
- Set up alerts - Notify before limits are hit
- Review by-pack usage - Identify inefficient packs
- Plan capacity - Scale infrastructure with growth
Related Documentation¶
- Configuration Reference – Environment variables
- Observability Guide – Monitoring setup
- Architecture Overview – System design